diff --git a/.github/dependabot.yml b/.github/dependabot.yml index e81ed07df..5a41a73aa 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -17,10 +17,8 @@ updates: # rather than landing inside an aggregated `chore(deps)` PR. - "turso_core" - "turso_*" - # monty is pre-1.0 and breaks its embedding API on most 0.0.x bumps - # (0.0.19 dropped `max_allocations` and added a print-collect cap). - # Keep it standalone so the builtin rewrite each bump needs is - # reviewed on its own, not buried in an aggregated `chore(deps)` PR. + # Monty deps (pulled in by the bashkit-monty forks) change the + # embedding API often; keep them out of aggregated PRs. - "monty" - "monty-*" # Surface turso bumps individually with a label that flags them for @@ -29,7 +27,7 @@ updates: # standalone delivery. ignore: # num-bigint is hard-pinned to 0.4.x in crates/bashkit-python: monty - # (0.0.19) depends on num-bigint 0.4, and py_to_monty hands a + # (1.4) depends on num-bigint 0.4, and py_to_monty hands a # `num_bigint::BigInt` to `MontyObject::BigInt`. A 0.5 bump makes the two # BigInt types mismatch and fails to compile. Block major/minor jumps # (0.4 -> 0.5) while still allowing 0.4.x patch updates, until monty @@ -38,24 +36,14 @@ updates: update-types: - "version-update:semver-major" - "version-update:semver-minor" - # monty/monty-types are held at 0.0.19 for a security reason, not just an - # API-churn one. 0.0.21 replaced host-side memory accounting with a probe - # of globals that only the `monty-alloc` global allocator writes, so an - # embedder that cannot install a process-wide allocator — which bashkit, - # as a library and a CPython extension module, cannot — silently loses the - # Python sandbox's `max_memory` ceiling. Four threat-model regression - # tests fail on the bump. Without these entries dependabot reopens the - # same broken PR every week (#2296, #2297). - # Drop the ignores once monty exposes an embedder-usable memory bound; - # see knowledge/runtimes/python-builtin.md § Upgrade blocker. + # monty/monty-types are not used from crates.io: bashkit embeds patched + # forks (crates/bashkit-monty, crates/bashkit-monty-types) that add a + # per-VM memory probe and a checkpoint hook. A registry bump would not + # touch them; upgrade by re-copying upstream source and re-applying the + # patch. See knowledge/runtimes/python-builtin.md. - dependency-name: "monty" - dependency-name: "monty-types" - # The python `re` gate parses user code with the same ruff parser Monty - # 0.0.19 bundles. A standalone bump would let the gate's grammar drift - # from the executor's, and code the gate fails to parse is passed - # through. Move these only together with monty. - - dependency-name: "ruff_python_parser" - - dependency-name: "ruff_python_ast" + - dependency-name: "monty-macros" # wasmtime is pinned exactly (=48.0.6): the `cpython` feature embeds a # module precompiled by build.rs, and a precompiled module loads only @@ -69,30 +57,9 @@ updates: # `idna`'s Unicode back end, and 1.0.x is the "no back end" stream that # keeps the 21-crate ICU4X stack out of the tree. Dependabot would read # the pin as staleness and bump it straight back to 1.2.x. See the - # rationale comment above [patch.crates-io] in the root Cargo.toml. + # rationale comment at the end of the root Cargo.toml. - dependency-name: "idna_adapter" - # get-size2 is not a dependency bashkit uses — no bashkit source - # references it. It is declared under the `python` feature purely to - # hold the *whole graph* at 0.10.1, which is the last version that - # implements `GetSize` for compact_str 0.9. monty 0.0.19's - # ruff_python_ast derives `get_size2::GetSize` on nodes holding a - # `CompactString` from compact_str 0.9, so any get-size2 >= 0.10.2 - # (which moved those impls to compact_str 0.10) leaves the derive with - # no impl: - # - # error[E0277]: the trait bound `CompactString: GetSize` is not - # satisfied --> ruff_python_ast-0.0.3/src/nodes.rs:411:41 - # note: there are multiple different versions of crate `compact_str` - # - # Bumping bashkit's declared version does not just fail to help, it - # removes the constraint that keeps ruff's copy pinned, letting it - # float to 0.10.3 and break (#2381, all 22 build jobs red). Ignore - # outright rather than by update-type: the breaking move was a patch - # release. Drop this once monty's ruff moves to compact_str 0.10; the - # pin comment sits next to the dep in crates/bashkit/Cargo.toml. - - dependency-name: "get-size2" - # branches is not a dependency bashkit uses — no bashkit source # references it. It is declared under the `sqlite` feature purely to turn # ON `branches/std` for the whole graph: `turso_core` depends on diff --git a/.github/workflows/apidocs-drift.yml b/.github/workflows/apidocs-drift.yml index 4e4c7939a..7756fa669 100644 --- a/.github/workflows/apidocs-drift.yml +++ b/.github/workflows/apidocs-drift.yml @@ -75,7 +75,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 with: diff --git a/.github/workflows/bash-oracle.yml b/.github/workflows/bash-oracle.yml index 66d9f0d12..62fd0ea63 100644 --- a/.github/workflows/bash-oracle.yml +++ b/.github/workflows/bash-oracle.yml @@ -38,7 +38,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/builtins-drift.yml b/.github/workflows/builtins-drift.yml index 024c0d6f5..d5b740fdc 100644 --- a/.github/workflows/builtins-drift.yml +++ b/.github/workflows/builtins-drift.yml @@ -41,7 +41,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/c-api-binaries.yml b/.github/workflows/c-api-binaries.yml index ef8898d2f..6ae8538e9 100644 --- a/.github/workflows/c-api-binaries.yml +++ b/.github/workflows/c-api-binaries.yml @@ -104,7 +104,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: targets: ${{ matrix.target }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ea1813bc6..f60b274ae 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,7 +28,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: components: rustfmt, clippy @@ -84,7 +84,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: targets: wasm32-unknown-unknown, wasm32-wasip2 @@ -122,7 +122,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: targets: wasm32-unknown-unknown @@ -153,7 +153,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: targets: wasm32-unknown-unknown @@ -205,7 +205,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 # Install the prebuilt cargo-audit binary rather than letting # rustsec/audit-check compile it from source. The source build resolves @@ -272,7 +272,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 @@ -405,9 +405,9 @@ jobs: matrix: include: - os: ubuntu-latest - rust: "1.95.0" + rust: "1.96.0" - os: macos-latest - rust: "1.95.0" + rust: "1.96.0" - os: windows-2025 rust: "1.96.0" steps: @@ -416,7 +416,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: toolchain: ${{ matrix.rust }} @@ -442,7 +442,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 with: @@ -477,7 +477,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 with: @@ -507,7 +507,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/cli-binaries.yml b/.github/workflows/cli-binaries.yml index 9f791da97..46b767033 100644 --- a/.github/workflows/cli-binaries.yml +++ b/.github/workflows/cli-binaries.yml @@ -96,7 +96,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: targets: ${{ matrix.target }} diff --git a/.github/workflows/coreutils-args-drift.yml b/.github/workflows/coreutils-args-drift.yml index 2f0cfe978..be0574990 100644 --- a/.github/workflows/coreutils-args-drift.yml +++ b/.github/workflows/coreutils-args-drift.yml @@ -71,7 +71,7 @@ jobs: fetch-depth: 0 - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: components: rustfmt diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 2a8e52a72..2fb0e79b3 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -35,7 +35,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: components: llvm-tools-preview @@ -93,7 +93,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: components: llvm-tools-preview @@ -144,7 +144,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: components: llvm-tools-preview diff --git a/.github/workflows/debian-oracle.yml b/.github/workflows/debian-oracle.yml index 463faa2f1..f056fedc9 100644 --- a/.github/workflows/debian-oracle.yml +++ b/.github/workflows/debian-oracle.yml @@ -42,7 +42,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 with: diff --git a/.github/workflows/js.yml b/.github/workflows/js.yml index 863292f5c..7aa5578f7 100644 --- a/.github/workflows/js.yml +++ b/.github/workflows/js.yml @@ -42,7 +42,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 @@ -111,7 +111,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 @@ -266,7 +266,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + - uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: targets: ${{ matrix.target }} - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 4f2353375..47ee364a7 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -61,7 +61,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 # Prebuilt binary rather than a source build: cargo-audit's own # dependencies resolve unlocked, and an MSRV bump in one of them past our @@ -95,7 +95,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 diff --git a/.github/workflows/publish-js.yml b/.github/workflows/publish-js.yml index 034c2eff3..039d7421d 100644 --- a/.github/workflows/publish-js.yml +++ b/.github/workflows/publish-js.yml @@ -110,7 +110,7 @@ jobs: cache-dependency-path: crates/bashkit-js/pnpm-lock.yaml - name: Install Rust - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: targets: ${{ matrix.settings.target }} diff --git a/.github/workflows/publish-python.yml b/.github/workflows/publish-python.yml index f5954f350..cc8e80f90 100644 --- a/.github/workflows/publish-python.yml +++ b/.github/workflows/publish-python.yml @@ -148,7 +148,7 @@ jobs: with: python-version: "3.13" - # nightly satisfies our deps' MSRV (monty needs 1.95) + edition 2024; + # nightly satisfies our deps' MSRV (monty needs 1.96) + edition 2024; # its LLVM matches Emscripten 4.0.9's binaryen. pyodide-build manages its # own matching emsdk via the cross-build env (no setup-emsdk needed). - name: Install nightly Rust with the Emscripten target diff --git a/.github/workflows/publish-wasm.yml b/.github/workflows/publish-wasm.yml index bed566c8f..aa176d2ed 100644 --- a/.github/workflows/publish-wasm.yml +++ b/.github/workflows/publish-wasm.yml @@ -63,7 +63,7 @@ jobs: persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 with: targets: wasm32-unknown-unknown diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e9e4a11db..0476b6943 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -107,12 +107,12 @@ jobs: fi - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - name: Verify bashkit-cpython-wasm package without credentials run: | cargo publish --dry-run -p bashkit-cpython-wasm - # Cargo 1.95 publish dry-runs retain a temporary archive. Finalize + # Cargo 1.95+ publish dry-runs retain a temporary archive. Finalize # the verified package at Cargo's package output before measuring it. cargo package -p bashkit-cpython-wasm # crates.io rejects crates over 10 MiB; the embedded snapshot and @@ -136,11 +136,95 @@ jobs: env: CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} + # Publish the Monty forks (bashkit's `python` feature). bashkit-monty depends + # on bashkit-monty-types, and bashkit on both, so they go first, in order. + # See knowledge/runtimes/python-builtin.md. + publish-bashkit-monty-types: + name: Publish bashkit-monty-types + needs: validate-tag + runs-on: ubuntu-latest + environment: release + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.validate-tag.outputs.sha }} + persist-credentials: false + + - name: Verify publish source is on main + run: | + git fetch --no-tags origin main:refs/remotes/origin/main + SOURCE_SHA=$(git rev-parse HEAD) + if ! git merge-base --is-ancestor "$SOURCE_SHA" origin/main; then + echo "Error: publish source $SOURCE_SHA is not reachable from origin/main" + exit 1 + fi + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 + + - name: Verify bashkit-monty-types package without credentials + run: cargo publish --dry-run -p bashkit-monty-types + + # Exchange after package verification so the 30-minute token stays fresh. + - name: Authenticate to crates.io + id: auth + uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 + + - name: Publish bashkit-monty-types to crates.io + run: cargo publish --no-verify -p bashkit-monty-types + env: + CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} + + publish-bashkit-monty: + name: Publish bashkit-monty + needs: [validate-tag, publish-bashkit-monty-types] + runs-on: ubuntu-latest + environment: release + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.validate-tag.outputs.sha }} + persist-credentials: false + + - name: Verify publish source is on main + run: | + git fetch --no-tags origin main:refs/remotes/origin/main + SOURCE_SHA=$(git rev-parse HEAD) + if ! git merge-base --is-ancestor "$SOURCE_SHA" origin/main; then + echo "Error: publish source $SOURCE_SHA is not reachable from origin/main" + exit 1 + fi + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 + + - name: Wait for crates.io index update + run: sleep 30 + + - name: Verify bashkit-monty package without credentials + run: cargo publish --dry-run -p bashkit-monty + + # Exchange after package verification so the 30-minute token stays fresh. + - name: Authenticate to crates.io + id: auth + uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 + + - name: Publish bashkit-monty to crates.io + run: cargo publish --no-verify -p bashkit-monty + env: + CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} + # Publish bashkit (core library) to crates.io publish-bashkit: name: Publish bashkit runs-on: ubuntu-latest - needs: [validate-tag, publish-bashkit-cpython-wasm] + needs: [validate-tag, publish-bashkit-cpython-wasm, publish-bashkit-monty] environment: release permissions: contents: read @@ -162,7 +246,7 @@ jobs: echo "Publish source verified on origin/main: $SOURCE_SHA" - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - name: Verify version matches tag env: @@ -208,7 +292,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - name: Wait for crates.io index update run: sleep 30 @@ -242,7 +326,7 @@ jobs: persist-credentials: false - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - name: Wait for crates.io index update run: sleep 30 @@ -266,7 +350,7 @@ jobs: verify-publish: name: Verify published versions runs-on: ubuntu-latest - needs: [validate-tag, publish-bashkit-cpython-wasm, publish-bashkit, publish-bashkit-cli, publish-bashkit-scripted-tool] + needs: [validate-tag, publish-bashkit-cpython-wasm, publish-bashkit-monty-types, publish-bashkit-monty, publish-bashkit, publish-bashkit-cli, publish-bashkit-scripted-tool] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -283,4 +367,4 @@ jobs: run: | EXPECTED="${RELEASE_TAG#v}" echo "Expected version: $EXPECTED" - python3 scripts/verify_crates_publish.py --expected "$EXPECTED" bashkit-cpython-wasm bashkit bashkit-cli bashkit-scripted-tool + python3 scripts/verify_crates_publish.py --expected "$EXPECTED" bashkit-cpython-wasm bashkit-monty-types bashkit-monty bashkit bashkit-cli bashkit-scripted-tool diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 377512264..524b33b4c 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -100,7 +100,7 @@ jobs: path: crates/bashkit-python/dist - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 @@ -147,7 +147,7 @@ jobs: - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" - - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + - uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 - name: Build and install native wheel run: | @@ -183,7 +183,7 @@ jobs: - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 + uses: dtolnay/rust-toolchain@d86e0fa8f147d6539442c26a61ebba8becc19489 # 1.96.0 - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 @@ -281,7 +281,7 @@ jobs: python-version: "3.13" # Pyodide passes `-Z link-native-libraries=no` (nightly-only). The nightly - # must satisfy our deps' MSRV (monty needs rustc 1.95) and edition 2024, + # must satisfy our deps' MSRV (monty needs rustc 1.96) and edition 2024, # so it has to be recent; its LLVM (19+) matches Emscripten 4.0.9's # binaryen, which is what avoids the wasm-opt target-feature skew that # older Emscripten (3.1.x) hit. See knowledge/runtimes/emscripten-wheels.md. diff --git a/.gitignore b/.gitignore index f4ab6d4b5..b56082878 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,8 @@ # Local files local* +# Upstream Monty source file in the fork; must stay tracked. +!crates/bashkit-monty/src/builtins/locals.rs # IDE .vscode/ diff --git a/Cargo.lock b/Cargo.lock index 292d5ff3d..eb4c02498 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -245,6 +245,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "ar_archive_writer" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6" +dependencies = [ + "object", +] + [[package]] name = "arbitrary" version = "1.4.2" @@ -342,23 +351,22 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "attribute-derive" -version = "0.10.5" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05832cdddc8f2650cc2cc187cc2e952b8c133a48eb055f35211f61ee81502d77" +checksum = "d2f9ef7a68684657ce9da341c934c73b63df7a3585a61e366d84c84ed5d3d167" dependencies = [ "attribute-derive-macro", - "derive-where", "manyhow", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "attribute-derive-macro" -version = "0.10.5" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a7cdbbd4bd005c5d3e2e9c885e6fa575db4f4a3572335b974d8db853b6beb61" +checksum = "300d426e5e73549125bb8e4649bdd5508f82c94ddf898fb0517246e71dfb8e98" dependencies = [ "collection_literals", "interpolator", @@ -367,7 +375,7 @@ dependencies = [ "proc-macro2", "quote", "quote-use", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -432,6 +440,8 @@ dependencies = [ "async-trait", "base64 0.23.1", "bashkit-cpython-wasm", + "bashkit-monty", + "bashkit-monty-types", "bigdecimal", "bitflags 2.13.2", "blake2", @@ -452,7 +462,6 @@ dependencies = [ "foldhash", "futures-core", "futures-util", - "get-size2", "getrandom 0.4.3", "gloo-timers", "hifijson", @@ -464,8 +473,6 @@ dependencies = [ "markkit", "markkit-cli", "md-5", - "monty", - "monty-types", "num-bigint 0.4.8", "num-traits", "os_display", @@ -481,8 +488,6 @@ dependencies = [ "regex", "regex-automata", "reqwest", - "ruff_python_ast", - "ruff_python_parser", "russh", "rustls", "ryu", @@ -604,6 +609,63 @@ dependencies = [ "tokio", ] +[[package]] +name = "bashkit-monty" +version = "0.20.3" +dependencies = [ + "ahash", + "bashkit-monty-types", + "chrono", + "fancy-regex 0.17.0", + "getrandom 0.3.4", + "hashbrown 0.16.1", + "indexmap", + "itertools 0.14.0", + "itoa", + "jiter", + "libm", + "memchr", + "minicbor-serde", + "monty-macros", + "num-bigint 0.4.8", + "num-integer", + "num-traits", + "postcard", + "ruff_python_ast", + "ruff_python_codegen", + "ruff_python_parser", + "ruff_python_stdlib", + "ruff_source_file", + "ruff_text_size", + "serde", + "serde_bytes", + "sha1", + "sha2 0.11.1", + "smallvec", + "speedate", + "strum 0.27.2", + "unicode-general-category", + "unicode-normalization", + "unicode_names2", +] + +[[package]] +name = "bashkit-monty-types" +version = "0.20.3" +dependencies = [ + "chrono", + "jiff", + "monty-macros", + "num-bigint 0.4.8", + "num-traits", + "ruff_python_stdlib", + "serde", + "serde_bytes", + "strum 0.27.2", + "unicode-general-category", + "web-time", +] + [[package]] name = "bashkit-python" version = "0.20.3" @@ -986,6 +1048,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "char_str" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cba78a5abb515610e10af297615434b019755b5d7be14e559ff5340dff50c4" +dependencies = [ + "castaway", + "get-size2", + "itoa", + "ryu", +] + [[package]] name = "chrono" version = "0.4.45" @@ -1184,6 +1258,19 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "compact_str" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79fcda08c33bb58b97008b2cdada6622500e949e060f5913361763121abd2416" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "static_assertions", + "zmij", +] + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -1741,17 +1828,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "derive-where" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d08b3a0bcc0d079199cd476b2cae8435016ec11d1c0986c6901c5ac223041534" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "derive_more" version = "2.1.1" @@ -1827,6 +1903,12 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd8e701084c37e7ef62d3f9e453b618130cbc0ef3573847785952a3ac3f746bf" +[[package]] +name = "drop_bomb" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bda8e21c04aca2ae33ffc2fd8c23134f3cac46db123ba97bd9d3f3b8a4a85e1" + [[package]] name = "dtoa" version = "1.0.11" @@ -2327,22 +2409,22 @@ dependencies = [ [[package]] name = "get-size-derive2" -version = "0.10.3" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c736d226c32e496b8377813b52269e11ad3a48d8373b68862d0364f04fd1229d" +checksum = "28f0daa179069133df60523e0f59d0a6bd2d3db9ccae01b630896d269c4a802e" dependencies = [ "attribute-derive", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "get-size2" -version = "0.10.1" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "823645bc6404ae2915707777061a47d3a031a9ee0bff51b34ec973df3d8d2990" +checksum = "050a5d07359ebfac7f0b74916d94cfa30575e45fdc7e9bfbb0f76d5d4203325a" dependencies = [ - "compact_str", + "compact_str 0.10.0", "get-size-derive2", "hashbrown 0.17.1", "ordermap", @@ -3116,6 +3198,7 @@ dependencies = [ "defmt", "jiff-core", "jiff-static", + "jiff-tzdb", "jiff-tzdb-platform", "log", "portable-atomic", @@ -3162,8 +3245,9 @@ dependencies = [ [[package]] name = "jiter" -version = "0.15.0" -source = "git+https://github.com/pydantic/jiter?rev=6d57715e01ec78859c62fc5447073c0b5902de39#6d57715e01ec78859c62fc5447073c0b5902de39" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc2f2b4e673d798b3dbad0af24bc23b92013e680a6b9ad300b4e5e52fafe0586" dependencies = [ "ahash", "bitvec", @@ -3455,21 +3539,21 @@ dependencies = [ [[package]] name = "manyhow" -version = "0.11.4" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b33efb3ca6d3b07393750d4030418d594ab1139cee518f0dc88db70fec873587" +checksum = "f1704b073316272a6785b70599f91f73b49022c2e290b065591ee6b9109ed8c7" dependencies = [ "manyhow-macros", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "manyhow-macros" -version = "0.11.4" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46fce34d199b78b6e6073abf984c9cf5fd3e9330145a93ee0738a7443e371495" +checksum = "31601db71f1f5fb6f831a18aa3052d13a62528ee4f2cba7e8c9a5e258d953725" dependencies = [ "proc-macro-utils", "proc-macro2", @@ -3598,6 +3682,22 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "minicbor" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7244eafd1e09e7c4e33043881997aa6ab6dffff3ed2cee3395a278980481d6e" + +[[package]] +name = "minicbor-serde" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05ae1ca1d2c55196b389c8308119aa0e2aa8d31115f018dcc23ba3c5d350eb3" +dependencies = [ + "minicbor", + "serde", +] + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -3671,66 +3771,17 @@ dependencies = [ "num-traits", ] -[[package]] -name = "monty" -version = "0.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58b15149448f6034f1bd581638fdf821753b0182a4c5eaf13e4cfd92f95d966b" -dependencies = [ - "ahash", - "chrono", - "fancy-regex 0.17.0", - "hashbrown 0.16.1", - "itertools 0.14.0", - "itoa", - "jiter", - "libm", - "monty-macros", - "monty-types", - "num-bigint 0.4.8", - "num-integer", - "num-traits", - "postcard", - "ruff_python_ast", - "ruff_python_parser", - "ruff_python_stdlib", - "ruff_text_size", - "serde", - "smallvec", - "speedate", - "strum 0.27.2", - "unicode-general-category", - "unicode-normalization", - "unicode_names2", -] - [[package]] name = "monty-macros" -version = "0.0.19" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b6c93dbe4b43469c6d2ece3732053f3fc7af278cf71045ed59c7b6da381530" +checksum = "eb48631728d292ef4fd0eb58a7bbe65047fc70beef3c3659d0d3288a71a28f3c" dependencies = [ "proc-macro2", "quote", "syn 2.0.119", ] -[[package]] -name = "monty-types" -version = "0.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a8988fa8d9902432d5e685a7bb97c84844022dd9560e796c00b119a4c27519b" -dependencies = [ - "chrono", - "monty-macros", - "num-bigint 0.4.8", - "num-traits", - "serde", - "strum 0.27.2", - "unicode-general-category", - "web-time", -] - [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -4127,7 +4178,7 @@ version = "0.117.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6eb1bd62de89fb0c646bfb053b72370750fab43a84ebe09ad97cfa020712314" dependencies = [ - "compact_str", + "compact_str 0.9.1", "oxc-miette", "oxc_allocator", "oxc_ast_macros", @@ -4141,7 +4192,7 @@ version = "0.117.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e65cbfb06ecbae07e0da931815b6b03ade886d016302c400bda7dc0a2f600d3" dependencies = [ - "compact_str", + "compact_str 0.9.1", "hashbrown 0.16.1", "oxc_allocator", "oxc_estree", @@ -4364,7 +4415,9 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" dependencies = [ + "phf_macros 0.12.1", "phf_shared 0.12.1", + "serde", ] [[package]] @@ -4419,6 +4472,16 @@ dependencies = [ "rand 0.8.8", ] +[[package]] +name = "phf_generator" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cbb1126afed61dd6368748dae63b1ee7dc480191c6262a3b4ff1e29d86a6c5b" +dependencies = [ + "fastrand", + "phf_shared 0.12.1", +] + [[package]] name = "phf_generator" version = "0.13.1" @@ -4439,6 +4502,19 @@ dependencies = [ "phf_shared 0.14.0", ] +[[package]] +name = "phf_macros" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d713258393a82f091ead52047ca779d37e5766226d009de21696c4e667044368" +dependencies = [ + "phf_generator 0.12.1", + "phf_shared 0.12.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "phf_macros" version = "0.13.1" @@ -4779,6 +4855,16 @@ dependencies = [ "unarray", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "pulldown-cmark" version = "0.13.6" @@ -4913,9 +4999,9 @@ dependencies = [ [[package]] name = "quote-use" -version = "0.8.4" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9619db1197b497a36178cfc736dc96b271fe918875fbf1344c436a7e93d0321e" +checksum = "48356e493823dc3c1d7e9fc7b3ff204ecec48afbdd718fc4134091b88eb63f3d" dependencies = [ "quote", "quote-use-macros", @@ -4923,14 +5009,14 @@ dependencies = [ [[package]] name = "quote-use-macros" -version = "0.8.4" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82ebfb7faafadc06a7ab141a6f67bcfb24cb8beb158c6fe933f2f035afa99f35" +checksum = "8cf1c5de6a7cc231c71e03c77aa4c7019097859ea7029156b54d2894a8430704" dependencies = [ "proc-macro-utils", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -5263,14 +5349,15 @@ dependencies = [ [[package]] name = "ruff_python_ast" -version = "0.0.3" +version = "0.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a10ab966362319801f5e85ce5c6aeac69f0cf50936a31e888f5d004e9279f337" +checksum = "6aa1de604c478a790cfbcc9c1fef3060e619ed87dd776c6614862ed7e59dc461" dependencies = [ "aho-corasick", "arrayvec", "bitflags 2.13.2", - "compact_str", + "char_str", + "compact_str 0.10.0", "get-size2", "is-macro", "memchr", @@ -5282,21 +5369,48 @@ dependencies = [ "thiserror", ] +[[package]] +name = "ruff_python_codegen" +version = "0.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61039f2c61869bdabf2e5448b561ab6546b787718926c78973ebfefe03f84298" +dependencies = [ + "ruff_python_ast", + "ruff_python_literal", + "ruff_python_parser", + "ruff_source_file", + "ruff_text_size", +] + +[[package]] +name = "ruff_python_literal" +version = "0.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b6025882ae43876fda9867693e14d1d749acefb3db2763d81bfa32a8cd92682" +dependencies = [ + "bitflags 2.13.2", + "icu_properties", + "itertools 0.15.0", + "ruff_python_ast", +] + [[package]] name = "ruff_python_parser" -version = "0.0.3" +version = "0.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e3b8436fb010636ea79ce545acc3e391296ef4e804f7cef336dd5f9c8a4aa3a" +checksum = "b44b423a842d5d2f10807189a260ba677d4eacdc98c5d0459b66bef67fb78d97" dependencies = [ "bitflags 2.13.2", "bstr", - "compact_str", + "drop_bomb", "get-size2", + "hashbrown 0.17.1", "memchr", "ruff_python_ast", "ruff_python_trivia", "ruff_text_size", "rustc-hash", + "stacker", "static_assertions", "thin-vec", "unicode-ident", @@ -5306,9 +5420,9 @@ dependencies = [ [[package]] name = "ruff_python_stdlib" -version = "0.0.3" +version = "0.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c8860927bf42efdabb31ccb2ac9b8f98ee43897b45536f8023e217b158e49a4" +checksum = "ea8c1e6e69f7570e1f24c7a26ef93f6fd1475e2d76aa9ca4a78093c1f80523cb" dependencies = [ "bitflags 2.13.2", "unicode-ident", @@ -5316,21 +5430,22 @@ dependencies = [ [[package]] name = "ruff_python_trivia" -version = "0.0.3" +version = "0.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "969e4a14b2550818efea99b9e2361c714c72e4f1fb94799251d55aed20345189" +checksum = "990dadfad3aa3fd63040d98056112e5a377af8ada0c9c7659e8907a4b3c7cb34" dependencies = [ "itertools 0.15.0", "ruff_source_file", "ruff_text_size", + "rustc-hash", "unicode-ident", ] [[package]] name = "ruff_source_file" -version = "0.0.3" +version = "0.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c194e02d121e4a1744464ce3a982c4c196eb039bbf67532d18c8ce09f8da6381" +checksum = "ed11e9366de40e79707c0e575afd8beffad58ec94c253577d516b8679cf98308" dependencies = [ "memchr", "ruff_text_size", @@ -5338,9 +5453,9 @@ dependencies = [ [[package]] name = "ruff_text_size" -version = "0.0.3" +version = "0.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c91652ad39be604bc4d5299a5d19feccdd89e255609d89a031e7bb8e0d0aef9f" +checksum = "5a4edc941f215495170a1bda0beeeb31db2fdcd67beecfe7f29d94b2663e1965" dependencies = [ "get-size2", ] @@ -5801,6 +5916,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -6217,6 +6342,19 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -6273,6 +6411,7 @@ version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" dependencies = [ + "phf 0.12.1", "strum_macros 0.27.2", ] @@ -6391,7 +6530,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix", "windows-sys 0.61.2", @@ -6872,7 +7011,7 @@ version = "2.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5283634e518fe9e82c7b20520bb4bc209009fd16c82077c802f8111ecbb0117a" dependencies = [ - "rand 0.9.5", + "rand 0.10.3", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 8ff361a63..46f61e7a1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ categories = ["command-line-utilities", "parser-implementations"] # Important decision: pinned exactly. Precompiled `.cwasm` artifacts only load # into the identical wasmtime version. Runtime build: no Cranelift, Pulley # interpreter only; Cranelift is added as a build-dependency by the artifact -# crate. 48.x is the newest line supporting the pinned rustc 1.95. +# crate. 49.x became possible with rustc 1.96; bump it as its own change. wasmtime = { version = "=48.0.8", default-features = false, features = ["runtime", "std", "pulley", "async"] } # Async runtime # Base features are WASM-compatible; crates needing more (rt-multi-thread, fs, net, process) @@ -227,23 +227,6 @@ inherits = "release" lto = "fat" codegen-units = 1 -# Important decision (security): pin `jiter` to upstream main so the whole -# workspace can run pyo3 0.29, which fixes GHSA-36hh-v3qg-5jq4 (high, OOB read -# in PyList/PyTuple iterators) and GHSA-chgr-c6px-7xpp (missing `Sync` bound) -# in the bashkit-python extension. -# -# Blocker: `monty 0.0.19` -> `jiter ^0.15.0` and jiter 0.15.0 declares an -# optional `pyo3 = "^0.28.2"` (jiter 0.16.0 moved to pyo3 0.29 but is outside -# monty's range). -# Although jiter's `python` feature is never activated here (monty only enables -# `num-bigint`), the weak `pyo3?/num-bigint` reference plus pyo3-ffi's -# `links = "python"` global uniqueness force the resolver to honour jiter's -# 0.28 constraint, pinning the whole graph below pyo3 0.29. -# -# jiter `main` is still version 0.15.0 (semver-compatible with monty's -# `^0.15.0`) but already bumped its pyo3 dependency to 0.29, so this patch -# unblocks the upgrade without a fork. Drop it once monty ships a release that -# tracks a published jiter with pyo3 0.29. # Important decision (supply chain): `idna_adapter` is pinned to 1.0.0 in # Cargo.lock -- a lockfile-only pin, since the crate exists purely so the top # level can pick `idna`'s Unicode back end (1.2.x = ICU4X, 1.1.x = unicode-rs, @@ -267,5 +250,3 @@ codegen-units = 1 # # Restore after a `cargo update` that bumps it: # cargo update -p idna_adapter --precise 1.0.0 -[patch.crates-io] -jiter = { git = "https://github.com/pydantic/jiter", rev = "6d57715e01ec78859c62fc5447073c0b5902de39" } diff --git a/README.md b/README.md index c4aed1675..fe6d5675a 100644 --- a/README.md +++ b/README.md @@ -360,6 +360,7 @@ See [knowledge/integrations/git-support.md](knowledge/integrations/git-support.m ## Experimental: Python Support Enable the `python` feature to embed the [Monty](https://github.com/pydantic/monty) Python interpreter (pure Rust, Python 3.12). +Bashkit uses a slightly patched Monty 1.4, published as `bashkit-monty` and `bashkit-monty-types`: the patch adds a per-run memory probe and a VM checkpoint hook, so concurrent runs in one process get separate memory limits and honour cancellation. The upstream proposal is [pydantic/monty#740](https://github.com/pydantic/monty/pull/740); the forks go away once upstream has the hooks. Python code runs in-memory with configurable resource limits and VFS bridging, files created by bash are readable from Python and vice versa. @@ -386,9 +387,9 @@ with open('/tmp/data.txt', 'w') as f: bash.exec("cat /tmp/data.txt").await?; // "hello from python" ``` -Stdlib modules: `math`, `pathlib`, `os` (getenv/environ), `sys`, `typing`. -Security note: `re` is intentionally disabled due to regex backtracking DoS risk. -Limitations: file I/O is VFS-scoped, no network, no classes, no third-party imports. +Stdlib modules: `json`, `math`, `re`, `datetime`, `pathlib`, `os`, `sys`, `typing`, `csv`, `collections`, and more. +Rust embedders install `bashkit::MeteredAllocator` as the global allocator; it gives each run its own memory limit. +Limitations: file I/O is VFS-scoped, no network, simple classes only (no inheritance), no third-party imports. See [crates/bashkit/docs/python.md](crates/bashkit/docs/python.md) for the full guide. For full CPython 3.14 (complete language and stdlib, CPython CLI semantics), enable the diff --git a/crates/bashkit-capi/src/lib.rs b/crates/bashkit-capi/src/lib.rs index ff232e1d8..cbd703959 100644 --- a/crates/bashkit-capi/src/lib.rs +++ b/crates/bashkit-capi/src/lib.rs @@ -26,6 +26,12 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::runtime::{Builder, Runtime}; +// Monty python3 charges each VM for its own allocations through this +// allocator (see bashkit::MeteredAllocator). In a cdylib it only governs this +// library's Rust allocations, never the host runtime's allocator. +#[global_allocator] +static METERED_ALLOC: bashkit::MeteredAllocator = bashkit::MeteredAllocator; + pub const BASHKIT_ABI_VERSION_1: u32 = 1; pub const BASHKIT_MAX_CONFIG_BYTES: usize = 10_000_000; pub const BASHKIT_RESULT_STDOUT_TRUNCATED: u32 = 1 << 0; diff --git a/crates/bashkit-capi/src/runtime_functions.rs b/crates/bashkit-capi/src/runtime_functions.rs index 8dfd166e6..18504c142 100644 --- a/crates/bashkit-capi/src/runtime_functions.rs +++ b/crates/bashkit-capi/src/runtime_functions.rs @@ -225,7 +225,7 @@ pub(super) fn python_handler(registration: Registration) -> bashkit::PythonExter Arc::new(move |name, args, kwargs| { Box::pin(async move { let result = async { - let args = runtime_value::encode_python(&bashkit::MontyObject::Tuple(args)).map_err(|e| e.to_string())?; + let args = runtime_value::encode_python(&bashkit::MontyObject::tuple(args)).map_err(|e| e.to_string())?; let kwargs = runtime_value::encode_python(&bashkit::MontyObject::dict(kwargs)).map_err(|e| e.to_string())?; let value = dispatch(registration, serde_json::json!({"language":"python", "name":name, "args":args, "kwargs":kwargs})).await?; runtime_value::decode_python(&value).map_err(|e| e.to_string()) diff --git a/crates/bashkit-cli/src/main.rs b/crates/bashkit-cli/src/main.rs index 47bfa821a..12608f588 100644 --- a/crates/bashkit-cli/src/main.rs +++ b/crates/bashkit-cli/src/main.rs @@ -309,6 +309,11 @@ fn format_panic_message(payload: &dyn std::any::Any) -> String { format!("bashkit: internal error: {msg}") } +// Per-VM Monty memory metering (see bashkit::MeteredAllocator). +#[cfg(feature = "python")] +#[global_allocator] +static ALLOC: bashkit::MeteredAllocator = bashkit::MeteredAllocator; + fn main() -> Result<()> { // THREAT[TM-INF-021]: Suppress stack backtraces to prevent information disclosure. // Custom panic hook emits a sanitized message without file paths, line numbers, diff --git a/crates/bashkit-js/src/lib.rs b/crates/bashkit-js/src/lib.rs index dca97335e..2157e9418 100644 --- a/crates/bashkit-js/src/lib.rs +++ b/crates/bashkit-js/src/lib.rs @@ -45,6 +45,12 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex as StdMutex}; use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore}; +// Monty python3 charges each VM for its own allocations through this +// allocator (see bashkit::MeteredAllocator). In a cdylib it only governs this +// library's Rust allocations, never the host runtime's allocator. +#[global_allocator] +static METERED_ALLOC: bashkit::MeteredAllocator = bashkit::MeteredAllocator; + // --------------------------------------------------------------------------- // Shared tokio runtime + concurrency limiter for JS tool callbacks (issue #982). // A single multi-thread runtime is created lazily and reused for every callback diff --git a/crates/bashkit-js/src/runtime_functions.rs b/crates/bashkit-js/src/runtime_functions.rs index 8da46f47f..2c4e57644 100644 --- a/crates/bashkit-js/src/runtime_functions.rs +++ b/crates/bashkit-js/src/runtime_functions.rs @@ -67,7 +67,7 @@ pub(super) fn python_handler() -> PythonExternalFnHandler { Arc::new(|name, args, kwargs| { Box::pin(async move { let result = async { - let args = runtime_value::encode_python(&bashkit::MontyObject::Tuple(args)) + let args = runtime_value::encode_python(&bashkit::MontyObject::tuple(args)) .map_err(|e| e.to_string())?; let kwargs = runtime_value::encode_python(&bashkit::MontyObject::dict(kwargs)) .map_err(|e| e.to_string())?; diff --git a/crates/bashkit-monty-types/Cargo.toml b/crates/bashkit-monty-types/Cargo.toml new file mode 100644 index 000000000..630516d7a --- /dev/null +++ b/crates/bashkit-monty-types/Cargo.toml @@ -0,0 +1,62 @@ +# Fork of pydantic/monty monty-types-1.4.0 (MIT) for bashkit's in-process Python. +# +# Important decision (security): bashkit runs many tenants' Python in one +# process. Upstream Monty enforces `max_memory` through a process-wide +# allocator counter and has no in-VM host checkpoint, so bashkit carries a +# small patch in `bashkit-monty-types` (`set_memory_probe`, pydantic/monty#740, +# and `set_checkpoint_hook`) and republishes `monty` against it. Source is +# upstream monty-types-1.4.0 unchanged except marked edits; the library names stay `monty` / +# `monty_types` so code reads as upstream. Drop both crates once upstream ships +# the hooks. See knowledge/runtimes/python-builtin.md. +# +# Not formatted or linted as bashkit code: kept byte-identical to upstream +# (rustfmt.toml disables formatting; a crate-level `#![allow]` in lib.rs and +# [lints] allow upstream warnings; upstream tests are not vendored). Every +# local edit is marked with a `bashkit fork:` comment. + +[package] +name = "bashkit-monty-types" +version.workspace = true +edition = "2024" +rust-version = "1.96" +authors = ["Samuel Colvin ", "Everruns"] +license = "MIT" +repository.workspace = true +description = "Fork of pydantic/monty's monty-types 1.4.0 with an embedder memory probe and checkpoint hook, for bashkit's python3" +keywords = ["python", "interpreter", "sandbox", "bashkit"] +categories = ["compilers", "emulators"] +readme = "README.md" +include = ["src/**", "README.md", "LICENSE"] + +[lib] +name = "monty_types" +path = "src/lib.rs" +# Upstream tests are not vendored. +test = false +doctest = false + +[dependencies] +chrono = { version = "0.4", features = ["serde"] } +jiff = { version = "0.2", features = ["std", "serde"], default-features = false } +monty-macros = { version = "1.4.0" } +num-bigint = { version = "0.4", features = ["serde"] } +num-traits = { version = "0.2" } +ruff_python_stdlib = { version = "0.0.14" } +serde = { version = "1.0", features = ["derive", "rc"] } +serde_bytes = { version = "0.11" } +strum = { version = "0.27", features = ["derive", "phf"] } +unicode-general-category = { version = "1" } + +[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] +web-time = { version = "1.1" } + +[features] +test-hooks = [] +tzdb = ["jiff/tzdb-zoneinfo", "tzdb-bundled"] +tzdb-bundled = ["jiff/tzdb-bundle-always"] + +[lints.rust] +warnings = "allow" + +[lints.clippy] +all = "allow" diff --git a/crates/bashkit-monty-types/LICENSE b/crates/bashkit-monty-types/LICENSE new file mode 100644 index 000000000..d30ac52dc --- /dev/null +++ b/crates/bashkit-monty-types/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Pydantic Services Inc. 2026 to present + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/bashkit-monty-types/README.md b/crates/bashkit-monty-types/README.md new file mode 100644 index 000000000..eeba357b6 --- /dev/null +++ b/crates/bashkit-monty-types/README.md @@ -0,0 +1,69 @@ +# monty-types + +Shared boundary types for [Monty](https://github.com/pydantic/monty), the +Python sandbox — the owned, heap-free data types that cross between the +sandbox and the hosts that embed it, with **no interpreter +implementation**. + +## What's here + +- `MontyObject` / `MontyType` — Python values and their types at the host + boundary, including the `datetime` family (`MontyDate`, `MontyDateTime`, + `MontyTimeDelta`, `MontyTimeZone`) and `MontyFileHandle`. +- `ObjectRef` — a borrowed value, with typed accessors (`as_int`, `as_str`, `items`, `pairs`). + `MontyObject::as_ref()` borrows a value for inspection. +- `CallArgs` / `NamedValues` — the arguments or inputs of one message. + Their builders accept `MontyObject` values; their iterators return borrowed values. + Both carriers and the `MontyObject` / `ObjectRef` types keep their fields private. +- `unstable` — graph representation APIs for bindings and transport adapters, with no API compatibility guarantee. + They may change or disappear in any release; prefer value constructors and typed accessors when possible. +- `MontyException` / `ExcType` — exceptions with tracebacks (`StackFrame`, + `CodeLoc`) and structured payloads (`ExcData`). +- `OsFunctionCall` — the typed OS-call payloads sandboxed code suspends with + (file reads/writes, `open()`, `os.getenv`, ...), plus the `stat_result` + builders hosts use to answer them. +- `MontyPath` preserves OS-call paths for validation; `normalize_virtual_path` + provides the lexical POSIX normalization shared by the interpreter, mounts, and `OsFunctionCall::to_args()` callbacks. + It borrows canonical paths and resolves relative inputs from `/`. + Validate NUL bytes and path limits before calling it; it does not confine filesystem access. +- `ResourceTracker` / `ResourceLimits` — the resource tracker the + interpreter uses to enforce time/memory/recursion limits, plus the + `max_suspensions` budget hosts enforce themselves. +- `PrintStream` / `PrintWriter` / `CollectedStreams` — `print()` output + capture, and the labelled buffer behind `PrintWriter::CollectStreams`. +- `CompileOptions`, `ExtFunctionResult`, `NameLookupResult`, `FileMode`, and + the CPython-compatible formatting helpers behind their `repr()`s. + +## Who should depend on it + +Host-side crates that need these types without linking the interpreter — +`monty-fs` (which services `OsFunctionCall`s locally via +`MountTable::handle_os_call`), `monty-pool` (which talks to Monty workers +over the wire), the `pydantic-monty-client` Python bindings and the +`@pydantic/monty` JS bindings — depend on this crate **instead of `monty`**, +so their binaries never link the interpreter itself. Only worker-side crates +(`monty-runtime`, `monty-wasm-runtime`, and `monty-proto` with its `worker` +feature) link `monty`. + +```rust +use monty_types::MontyObject; + +let value = MontyObject::list([MontyObject::int(1), MontyObject::string("x".to_owned())]); +assert_eq!(value.py_repr(), "[1, 'x']"); +``` + +## Monty crates + +- [`monty`](https://crates.io/crates/monty) — the core interpreter: Python parser, bytecode VM, and sandbox. +- [`monty-types`](https://crates.io/crates/monty-types) — the shared boundary data types (values, exceptions, OS calls, resource limits) hosts use without linking the interpreter. **this crate** +- [`monty-fs`](https://crates.io/crates/monty-fs) — host-side filesystem mounts: maps virtual sandbox paths to real host directories. +- [`monty-runtime`](https://crates.io/crates/monty-runtime) — the `monty` binary: REPL, file runner, and subprocess worker mode. +- [`monty-pool`](https://crates.io/crates/monty-pool) — an elastic pool of crash-isolated `monty` worker subprocesses. +- [`monty-proto`](https://crates.io/crates/monty-proto) — the protobuf wire protocol spoken between pool parents and workers. +- [`monty-type-checking`](https://crates.io/crates/monty-type-checking) — type checking of sandboxed code, powered by [ty](https://docs.astral.sh/ty/). +- [`monty-typeshed`](https://crates.io/crates/monty-typeshed) — the trimmed typeshed stubs describing the stdlib subset Monty implements. +- [`monty-macros`](https://crates.io/crates/monty-macros) — the proc macros behind `monty`'s argument parsing. + +## License + +MIT diff --git a/crates/bashkit-monty-types/rustfmt.toml b/crates/bashkit-monty-types/rustfmt.toml new file mode 100644 index 000000000..582ae19f4 --- /dev/null +++ b/crates/bashkit-monty-types/rustfmt.toml @@ -0,0 +1,2 @@ +# Upstream source, kept byte-identical: never reformat. +disable_all_formatting = true diff --git a/crates/bashkit-monty-types/src/args.rs b/crates/bashkit-monty-types/src/args.rs new file mode 100644 index 000000000..3411668e6 --- /dev/null +++ b/crates/bashkit-monty-types/src/args.rs @@ -0,0 +1,15 @@ +//! Projection of typed argument structs into the [`CallArgs`] host callbacks consume. +//! The `#[derive(ToArgs)]` macro in `monty-macros` emits implementations via +//! `crate::args::ToArgs`, which resolves in this crate. + +use crate::object::CallArgs; + +/// Projects a typed args struct into the [`CallArgs`] host callbacks expect. +/// Consumes `self` to avoid cloning owned fields. +/// +/// Inverse of `monty`'s internal `FromArgs` (`ArgValues` → struct); driven by +/// [`crate::os::OsFunctionCall::to_args`] for the Python and JavaScript bindings. +pub trait ToArgs { + /// Consumes the fields into arguments for delivery to the host. + fn to_args(self) -> CallArgs; +} diff --git a/crates/bashkit-monty-types/src/builtins.rs b/crates/bashkit-monty-types/src/builtins.rs new file mode 100644 index 000000000..2e03a405e --- /dev/null +++ b/crates/bashkit-monty-types/src/builtins.rs @@ -0,0 +1,122 @@ +//! [`BuiltinsFunctions`] — the name-level identity of every interpreter-native +//! Python builtin, carried by [`MontyObject::builtin_function`](crate::MontyObject::builtin_function). + +use strum::{Display, EnumString, FromRepr, IntoStaticStr, VariantNames}; +/// Enumerates every interpreter-native Python builtin function. +/// +/// Listed alphabetically per +/// Commented-out variants are not yet implemented. +/// +/// Note: Type constructors are handled by the `Type` enum, not here. +/// +/// Uses strum derives for automatic `Display`, `FromStr`, and `IntoStaticStr` implementations. +/// All variants serialize to lowercase (e.g., `Print` -> "print"). +#[derive( + Debug, + Clone, + Copy, + Display, + EnumString, + FromRepr, + IntoStaticStr, + VariantNames, + PartialEq, + Eq, + Hash, + serde::Serialize, + serde::Deserialize, +)] +// `use_phf` while still below the ~100-variant threshold: it breaks even now and the enum keeps growing. +#[strum(serialize_all = "lowercase", use_phf)] +#[serde(rename_all = "lowercase")] +#[repr(u8)] +pub enum BuiltinsFunctions { + Abs, + // Aiter, + All, + // Anext, + Any, + // Ascii, + Bin, + // bool - handled by Type enum + // Breakpoint, + // bytearray - handled by Type enum + // bytes - handled by Type enum + // Callable, + Chr, + // Classmethod, + // Compile, + // complex - handled by Type enum + // Delattr, + // dict - handled by Type enum + // Dir, + Divmod, + Enumerate, + Filter, + // float - handled by Type enum + // Format - appended below + // frozenset - handled by Type enum + Getattr, + // Globals, + Hasattr, + Hash, + // Help, + Hex, + Id, + // Input, + // int - handled by Type enum + Isinstance, + // Issubclass, + // Iter - handled by Type enum + Len, + // list - handled by Type enum + Map, + Max, + // memoryview - handled by Type enum + Min, + Next, + // object - handled by Type enum + Oct, + Open, + Ord, + Pow, + Print, + // Property, + // range - handled by Type enum + Repr, + Reversed, + Round, + // set - handled by Type enum + Setattr, + // Slice, + Sorted, + // Staticmethod, + // str - handled by Type enum + Sum, + // Super, + // tuple - handled by Type enum + Type, + // Vars, + Zip, + // __import__ - not planned + // Appended out of alphabetical order: the discriminant is emitted as a + // bytecode operand, so this list is append-only. + /// `object.__setattr__(obj, name, value)` — the write that bypasses a + /// class's attribute hooks, reached only through `object`. Its name is not + /// an identifier, so it can never resolve as a bare global. + /// + /// The first variant whose name is not its lowercased identifier, so it + /// needs both renames: serde and strum each carry the name across a + /// different boundary (JSON vs. `Display`/`FromStr`) and must agree. + #[strum(serialize = "object.__setattr__")] + #[serde(rename = "object.__setattr__")] + ObjectSetattr, + /// `format(value, format_spec='')`, appended after [`Self::ObjectSetattr`]. + Format, + /// `eval(source, /, globals=None, locals=None)`, appended after [`Self::Format`]. + Eval, + /// `exec(source, /, globals=None, locals=None, *, closure=None)`, appended after [`Self::Eval`]. + Exec, + /// `locals()`, appended after [`Self::Exec`]. + Locals, +} diff --git a/crates/bashkit-monty-types/src/exceptions.rs b/crates/bashkit-monty-types/src/exceptions.rs new file mode 100644 index 000000000..5ff0ea772 --- /dev/null +++ b/crates/bashkit-monty-types/src/exceptions.rs @@ -0,0 +1,936 @@ +//! Public exception types: [`ExcType`], [`MontyException`] and its +//! traceback/payload components ([`StackFrame`], [`CodeLoc`], [`ExcData`]). + +use std::{ + error, + fmt::{self, Write}, + mem, str, + sync::Arc, +}; + +use serde::{Deserialize, Serialize}; +use strum::{Display, EnumString, IntoStaticStr, VariantNames}; + +use crate::format::StringRepr; + +/// Public representation of a Monty exception. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct MontyException { + /// The exception type raised + exc_type: ExcType, + /// Optional exception message explaining what went wrong + message: Option, + /// Stack trace of the exception, first is the outermost frame shown first in the traceback + traceback: Vec, + /// Structured payload for exception types that carry more than a message. + data: ExcData, +} + +/// Number of identical consecutive frames to show before collapsing. +/// +/// CPython shows 3 identical frames, then "[Previous line repeated N more times]". +const REPEAT_FRAMES_SHOWN: usize = 3; + +/// Display implementation for MontyException should exactly match python traceback format. +impl fmt::Display for MontyException { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Print the traceback header if we have frames + if !self.traceback.is_empty() { + writeln!(f, "Traceback (most recent call last):")?; + } + + // Print frames, collapsing consecutive identical frames like CPython does + let mut i = 0; + while i < self.traceback.len() { + let frame = &self.traceback[i]; + + // Count consecutive identical frames + let mut repeat_count = 1; + while i + repeat_count < self.traceback.len() + && frames_are_identical(frame, &self.traceback[i + repeat_count]) + { + repeat_count += 1; + } + + if repeat_count > REPEAT_FRAMES_SHOWN { + // Show first REPEAT_FRAMES_SHOWN frames, then collapse the rest + for j in 0..REPEAT_FRAMES_SHOWN { + write!(f, "{}", self.traceback[i + j])?; + } + let collapsed = repeat_count - REPEAT_FRAMES_SHOWN; + writeln!(f, " [Previous line repeated {collapsed} more times]")?; + i += repeat_count; + } else { + // Show all frames in this group + for j in 0..repeat_count { + write!(f, "{}", self.traceback[i + j])?; + } + i += repeat_count; + } + } + + if let Some(msg) = &self.message { + write!(f, "{}: {}", self.exc_type, msg) + } else { + write!(f, "{}", self.exc_type) + } + } +} + +impl error::Error for MontyException {} + +impl MontyException { + /// Create a new MontyException with the given exception type and message. + /// + /// You can't provide a traceback here, it's send when raising the exception. + #[must_use] + pub fn new(exc_type: ExcType, message: Option) -> Self { + Self { + exc_type, + message, + traceback: vec![], + data: ExcData::None, + } + } + + /// Creates an exception with an explicit traceback. + /// + /// Most callers should use [`MontyException::new`] — the traceback is + /// normally attached when the exception is raised. This constructor + /// exists for boundaries that *reconstruct* an exception that was raised + /// elsewhere (e.g. deserializing one received from a `monty subprocess` + /// worker) and must preserve its original frames. + #[must_use] + pub fn with_traceback(exc_type: ExcType, message: Option, traceback: Vec) -> Self { + Self { + exc_type, + message, + traceback, + data: ExcData::None, + } + } + + /// Attaches a structured payload — see [`ExcData`]. Public for + /// boundaries that reconstruct an exception raised elsewhere (like + /// [`MontyException::with_traceback`]); in-process raises attach the + /// payload at the raise site instead. + #[must_use] + pub fn with_data(mut self, data: ExcData) -> Self { + self.data = data; + self + } + + /// The structured payload, [`ExcData::None`] for most exceptions. + #[must_use] + pub fn data(&self) -> &ExcData { + &self.data + } + + /// Structured `UnicodeDecodeError`/`UnicodeEncodeError` fields, present + /// only for unicode errors raised by codec operations on objects no + /// larger than [`UnicodeErrorData::MAX_OBJECT_LEN`]. + #[must_use] + pub fn unicode_data(&self) -> Option<&UnicodeErrorData> { + self.data.unicode() + } + + /// Structured `json.JSONDecodeError` fields, present only for decode + /// errors raised by `json.loads` (not for manually raised exceptions). + #[must_use] + pub fn json_data(&self) -> Option<&JsonErrorData> { + self.data.json() + } + + /// Removes and returns the structured payload, for consumers (like the + /// Python bindings) that rebuild the native exception and want the + /// payload by value without cloning it. + #[must_use] + pub fn take_data(&mut self) -> ExcData { + mem::take(&mut self.data) + } + + /// Appends frames to this exception's traceback. + pub fn add_traceback(&mut self, traceback: impl IntoIterator) { + self.traceback.extend(traceback); + } + + /// Shorthand for a traceback-free `RuntimeError` wrapping `err`'s display + /// output — used at host boundaries (input conversion, REPL feeds) where + /// no sandbox stack frames exist. + #[must_use] + pub fn runtime_error(err: impl fmt::Display) -> Self { + Self { + exc_type: ExcType::RuntimeError, + message: Some(err.to_string()), + traceback: vec![], + data: ExcData::None, + } + } + + /// The exception type raised. + #[must_use] + pub fn exc_type(&self) -> ExcType { + self.exc_type + } + + /// Optional exception message explaining what went wrong. + /// + /// Equivalent of python's `exc.args[0]` + #[must_use] + pub fn message(&self) -> Option<&str> { + self.message.as_deref() + } + + /// Optional exception message explaining what went wrong. + /// + /// This takes ownership of the MontyException and returns an owned String. + /// + /// Equivalent of python's `exc.args[0]` + #[must_use] + pub fn into_message(self) -> Option { + self.message + } + + /// Stack trace of the exception, first is the outermost frame shown first in the traceback + #[must_use] + pub fn traceback(&self) -> &[StackFrame] { + &self.traceback + } + + /// Returns a compact summary of the exception. + /// + /// Format: `ExceptionType: message` (e.g., `NotImplementedError: feature not supported`) + /// If there's no message, just returns the exception type name. + #[must_use] + pub fn summary(&self) -> String { + if let Some(msg) = &self.message { + format!("{}: {}", self.exc_type, msg) + } else { + self.exc_type.to_string() + } + } + + /// Returns the exception formatted as Python's repr() would display it. + /// + /// Format: `ExceptionType('message')` (e.g., `ValueError('invalid value')`) + /// Uses appropriate quoting for messages containing quotes. + #[must_use] + pub fn py_repr(&self) -> String { + let type_str: &'static str = self.exc_type.into(); + if let Some(msg) = &self.message { + format!("{}({})", type_str, StringRepr(msg)) + } else { + format!("{type_str}()") + } + } +} + +/// Check if two stack frames are identical for the purpose of collapsing repeated frames. +/// +/// Two frames are identical if they have the same filename, line number, and function name. +fn frames_are_identical(a: &StackFrame, b: &StackFrame) -> bool { + a.filename == b.filename && a.start.line == b.start.line && a.frame_name == b.frame_name +} + +/// Python exception types supported by the interpreter. +/// +/// Uses strum derives for automatic `Display`, `FromStr`, and `Into<&'static str>` implementations. +/// The string representation matches the variant name exactly (e.g., `ValueError` -> "ValueError"), +/// except where a `serialize` attribute gives a dotted name to disambiguate a stdlib subclass from +/// its builtin parent (`binascii.Error` from `ValueError`, say). +/// +/// `ExcType::VARIANTS` is the canonical list of those names, and the host bridges mirror it: +/// `PYTHON_EXC_NAMES` in `crates/monty-js/ts/errors.ts` and the `ExcType` literal in +/// `pydantic_monty/__init__.py`. Both are hand-written, so `monty-proto`'s `exc_type_bridges` test +/// reads them and pins them here — adding a variant without wiring the bridges fails that test. +#[derive( + Debug, + Clone, + Copy, + Default, + PartialEq, + Eq, + Hash, + Display, + EnumString, + IntoStaticStr, + VariantNames, + Serialize, + Deserialize, +)] +pub enum ExcType { + /// primary exception class - matches any exception in isinstance checks. + /// + /// Also the `Default` — required so `Type` (which embeds an `ExcType` in + /// its `Exception` variant) can derive `strum::EnumIter`. + #[default] + Exception, + + /// System exit exceptions + BaseException, + SystemExit, + KeyboardInterrupt, + + // --- ArithmeticError hierarchy --- + /// Intermediate class for arithmetic errors. + ArithmeticError, + /// Subclass of ArithmeticError. + OverflowError, + /// Subclass of ArithmeticError. + ZeroDivisionError, + + // --- LookupError hierarchy --- + /// Intermediate class for lookup errors. + LookupError, + /// Subclass of LookupError. + IndexError, + /// Subclass of LookupError. + KeyError, + + // --- RuntimeError hierarchy --- + /// Intermediate class for runtime errors. + RuntimeError, + /// Subclass of RuntimeError. + NotImplementedError, + /// Subclass of RuntimeError. + RecursionError, + + // --- AttributeError hierarchy --- + AttributeError, + /// Subclass of AttributeError (from dataclasses module). + FrozenInstanceError, + + // --- NameError hierarchy --- + NameError, + /// Subclass of NameError - for accessing local variable before assignment. + UnboundLocalError, + + // --- ValueError hierarchy --- + ValueError, + /// Subclass of ValueError - for encoding/decoding errors. + UnicodeDecodeError, + /// Subclass of ValueError - for encoding errors (e.g. `str.encode('ascii')` + /// on a string containing non-ASCII characters). + UnicodeEncodeError, + /// Subclass of ValueError for invalid JSON syntax in `json.loads()`. + #[strum(serialize = "json.JSONDecodeError")] + JsonDecodeError, + /// Subclass of ValueError for invalid TOML in `tomllib.loads()` / `tomllib.load()`. + #[strum(serialize = "tomllib.TOMLDecodeError")] + TomlDecodeError, + + // --- ImportError hierarchy --- + /// Import-related errors (module not found, name not in module). + ImportError, + /// Subclass of ImportError - for when a module cannot be found. + ModuleNotFoundError, + + // --- OSError hierarchy --- + /// OS-related errors (file not found, permission denied, etc.) + OSError, + /// Subclass of OSError - for when a file or directory cannot be found. + FileNotFoundError, + /// Subclass of OSError - for when a file already exists. + FileExistsError, + /// Subclass of OSError - for when a path is a directory but a file was expected. + IsADirectoryError, + /// Subclass of OSError - for when a path is not a directory but one was expected. + NotADirectoryError, + /// Subclass of OSError - for when an operation is not permitted (e.g., writing + /// to a read-only mount, or attempting to access a path outside a mounted directory). + PermissionError, + /// `io.UnsupportedOperation` - raised by file objects when a requested + /// operation isn't allowed by the open mode (e.g. `read()` on `'w'`). + /// + /// In CPython this inherits from both `OSError` and `ValueError`. Monty's + /// `ExcType` enum models single parents, but [`Self::is_subclass_of`] + /// matches `UnsupportedOperation` against both `OSError` and `ValueError` + /// so `except ValueError:` and `except OSError:` both catch it as in + /// CPython. + #[strum(serialize = "io.UnsupportedOperation")] + UnsupportedOperation, + /// Subclass of OSError since Python 3.3 (PEP 3151). + TimeoutError, + + // --- Standalone exception types --- + AssertionError, + MemoryError, + StopIteration, + SyntaxError, + TypeError, + + // --- Module-specific exception types --- + + // --- re module --- + /// `re.PatternError` - raised for invalid regex patterns or unsupported regex features. + /// + /// # Behavior Note + /// + /// Limited to monty's exception type, `PatternError` does not provide `pattern`, `pos`, + /// `lineno` and `colno` attributes. + /// + /// As per CPython's implementation, it would be hard to convert `fancy-regex`'s error + /// representations into the required attributes. + #[strum(serialize = "re.PatternError")] + RePatternError, + + // --- binascii module --- + /// `binascii.Error` - raised by the `base64` codecs for malformed input. + /// + /// A `ValueError` subclass in CPython, so `except ValueError:` catches it. + #[strum(serialize = "binascii.Error")] + BinasciiError, + + /// `binascii.Incomplete` - a direct `Exception` subclass, not a `ValueError`. + /// + /// Nothing raises it: the `a2b_hqx` family it belonged to left CPython in + /// 3.11, so the class survives only for `except binascii.Incomplete:` in + /// older code. Monty exposes it for the same reason. + #[strum(serialize = "binascii.Incomplete")] + BinasciiIncomplete, + + // --- csv module --- + /// `csv.Error` - raised by the `csv` readers and writers for malformed data + /// and unknown dialect names. + /// + /// A direct `Exception` subclass, named `_csv.Error` as in CPython. + #[strum(serialize = "_csv.Error")] + CsvError, + + // --- decimal module --- + // CPython's decimal signals form a multiple-inheritance hierarchy under + // `ArithmeticError`; [`Self::decimal_ancestors`] lists each one's bases. + /// `decimal.DecimalException`, the base of every decimal signal. + #[strum(serialize = "decimal.DecimalException")] + DecimalException, + /// `decimal.Clamped`: an exponent was changed to fit the representation. + #[strum(serialize = "decimal.Clamped")] + DecimalClamped, + /// `decimal.InvalidOperation`: an operation with no meaningful result. + #[strum(serialize = "decimal.InvalidOperation")] + DecimalInvalidOperation, + /// `decimal.ConversionSyntax`: a malformed numeric string. + #[strum(serialize = "decimal.ConversionSyntax")] + DecimalConversionSyntax, + /// `decimal.DivisionByZero`: a finite non-zero dividend divided by zero. + #[strum(serialize = "decimal.DivisionByZero")] + DecimalDivisionByZero, + /// `decimal.DivisionImpossible`: an integer quotient too long for the precision. + #[strum(serialize = "decimal.DivisionImpossible")] + DecimalDivisionImpossible, + /// `decimal.DivisionUndefined`: zero divided by zero. + #[strum(serialize = "decimal.DivisionUndefined")] + DecimalDivisionUndefined, + /// `decimal.Inexact`: a result was rounded and lost non-zero digits. + #[strum(serialize = "decimal.Inexact")] + DecimalInexact, + /// `decimal.InvalidContext`: an invalid context setting was detected. + #[strum(serialize = "decimal.InvalidContext")] + DecimalInvalidContext, + /// `decimal.Rounded`: a result was rounded, perhaps without losing digits. + #[strum(serialize = "decimal.Rounded")] + DecimalRounded, + /// `decimal.Subnormal`: a result's exponent fell below `Emin`. + #[strum(serialize = "decimal.Subnormal")] + DecimalSubnormal, + /// `decimal.Overflow`: a result's exponent exceeded `Emax`. + #[strum(serialize = "decimal.Overflow")] + DecimalOverflow, + /// `decimal.Underflow`: a subnormal result was rounded. + #[strum(serialize = "decimal.Underflow")] + DecimalUnderflow, + /// `decimal.FloatOperation`: floats and Decimals were mixed. + #[strum(serialize = "decimal.FloatOperation")] + DecimalFloatOperation, +} +impl ExcType { + /// Checks if this exception type is a subclass of another exception type. + /// + /// Implements Python's exception hierarchy for try/except matching: + /// - `Exception` is the base class for all standard exceptions + /// - `LookupError` is the base for `KeyError` and `IndexError` + /// - `ArithmeticError` is the base for `ZeroDivisionError` and `OverflowError` + /// - `RuntimeError` is the base for `RecursionError` and `NotImplementedError` + /// + /// Returns true if `self` would be caught by `except handler_type:`. + #[must_use] + pub fn is_subclass_of(self, handler_type: Self) -> bool { + if self == handler_type || self.decimal_ancestors().contains(&handler_type) { + return true; + } + match handler_type { + // BaseException catches all exceptions + Self::BaseException => true, + // Exception catches everything except BaseException, and direct subclasses: KeyboardInterrupt, SystemExit + Self::Exception => !matches!(self, Self::BaseException | Self::KeyboardInterrupt | Self::SystemExit), + // LookupError catches KeyError and IndexError + Self::LookupError => matches!(self, Self::KeyError | Self::IndexError), + // ArithmeticError catches ZeroDivisionError and OverflowError + Self::ArithmeticError => matches!(self, Self::ZeroDivisionError | Self::OverflowError), + // RuntimeError catches RecursionError and NotImplementedError + Self::RuntimeError => matches!(self, Self::RecursionError | Self::NotImplementedError), + // AttributeError catches FrozenInstanceError + Self::AttributeError => matches!(self, Self::FrozenInstanceError), + // NameError catches UnboundLocalError + Self::NameError => matches!(self, Self::UnboundLocalError), + // io.UnsupportedOperation is here because CPython gives it dual + // OSError + ValueError parentage + Self::ValueError => matches!( + self, + Self::UnicodeDecodeError + | Self::UnicodeEncodeError + | Self::JsonDecodeError + | Self::TomlDecodeError + | Self::BinasciiError + | Self::UnsupportedOperation + ), + // ImportError catches ModuleNotFoundError + Self::ImportError => matches!(self, Self::ModuleNotFoundError), + // OSError catches FileNotFoundError, FileExistsError, IsADirectoryError, + // NotADirectoryError, PermissionError, io.UnsupportedOperation, and + // TimeoutError (an OSError subclass since Python 3.3) + Self::OSError => matches!( + self, + Self::FileNotFoundError + | Self::FileExistsError + | Self::IsADirectoryError + | Self::NotADirectoryError + | Self::PermissionError + | Self::UnsupportedOperation + | Self::TimeoutError + ), + // All other types only match exactly (handled by self == handler_type above) + _ => false, + } + } + + /// Every base of a `decimal` exception below `Exception`, in CPython's MRO order; + /// empty for every other type. + /// + /// The decimal signals inherit from several classes at once (`DivisionByZero` is + /// also a `ZeroDivisionError`, `Underflow` is `Inexact`, `Rounded` and `Subnormal`). + #[must_use] + pub fn decimal_ancestors(self) -> &'static [Self] { + const BASE: &[ExcType] = &[ExcType::DecimalException, ExcType::ArithmeticError]; + const INVALID: &[ExcType] = &[ + ExcType::DecimalInvalidOperation, + ExcType::DecimalException, + ExcType::ArithmeticError, + ]; + match self { + Self::DecimalException => &[Self::ArithmeticError], + Self::DecimalClamped + | Self::DecimalInvalidOperation + | Self::DecimalInexact + | Self::DecimalRounded + | Self::DecimalSubnormal => BASE, + Self::DecimalConversionSyntax | Self::DecimalDivisionImpossible | Self::DecimalInvalidContext => INVALID, + Self::DecimalDivisionUndefined => &[ + Self::DecimalInvalidOperation, + Self::DecimalException, + Self::ZeroDivisionError, + Self::ArithmeticError, + ], + Self::DecimalDivisionByZero => &[Self::DecimalException, Self::ZeroDivisionError, Self::ArithmeticError], + Self::DecimalOverflow => &[ + Self::DecimalInexact, + Self::DecimalRounded, + Self::DecimalException, + Self::ArithmeticError, + ], + Self::DecimalUnderflow => &[ + Self::DecimalInexact, + Self::DecimalRounded, + Self::DecimalSubnormal, + Self::DecimalException, + Self::ArithmeticError, + ], + Self::DecimalFloatOperation => &[Self::DecimalException, Self::ArithmeticError, Self::TypeError], + _ => &[], + } + } +} + +/// Structured payload attached to exception types whose CPython counterparts +/// carry more than a message. Currently unicode and json decode errors have +/// one; the enum leaves room for future variants (e.g. `OSError`'s +/// `errno`/`filename`) without another field on every exception. +#[derive(Debug, Clone, Default, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +pub enum ExcData { + /// No structured payload — every exception type without a variant below. + #[default] + None, + /// `UnicodeDecodeError` / `UnicodeEncodeError` constructor fields. + /// Boxed to keep the common `None` case (and every exception embedding + /// this enum) small. + Unicode(Box), + /// `json.JSONDecodeError` attribute fields. Boxed like + /// [`ExcData::Unicode`] to keep the enum small. + Json(Box), +} + +impl ExcData { + /// The unicode-error fields, if this is [`ExcData::Unicode`]. + #[must_use] + pub fn unicode(&self) -> Option<&UnicodeErrorData> { + match self { + Self::Unicode(data) => Some(data), + _ => None, + } + } + + /// The json-error fields, if this is [`ExcData::Json`]. + #[must_use] + pub fn json(&self) -> Option<&JsonErrorData> { + match self { + Self::Json(data) => Some(data), + _ => None, + } + } +} + +/// Structured fields of a `UnicodeDecodeError` / `UnicodeEncodeError`, +/// mirroring CPython's `encoding` / `object` / `start` / `end` / `reason` +/// exception attributes. +/// +/// Monty exceptions are otherwise message-only; unicode errors additionally +/// carry these fields so host bindings (e.g. `pydantic_monty`) can construct +/// real `UnicodeDecodeError` / `UnicodeEncodeError` instances instead of +/// falling back to a plain `ValueError`. The payload is omitted when the +/// offending object is larger than [`UnicodeErrorData::MAX_OBJECT_LEN`] — +/// exceptions can be stored and copied outside the sandbox's resource +/// tracker, so an unbounded payload would let huge inputs evade memory +/// limits. Sandboxed code never sees these fields (in-sandbox exceptions +/// expose only `args`). +#[derive(Debug, Clone, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +pub struct UnicodeErrorData { + /// The codec name as CPython reports it, e.g. `"utf-8"`, `"ascii"`. + pub encoding: String, + /// The full input that failed to encode/decode (`str` for encode errors, + /// `bytes` for decode errors), matching CPython's `exc.object`. + pub object: UnicodeErrorObject, + /// Start of the failing range: a character index for encode errors, a + /// byte offset for decode errors. + pub start: usize, + /// Exclusive end of the failing range, in the same units as `start`. + pub end: usize, + /// CPython's reason wording, e.g. `"ordinal not in range(128)"`. + pub reason: String, +} + +/// The `object` attribute of a unicode error: the input being converted. +#[derive(Debug, Clone, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +pub enum UnicodeErrorObject { + /// A decode error's input `bytes`. + Bytes(#[serde(with = "serde_bytes")] Vec), + /// An encode error's input `str`. + Str(String), +} + +impl UnicodeErrorData { + /// Payload size cap: unicode errors on objects larger than this carry no + /// structured data (hosts fall back to the message-only `ValueError`). + /// Exception payloads are copied into the host once they escape the worker, + /// so the cap bounds how much host memory a single raise can pin. + pub const MAX_OBJECT_LEN: usize = 64 * 1024; + + /// Builds the payload for an encode error on `object`, or + /// [`ExcData::None`] when `object` exceeds [`Self::MAX_OBJECT_LEN`]. + #[must_use] + pub fn encode(encoding: &str, object: &str, start: usize, end: usize, reason: &str) -> ExcData { + if object.len() <= Self::MAX_OBJECT_LEN { + ExcData::Unicode(Box::new(Self { + encoding: encoding.to_owned(), + object: UnicodeErrorObject::Str(object.to_owned()), + start, + end, + reason: reason.to_owned(), + })) + } else { + ExcData::None + } + } + + /// Builds the payload for a decode error on `object`, or + /// [`ExcData::None`] when `object` exceeds [`Self::MAX_OBJECT_LEN`]. + /// Public so `monty-fs` can build the payload for text-mode file reads. + #[must_use] + pub fn decode(encoding: &str, object: &[u8], start: usize, end: usize, reason: &str) -> ExcData { + if object.len() <= Self::MAX_OBJECT_LEN { + ExcData::Unicode(Box::new(Self { + encoding: encoding.to_owned(), + object: UnicodeErrorObject::Bytes(object.to_vec()), + start, + end, + reason: reason.to_owned(), + })) + } else { + ExcData::None + } + } +} + +/// Structured fields of a `json.JSONDecodeError`, mirroring CPython's `msg` / +/// `doc` / `pos` / `lineno` / `colno` exception attributes. `tomllib.TOMLDecodeError` +/// defines the same five attributes, so it carries this payload too. +/// +/// As with [`UnicodeErrorData`], the payload exists so host bindings can +/// construct a real `json.JSONDecodeError` instead of falling back to a plain +/// `ValueError`; sandboxed code never sees these fields. `lineno`/`colno` are +/// carried explicitly rather than recomputed from `doc` because `doc` may be +/// absent (see [`JsonErrorData::MAX_DOC_LEN`]). +#[derive(Debug, Clone, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +pub struct JsonErrorData { + /// The bare error message, without the `: line N column M (char K)` + /// suffix the formatted exception message carries. + pub msg: String, + /// The document being parsed, matching CPython's `exc.doc`. `None` when + /// the document exceeds [`JsonErrorData::MAX_DOC_LEN`] or is not valid + /// UTF-8 (`json.loads` on `bytes` input). + pub doc: Option, + /// Character index of the error in `doc`, matching CPython's `exc.pos`. + pub pos: usize, + /// 1-based line of the error, matching CPython's `exc.lineno`. + pub lineno: usize, + /// 1-based column of the error, matching CPython's `exc.colno`. + pub colno: usize, +} + +impl JsonErrorData { + /// Document size cap, mirroring [`UnicodeErrorData::MAX_OBJECT_LEN`]: + /// exception payloads are copied into the host once they escape the worker, + /// so `doc` is dropped (not truncated — a partial + /// document would misplace `pos`) for larger inputs. + pub const MAX_DOC_LEN: usize = 64 * 1024; + + /// Builds the payload for a decode error on `doc`, omitting the document + /// when it exceeds [`Self::MAX_DOC_LEN`] or is not valid UTF-8. + #[must_use] + pub fn build(msg: &str, doc: &[u8], pos: usize, lineno: usize, colno: usize) -> ExcData { + let doc = if doc.len() <= Self::MAX_DOC_LEN { + str::from_utf8(doc).ok().map(ToOwned::to_owned) + } else { + None + }; + ExcData::Json(Box::new(Self { + msg: msg.to_owned(), + doc, + pos, + lineno, + colno, + })) + } +} + +/// A single frame in a Python traceback. +/// +/// Contains all the information needed to display a traceback line: +/// the file location, function name, and optional source code preview. +/// +/// # Caret Markers +/// +/// Monty uses only `~` characters for caret markers in tracebacks, unlike CPython 3.11+ +/// which uses `~` for the function name and `^` for arguments (e.g., `~~~~~~~~~~~^^^^^^^^^^^`). +/// This simplification is intentional - Monty marks the entire expression span uniformly. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct StackFrame { + /// The filename where the code is located. + pub filename: String, + /// Start position in the source code. + pub start: CodeLoc, + /// End position in the source code. + pub end: CodeLoc, + /// The name of the frame (function name, or None for module-level code). + pub frame_name: Option, + /// The source code line for preview in the traceback. + /// + /// Stored as `Arc` rather than `String` so that consecutive frames + /// referencing the same source line — typical of recursion and tight + /// helper-function loops — share a single allocation. Without sharing, a + /// 1000-deep recursive call into code on a long line would clone the + /// entire line into each frame and amplify memory usage by the call + /// depth. Serialization roundtrips lose the sharing (each frame gets + /// its own `Arc`), but that is bounded by the wire size of the + /// traceback so does not regress the amplification. + pub preview_line: Option>, + /// Whether to hide the caret marker in the traceback for this frame. + /// + /// Set to `true` for: + /// - `raise` statements (CPython doesn't show carets for raise) + /// - `AttributeError` on attribute access (CPython doesn't show carets for these) + pub hide_caret: bool, + /// Whether to hide the `, in ` part of the frame line. + /// + /// Set to `true` for `SyntaxError` where CPython doesn't show the frame name. + /// CPython's SyntaxError format: ` File "...", line N` + /// vs runtime error format: ` File "...", line N, in ` + pub hide_frame_name: bool, +} + +impl fmt::Display for StackFrame { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // SyntaxError format: ` File "...", line N` + // Runtime error format: ` File "...", line N, in ` + if self.hide_frame_name { + write!(f, r#" File "{}", line {}"#, self.filename, self.start.line)?; + } else { + write!(f, r#" File "{}", line {}, in "#, self.filename, self.start.line)?; + if let Some(frame_name) = &self.frame_name { + f.write_str(frame_name)?; + } else { + f.write_str("")?; + } + } + + if let Some(line) = &self.preview_line { + if self.start.line != self.end.line { + // Multi-line statement range: `preview_line` holds a + // pre-rendered, dedented block (see `SourceMap::multiline_preview`). + // CPython prints each line at the 4-space frame indent with no + // caret markers. + f.write_char('\n')?; + for block_line in line.lines() { + writeln!(f, " {block_line}")?; + } + return Ok(()); + } + // Strip leading whitespace like CPython does + let trimmed = line.trim_start(); + writeln!(f, "\n {trimmed}")?; + + // Hide caret for raise statements, AttributeError, etc. + if !self.hide_caret { + let leading_spaces = line.len() - trimmed.len(); + // Calculate caret position relative to the trimmed line + // Column is 1-indexed, so subtract 1, then subtract leading spaces we stripped + let caret_start = if self.start.column as usize > leading_spaces { + 4 + self.start.column as usize - leading_spaces - 1 + } else { + 4 + }; + f.write_str(&" ".repeat(caret_start))?; + // Always render at least one caret, even for zero-length ranges + // (e.g. a SyntaxError pointing just past the end of a truncated token). + let caret_len = (self.end.column - self.start.column).max(1) as usize; + writeln!(f, "{}", "~".repeat(caret_len))?; + } + } else { + f.write_char('\n')?; + } + Ok(()) + } +} + +/// A line and column position in source code. +/// +/// Uses 1-based indexing for both line and column to match Python's conventions. +/// +/// `u32` matches `ruff_text_size::TextSize`, which underpins all source ranges +/// returned by the parser, so conversions between the two are zero-cost. +#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +pub struct CodeLoc { + /// Line number (1-based). + #[serde(rename = "L")] + pub line: u32, + /// Column number (1-based), counted in characters (not bytes). + #[serde(rename = "C")] + pub column: u32, +} + +impl Default for CodeLoc { + fn default() -> Self { + Self { line: 1, column: 1 } + } +} + +impl CodeLoc { + /// Creates a new CodeLoc from 0-based values. + /// + /// Lines and columns numbers are 1-indexed for display, hence `+ 1`. + /// Saturates at `u32::MAX` rather than panicking — overflow here is + /// already unreachable for any source ruff will accept (it caps source + /// size at 4 GiB), and saturation keeps the parser panic-free even if + /// that ever changes. + #[must_use] + pub fn new(line: u32, column: u32) -> Self { + Self { + line: line.saturating_add(1), + column: column.saturating_add(1), + } + } +} + +/// The source range of the expression that suspended execution, carried by +/// every suspension. +/// +/// `start` and `end` are UTF-8 byte offsets into the named source, `end` +/// exclusive: slice the source's bytes (in Python, `source.encode()[start:end]`) +/// rather than indexing the string. A peer that sends no position reads as +/// [`Self::unknown`]. +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct SourceRange { + /// The source the range indexes, named as a traceback frame names it: an + /// in-process one-shot run's script name, `` for a feed, + /// `` in `eval()` / `exec()`. + pub filename: String, + /// Byte offset where the expression starts. + pub start: u32, + /// Byte offset where the expression ends (exclusive). + pub end: u32, +} + +impl SourceRange { + /// Longest `filename` a range carries, in bytes, so a peer cannot make hosts copy a huge name. + pub const MAX_FILENAME_LEN: usize = 256; + + /// Builds a range, cutting `filename` on a char boundary. + #[must_use] + pub fn new(filename: &str, start: u32, end: u32) -> Self { + let mut len = filename.len().min(Self::MAX_FILENAME_LEN); + while !filename.is_char_boundary(len) { + len -= 1; + } + Self { + filename: filename[..len].to_owned(), + start, + end, + } + } + + /// The range a host reports when its peer sent no position: an empty + /// filename and an empty range at offset zero. + #[must_use] + pub fn unknown() -> Self { + Self { + filename: String::new(), + start: 0, + end: 0, + } + } +} + +/// Formats the message for a `UnicodeDecodeError` covering the byte range +/// `start..end`: CPython's single-byte form (`byte 0x{first_byte:02x} in +/// position {start}`) when the range is one byte, otherwise the range form +/// (`bytes in position {start}-{end - 1}`). +/// +/// A free function (rather than folded into `ExcType::unicode_decode_error`), +/// public and re-exported at the crate root, so `monty-fs` can produce the +/// identical wording when converting a `MountError::InvalidUtf8` from a +/// text-mode file read into an exception. +#[must_use] +pub fn unicode_decode_error_msg(codec: &str, first_byte: u8, start: usize, end: usize, reason: &str) -> String { + // Callers must pass a non-empty range; checked in debug builds only so a + // wrong caller can't panic the VM in release (it gets a garbled message + // position instead, which is harmless). + debug_assert!( + end > start, + "unicode_decode_error_msg: end ({end}) must be > start ({start})" + ); + if end - start == 1 { + format!("'{codec}' codec can't decode byte 0x{first_byte:02x} in position {start}: {reason}") + } else { + let last = end - 1; + format!("'{codec}' codec can't decode bytes in position {start}-{last}: {reason}") + } +} diff --git a/crates/bashkit-monty-types/src/file_mode.rs b/crates/bashkit-monty-types/src/file_mode.rs new file mode 100644 index 000000000..6037cc186 --- /dev/null +++ b/crates/bashkit-monty-types/src/file_mode.rs @@ -0,0 +1,211 @@ +//! [`FileMode`] — the parsed, validated form of a Python `open()` mode +//! string, carried by [`MontyFileHandle`](crate::object::MontyFileHandle). + +use std::{borrow::Cow, str::FromStr}; +/// A parsed Python `open()` mode. +/// +/// This single enum captures everything that matters about how a file was +/// opened: the access pattern (`r`/`w`/`a` and the `+` update flag) and +/// whether the file is binary. The variant name encodes the access pattern; +/// the `bool` payload is `true` for binary and `false` for text — i.e. +/// `Read(true)` is `'rb'` and `Read(false)` is `'r'`. +/// +/// Construct one with the [`FromStr`] impl (`mode_str.parse::()`). +/// The original input string is +/// intentionally not preserved; [`FileMode::as_str`] rebuilds the canonical +/// CPython form (`'r'`, `'rb+'`, `'wb'`, …), matching how CPython itself +/// normalizes input like `'rt'` → `'r'` and `'r+b'` → `'rb+'`. +/// +/// `+` update modes (`ReadUpdate`/`WriteUpdate`/`AppendUpdate`) are reserved +/// in the enum so the mode space is fully represented, but [`FromStr`] +/// currently rejects them — properly modelling them needs read-position +/// tracking that the file wrapper does not yet implement. Treat the `Update` +/// variants as unreachable at runtime; do not pattern-match against them as +/// if they were a valid result of parsing user input. +/// +/// Carried publicly by [`MontyFileHandle`](crate::MontyFileHandle) so a host servicing file +/// operations can inspect the mode without re-parsing the raw string. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum FileMode { + /// `r` / `rb`: read-only; the file must already exist. + Read(bool), + /// `r+` / `rb+`: read and write an existing file. Reserved; not yet + /// produced by [`FromStr`]. + ReadUpdate(bool), + /// `w` / `wb`: write-only; truncate the file (creating it if missing) on open. + Write(bool), + /// `w+` / `wb+`: read and write; truncate the file (creating it if missing). + /// Reserved; not yet produced by [`FromStr`]. + WriteUpdate(bool), + /// `a` / `ab`: write-only appending; create the file if missing, preserving content. + Append(bool), + /// `a+` / `ab+`: read and append; create the file if missing, preserving content. + /// Reserved; not yet produced by [`FromStr`]. + AppendUpdate(bool), +} +impl FileMode { + /// Returns the canonical Python `open()` mode string for this mode, + /// matching what CPython exposes via `file.mode`. + /// + /// The result is always one of the 12 well-formed mode strings (`r`, `rb`, + /// `r+`, `rb+`, `w`, `wb`, `w+`, `wb+`, `a`, `ab`, `a+`, `ab+`). This is + /// the canonical form CPython itself normalizes user input into — e.g. + /// `'rt'` → `'r'`, `'r+b'` → `'rb+'`, `'br'` → `'rb'`. + #[must_use] + pub fn as_str(&self) -> &'static str { + match self { + Self::Read(false) => "r", + Self::Read(true) => "rb", + Self::ReadUpdate(false) => "r+", + Self::ReadUpdate(true) => "rb+", + Self::Write(false) => "w", + Self::Write(true) => "wb", + Self::WriteUpdate(false) => "w+", + Self::WriteUpdate(true) => "wb+", + Self::Append(false) => "a", + Self::Append(true) => "ab", + Self::AppendUpdate(false) => "a+", + Self::AppendUpdate(true) => "ab+", + } + } + + /// Whether the file is binary (`'rb'`, `'wb'`, …) rather than text. + #[must_use] + pub fn is_binary(&self) -> bool { + let (Self::Read(b) + | Self::ReadUpdate(b) + | Self::Write(b) + | Self::WriteUpdate(b) + | Self::Append(b) + | Self::AppendUpdate(b)) = self; + *b + } + + /// Whether `read()` is allowed by this mode. + #[must_use] + pub fn readable(&self) -> bool { + matches!( + self, + Self::Read(_) | Self::ReadUpdate(_) | Self::WriteUpdate(_) | Self::AppendUpdate(_) + ) + } + + /// Whether `write()` is allowed by this mode. + #[must_use] + pub fn writable(&self) -> bool { + matches!( + self, + Self::Write(_) | Self::WriteUpdate(_) | Self::Append(_) | Self::AppendUpdate(_) | Self::ReadUpdate(_) + ) + } + + /// Whether writes should always append (`a`/`a+`). + #[must_use] + pub fn is_append(&self) -> bool { + matches!(self, Self::Append(_) | Self::AppendUpdate(_)) + } + + /// Whether `open()` must truncate the file to empty immediately (`w`/`w+`). + #[must_use] + pub fn truncate(&self) -> bool { + matches!(self, Self::Write(_) | Self::WriteUpdate(_)) + } + + /// Whether `open()` must create the file immediately if missing. + /// + /// True for the `w`/`w+` and `a`/`a+` families. For append modes this must + /// not disturb existing content. + #[must_use] + pub fn create(&self) -> bool { + matches!( + self, + Self::Write(_) | Self::WriteUpdate(_) | Self::Append(_) | Self::AppendUpdate(_) + ) + } + /// Returns the bare Python type name (`type(f).__name__`) for this mode. + #[must_use] + pub fn type_name(&self) -> &'static str { + match self { + _ if !self.is_binary() => "TextIOWrapper", + Self::ReadUpdate(_) | Self::WriteUpdate(_) | Self::AppendUpdate(_) => "BufferedRandom", + Self::Read(_) => "BufferedReader", + Self::Write(_) | Self::Append(_) => "BufferedWriter", + } + } + + /// Returns the fully-qualified `_io` wrapper type name a file opened with + /// this mode presents as, matching CPython's `repr(f)` (e.g. + /// `"_io.TextIOWrapper"`). The module-less form is [`type_name`](Self::type_name). + #[must_use] + pub fn file_type_name(&self) -> &'static str { + match self { + _ if !self.is_binary() => "_io.TextIOWrapper", + Self::ReadUpdate(_) | Self::WriteUpdate(_) | Self::AppendUpdate(_) => "_io.BufferedRandom", + Self::Read(_) => "_io.BufferedReader", + Self::Write(_) | Self::Append(_) => "_io.BufferedWriter", + } + } +} +/// Parses a Python `open()` mode string into a [`FileMode`]. +/// +/// Monty supports the common read, write, append, and update combinations in +/// text or binary form. Exclusive creation (`x`) is rejected for now because +/// it needs a dedicated mount-table operation to be race-free. +/// +/// The `Err` payload is a CPython-matched message — an unknown mode +/// character, duplicated `b`/`t`/`+`, conflicting binary+text flags, more +/// than one of the `r`/`w`/`a` actions, or none at all (`''`, `'b'`, `'t'`). +impl FromStr for FileMode { + type Err = Cow<'static, str>; + + fn from_str(mode: &str) -> Result { + let mut action = None; + let mut binary = false; + let mut text = false; + + for ch in mode.chars() { + match ch { + 'r' | 'w' | 'a' => { + if action.replace(ch).is_some() { + // CPython's duplicate-action message differs from the missing-action + // one below (lowercase, no `... and at most one plus` suffix). + return Err("must have exactly one of create/read/write/append mode".into()); + } + } + 'x' => return Err("exclusive creation mode is not supported".into()), + 'b' => { + if binary { + return Err("invalid mode: binary mode specified twice".into()); + } + binary = true; + } + 't' => { + if text { + return Err("invalid mode: text mode specified twice".into()); + } + text = true; + } + // `+` modes (`r+`, `w+`, `a+`, and their `b` variants) need + // read-position tracking that Monty does not yet implement. + // Reject them outright rather than silently truncating on the + // first write (which would happen because the OS-level read + // and write ops are full-file one-shots). + '+' => return Err("update modes ('+') are not yet supported".into()), + _ => return Err(format!("invalid mode: {ch:?}").into()), + } + } + + if binary && text { + return Err("can't have text and binary mode at once".into()); + } + let Some(action) = action else { + return Err("Must have exactly one of create/read/write/append mode and at most one plus".into()); + }; + + Ok(match action { + 'w' => Self::Write(binary), + 'a' => Self::Append(binary), + _ => Self::Read(binary), + }) + } +} diff --git a/crates/bashkit-monty-types/src/format.rs b/crates/bashkit-monty-types/src/format.rs new file mode 100644 index 000000000..86d8663e7 --- /dev/null +++ b/crates/bashkit-monty-types/src/format.rs @@ -0,0 +1,344 @@ +//! Pure CPython-compatible formatting helpers shared by the boundary types: +//! string/bytes `repr()` escaping, shortest-round-trip float rendering, and +//! timezone-offset `timedelta` reprs. + +use std::fmt::{self, Write}; + +use unicode_general_category::{GeneralCategory, get_general_category}; +/// Writes a Python `repr()` string for a given string slice to a formatter. +/// +/// Quote choice matches CPython: single quotes by default, switching to double +/// quotes only when the string contains a `'` but no `"` (so the quote needn't +/// be escaped). Backslash, the active quote, and `\n`/`\t`/`\r` use the short +/// escapes; any other **non-printable** character is escaped numerically +/// (`\xNN`/`\uNNNN`/`\UNNNNNNNN`), e.g. `repr('\x00') == "'\\x00'"` and +/// `repr('\xa0') == "'\\xa0'"`. +/// +/// "Non-printable" matches CPython's `str.isprintable` (see +/// `repr_needs_escape`): Unicode categories `C*` and `Z*`, except the ASCII +/// space. Category data comes from `unicode-general-category`, whose Unicode +/// version may differ slightly from CPython's, affecting only recently +/// (re)assigned code points. +pub fn string_repr_fmt(s: &str, f: &mut impl Write) -> fmt::Result { + let quote = if s.contains('\'') && !s.contains('"') { + '"' + } else { + '\'' + }; + f.write_char(quote)?; + for c in s.chars() { + match c { + '\\' => f.write_str("\\\\")?, + '\n' => f.write_str("\\n")?, + '\t' => f.write_str("\\t")?, + '\r' => f.write_str("\\r")?, + _ if c == quote => { + f.write_char('\\')?; + f.write_char(quote)?; + } + _ if repr_needs_escape(c) => write_char_escape(c, f)?, + _ => f.write_char(c)?, + } + } + f.write_char(quote) +} + +/// Whether `c` is escaped numerically in a Python `repr` — i.e. it is not +/// "printable" in CPython's sense. +/// +/// Non-printable = Unicode general categories `Other` (`Cc`, `Cf`, `Cs`, `Co`, +/// `Cn`) and `Separator` (`Zl`, `Zp`, `Zs`), with the sole exception of the +/// ASCII space `U+0020`. The `\t`/`\n`/`\r` short escapes are handled by the +/// caller before this is consulted. +fn repr_needs_escape(c: char) -> bool { + c != ' ' + && matches!( + get_general_category(c), + GeneralCategory::Control + | GeneralCategory::Format + | GeneralCategory::Surrogate + | GeneralCategory::PrivateUse + | GeneralCategory::Unassigned + | GeneralCategory::LineSeparator + | GeneralCategory::ParagraphSeparator + | GeneralCategory::SpaceSeparator + ) +} + +/// Writes the numeric repr escape for a single character, matching CPython's +/// width selection: `\xNN` for code points `<= 0xFF`, `\uNNNN` for `<= 0xFFFF`, +/// otherwise `\UNNNNNNNN`. +fn write_char_escape(c: char, f: &mut impl Write) -> fmt::Result { + let cp = c as u32; + if cp <= 0xFF { + write!(f, "\\x{cp:02x}") + } else if cp <= 0xFFFF { + write!(f, "\\u{cp:04x}") + } else { + write!(f, "\\U{cp:08x}") + } +} + +/// Formatter for a Python repr() string. +#[derive(Debug)] +pub struct StringRepr<'a>(pub &'a str); + +impl fmt::Display for StringRepr<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + string_repr_fmt(self.0, f) + } +} +/// Writes a CPython-compatible repr string for bytes to a formatter. +/// +/// Format: `b'...'` or `b"..."` depending on content. +/// - Uses single quotes by default +/// - Switches to double quotes if bytes contain `'` but not `"` +/// - Escapes: `\\`, `\t`, `\n`, `\r`, `\xNN` for non-printable bytes +pub fn bytes_repr_fmt(bytes: &[u8], f: &mut impl Write) -> fmt::Result { + // Determine quote character: use double quotes if single quote present but not double + let has_single = bytes.contains(&b'\''); + let has_double = bytes.contains(&b'"'); + let quote = if has_single && !has_double { '"' } else { '\'' }; + + f.write_char('b')?; + f.write_char(quote)?; + + for &byte in bytes { + match byte { + b'\\' => f.write_str("\\\\")?, + b'\t' => f.write_str("\\t")?, + b'\n' => f.write_str("\\n")?, + b'\r' => f.write_str("\\r")?, + b'\'' if quote == '\'' => f.write_str("\\'")?, + b'"' if quote == '"' => f.write_str("\\\"")?, + // Printable ASCII (32-126) + 0x20..=0x7e => f.write_char(byte as char)?, + // Non-printable: use \xNN format + _ => write!(f, "\\x{byte:02x}")?, + } + } + + f.write_char(quote) +} + +/// Returns a CPython-compatible repr string for bytes. +/// +/// Convenience wrapper around `bytes_repr_fmt` that returns an owned String. +#[must_use] +#[expect(clippy::missing_panics_doc, reason = "writing to a String cannot fail")] +pub fn bytes_repr(bytes: &[u8]) -> String { + let mut result = String::new(); + // Writing to String never fails + bytes_repr_fmt(bytes, &mut result).unwrap(); + result +} +/// A [`Display`](fmt::Display) adapter that writes a float exactly as CPython's +/// `repr()`/`str()` (identical for floats in Python 3): the shortest decimal +/// string that round-trips, switching to scientific notation when the base-10 +/// exponent is `< -4` or `>= 16`, and always keeping at least one fractional +/// digit (`1.0`, never `1`) — `1e16` → `"1e+16"`, `1234.5` → `"1234.5"`, +/// `inf`/`nan` lowercased. +/// +/// This is the default rendering for a bare `f"{x}"`, `str(x)`, `repr(x)` and +/// floats inside container reprs — *not* the format mini-language (that's +/// `format_float_g` et al, in `monty`). Rust can't do this directly: its `f64` `Display` +/// never uses scientific notation (`1e16` prints as `10000000000000000`) and +/// renders NaN as `"NaN"`. +/// +/// As a `Display` adapter it writes straight to the caller's sink with **no +/// heap allocation**: it borrows Rust's *shortest-digits* guarantee via `{:e}` +/// into a small stack buffer (an `f64` `{:e}` is ASCII and ≤ 24 bytes) and +/// re-lays-out those digits per CPython's rules. +pub struct FormatFloat(pub f64); + +impl fmt::Display for FormatFloat { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let v = self.0; + if v.is_nan() { + return f.write_str("nan"); + } + if v.is_sign_negative() { + f.write_char('-')?; + } + if v.is_infinite() { + return f.write_str("inf"); + } + // Rust's shortest scientific form gives minimal round-tripping digits + // plus the base-10 exponent (`1234.5` → `"1.2345e3"`, `0.0` → `"0e0"`), + // captured in a stack buffer so nothing touches the heap. + let mut sci = StackStr::new(); + write!(sci, "{:e}", v.abs())?; + let sci = sci.as_str(); + let (mantissa, exp_str) = sci.split_once('e').ok_or(fmt::Error)?; + // `{:e}` always emits a single leading digit, so the integer part is one + // char and the fraction (if any) follows the `.`. + let (int_part, frac) = mantissa.split_once('.').unwrap_or((mantissa, "")); + let exp10: i32 = exp_str.parse().map_err(|_| fmt::Error)?; + let ndigits = int_part.len() + frac.len(); + // `decpt` = number of digits to the left of the decimal point. + let decpt = exp10 + 1; + + if !(-4..16).contains(&exp10) { + // Scientific: leading digit, optional fraction, then `e±NN`. + f.write_str(int_part)?; + if !frac.is_empty() { + f.write_char('.')?; + f.write_str(frac)?; + } + let exp_sign = if exp10 < 0 { '-' } else { '+' }; + write!(f, "e{exp_sign}{:02}", exp10.unsigned_abs()) + } else if decpt <= 0 { + // `0.00…digits` — `-decpt` leading zeros after the point. + f.write_str("0.")?; + for _ in 0..-decpt { + f.write_char('0')?; + } + f.write_str(int_part)?; + f.write_str(frac) + } else { + let decpt = usize::try_from(decpt).expect("decpt is positive in this branch"); + if decpt >= ndigits { + // Integer-valued: digits, zeros up to the point, then `.0`. + f.write_str(int_part)?; + f.write_str(frac)?; + for _ in 0..decpt - ndigits { + f.write_char('0')?; + } + f.write_str(".0") + } else { + // Point falls inside the digit run. `int_part` is a single digit + // and `decpt >= 1`, so the split always lands within `frac`. + f.write_str(int_part)?; + let split = decpt - int_part.len(); + f.write_str(&frac[..split])?; + f.write_char('.')?; + f.write_str(&frac[split..]) + } + } + } +} + +/// A fixed-capacity [`fmt::Write`] sink backed by a stack array, used to capture +/// a bounded `{:e}` rendering without a heap allocation. +/// +/// 32 bytes comfortably holds any `f64` `{:e}` output (the longest is ~24 ASCII +/// bytes, e.g. `2.2250738585072014e-308`). A write that would overflow returns +/// [`fmt::Error`] rather than panicking — unreachable for the bounded `f64` +/// case, but it keeps the type panic-free for any future caller. +struct StackStr { + buf: [u8; 32], + len: usize, +} + +impl StackStr { + fn new() -> Self { + Self { buf: [0; 32], len: 0 } + } + + fn as_str(&self) -> &str { + // Only `{:e}` of an `f64` is written here, which is always valid ASCII. + str::from_utf8(&self.buf[..self.len]).unwrap_or("") + } +} + +impl fmt::Write for StackStr { + fn write_str(&mut self, s: &str) -> fmt::Result { + let end = self.len.checked_add(s.len()).ok_or(fmt::Error)?; + let slot = self.buf.get_mut(self.len..end).ok_or(fmt::Error)?; + slot.copy_from_slice(s.as_bytes()); + self.len = end; + Ok(()) + } +} + +/// A [`Display`](fmt::Display) adapter writing a complex number as CPython's +/// `repr()`/`str()`: `(1+2j)`, `1j`, `(-0-1j)`, `(nan+infj)`. +/// +/// Each part is the [`FormatFloat`] rendering with an integral value's `.0` +/// dropped (`1.0` → `1`, but `1e+16` stays). A real part that is exactly `+0.0` +/// is omitted along with the parentheses, so `complex(0, 1)` is `1j` while +/// `complex(-0.0, 1)` is `(-0+1j)`. Allocation-free like [`FormatFloat`]. +pub struct FormatComplex { + /// The real part. + pub real: f64, + /// The imaginary part. + pub imag: f64, +} + +impl fmt::Display for FormatComplex { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.real == 0.0 && self.real.is_sign_positive() { + write_complex_part(f, self.imag, false)?; + } else { + f.write_char('(')?; + write_complex_part(f, self.real, false)?; + write_complex_part(f, self.imag, true)?; + f.write_str("j)")?; + return Ok(()); + } + f.write_char('j') + } +} + +/// Writes one component of a complex repr: the float repr without a trailing +/// `.0`, prefixed with `+` when `signed` and the value is not negative. +fn write_complex_part(f: &mut impl Write, value: f64, signed: bool) -> fmt::Result { + let mut buf = StackStr::new(); + write!(buf, "{}", FormatFloat(value))?; + let text = buf.as_str(); + let text = text.strip_suffix(".0").unwrap_or(text); + // `FormatFloat` already leads negative values (including `-0.0` and + // `-inf`) with `-`; NaN never carries a sign. + if signed && !text.starts_with('-') { + f.write_char('+')?; + } + f.write_str(text) +} + +/// Classifies an invalid-UTF-8 error into CPython's reason wording, from the +/// first unexpected byte and `Utf8Error::error_len()`. +/// +/// `error_len == None` means the input ended mid-sequence (`unexpected end of +/// data`); otherwise a byte that is a legal multi-byte lead (0xC2–0xF4) was +/// followed by an invalid continuation, and anything else (stray +/// continuation bytes, the overlong leads 0xC0/0xC1, 0xF5–0xFF) is an +/// `invalid start byte`. Public (re-exported at the crate root) so `monty-fs` +/// produces identical wording for text-mode file reads. +#[must_use] +pub fn utf8_error_reason(first_bad_byte: u8, error_len: Option) -> &'static str { + if error_len.is_none() { + "unexpected end of data" + } else if (0xC2..=0xF4).contains(&first_bad_byte) { + "invalid continuation byte" + } else { + "invalid start byte" + } +} + +/// Formats the canonical `datetime.timedelta(...)` repr for a fixed timezone +/// offset in seconds, normalized like Python's `timedelta` (`days` may be +/// negative, `seconds` in `0..86400`) — e.g. `-18000` → +/// `datetime.timedelta(days=-1, seconds=68400)`. Used by the +/// `datetime.timezone` reprs of boundary values. +#[must_use] +pub fn format_offset_timedelta_repr(offset_seconds: i32) -> String { + const SECONDS_PER_DAY: i32 = 86_400; + let days = offset_seconds.div_euclid(SECONDS_PER_DAY); + let seconds = offset_seconds.rem_euclid(SECONDS_PER_DAY); + if days == 0 && seconds == 0 { + "datetime.timedelta(0)".to_owned() + } else { + let mut out = String::from("datetime.timedelta("); + if days != 0 { + write!(out, "days={days}").expect("writing to String never fails"); + } + if seconds != 0 { + if days != 0 { + out.push_str(", "); + } + write!(out, "seconds={seconds}").expect("writing to String never fails"); + } + out.push(')'); + out + } +} diff --git a/crates/bashkit-monty-types/src/graph.rs b/crates/bashkit-monty-types/src/graph.rs new file mode 100644 index 000000000..038f0a31d --- /dev/null +++ b/crates/bashkit-monty-types/src/graph.rs @@ -0,0 +1,652 @@ +//! [`MontyGraph`], the flat node arena Python values cross the sandbox +//! boundary in, and [`MontyNode`], one entry of it. +//! +//! A tree would copy a shared sub-object once per reference, so a small heap +//! graph could become an exponentially larger message. The arena keeps the +//! heap's shape: a container holds the ids of its children, a sub-object +//! referenced twice is one node referenced twice, and a message carries one +//! arena plus the ids of its roots ([`MontyObject`](crate::MontyObject), +//! [`CallArgs`](crate::CallArgs)). +//! +//! Nodes are in post-order: every child id is lower than the id of the node +//! holding it, so a decoder builds values in one forward pass without +//! recursion and no arena can contain a cycle. A reference back to an +//! enclosing container is instead a [`MontyNode::Cycle`] leaf holding the +//! placeholder its repr shows. + +use std::{error::Error, fmt, mem::size_of}; + +use num_bigint::BigInt; + +use crate::{ + builtins::BuiltinsFunctions, + exceptions::ExcType, + object::{ + MontyComplex, MontyDate, MontyDateTime, MontyFileHandle, MontyTime, MontyTimeDelta, MontyTimeZone, MontyType, + }, + uuid::MontyUuid, +}; + +/// Index of a node in a [`MontyGraph`]. +/// +/// Only meaningful together with the arena it was issued by: ids are dense +/// positions, not identities, and [`MontyGraph::merge`] rebases them. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +pub struct NodeId(pub u32); + +impl NodeId { + /// The id as a vector index. + #[must_use] + pub fn index(self) -> usize { + self.0 as usize + } +} + +impl fmt::Display for NodeId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} + +/// One entry of a [`MontyGraph`]: a leaf value, or a container holding the +/// ids of its children. +/// +/// A non-builtin class is its own [`ClassType`](Self::ClassType) node, shared +/// by every instance of it. Build values with the +/// [`MontyObject`](crate::MontyObject) constructors rather than from nodes. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum MontyNode { + /// Python's `Ellipsis` singleton (`...`). + Ellipsis, + /// Python's `NotImplemented` singleton. + NotImplemented, + /// Python's `None` singleton. + None, + /// Python boolean. + Bool(bool), + /// Python integer fitting in 64 bits. + Int(i64), + /// Python integer wider than 64 bits. + BigInt(BigInt), + /// Python float. + Float(f64), + /// Python complex. + Complex(MontyComplex), + /// Python string. + String(String), + /// Python bytes. + Bytes(#[serde(with = "serde_bytes")] Vec), + /// Python `datetime.date`. + Date(MontyDate), + /// Python `datetime.datetime`. + DateTime(MontyDateTime), + /// Python `datetime.time`. + Time(MontyTime), + /// Python `datetime.timedelta`. + TimeDelta(MontyTimeDelta), + /// Python `datetime.timezone`. + TimeZone(MontyTimeZone), + /// Python `decimal.Decimal`, as its canonical string (`str(d)`: `"1.20"`, + /// `"1E+5"`, `"-NaN12"`, `"Infinity"`), which round-trips exactly. + /// + /// The sandbox validates the text on import; a malformed one is rejected there. + Decimal(String), + /// A Python exception value with type and optional message. + Exception { + /// The exception type. + exc_type: ExcType, + /// Optional string argument passed to the exception constructor. + arg: Option, + }, + /// A builtin type object; a non-builtin class is a [`ClassType`](Self::ClassType) node. + Type(MontyType), + /// A builtin function such as `len`. + BuiltinFunction(BuiltinsFunctions), + /// A `pathlib.Path` (always a virtual POSIX path). + Path(String), + /// An open file object. + FileHandle(MontyFileHandle), + /// An external function provided by the host. + Function { + /// The function name. + name: String, + /// Optional docstring. + docstring: Option, + }, + /// Output-only fallback: the `repr()` of a value with no other representation. + Repr(String), + /// Output-only: a reference back to a container that encloses this node, + /// as the placeholder its repr shows (`[...]`, `(...)`, `{...}` or `...`). + Cycle(String), + /// Python list: ids of its items. + List(Vec), + /// Python tuple: ids of its items. + Tuple(Vec), + /// Python set: ids of its elements. + Set(Vec), + /// Python frozenset: ids of its elements. + FrozenSet(Vec), + /// Python named tuple: field names and the ids of the values. + NamedTuple { + /// Type name used in repr, e.g. `os.stat_result`. + type_name: String, + /// Attribute names, one per value. + field_names: Vec, + /// Ids of the values, in field order. + values: Vec, + }, + /// Python dict: `(key, value)` id pairs in insertion order. + Dict(Vec<(NodeId, NodeId)>), + /// A sandbox- or host-defined class, shared by every instance of it. + /// Boxed so the variant does not widen the node. + ClassType(Box), + /// An instance of a non-builtin class. + ClassInstance { + /// Id of the instance's [`ClassType`](Self::ClassType) node. + class_type: NodeId, + /// Identity of the instance, generated by whichever side defined it. + instance_id: MontyUuid, + /// Eagerly-sent attributes as `(name, value)` id pairs. + attrs: Vec<(NodeId, NodeId)>, + }, + /// A host-provided module: imports as a sandbox `module` object whose + /// attributes are `attrs`, and exports back with the same `id`. + Module { + /// The dotted module name, e.g. `pkg.sub`. + name: String, + /// Identity of the module, generated by the host that defined it. + id: MontyUuid, + /// The module's attributes as `(name, value)` id pairs. + attrs: Vec<(NodeId, NodeId)>, + }, +} + +impl MontyNode { + /// Calls `f` with every child id this node holds, in order; for + /// [`ClassInstance`](Self::ClassInstance) the class id comes first. + pub fn for_each_child(&self, mut f: impl FnMut(NodeId)) { + match self { + Self::List(ids) | Self::Tuple(ids) | Self::Set(ids) | Self::FrozenSet(ids) => { + ids.iter().copied().for_each(f); + } + Self::NamedTuple { values, .. } => values.iter().copied().for_each(f), + Self::Dict(pairs) => pairs.iter().for_each(|(key, value)| { + f(*key); + f(*value); + }), + Self::ClassType(class) => class.attrs.iter().for_each(|(key, value)| { + f(*key); + f(*value); + }), + Self::ClassInstance { class_type, attrs, .. } => { + f(*class_type); + for (key, value) in attrs { + f(*key); + f(*value); + } + } + Self::Module { attrs, .. } => attrs.iter().for_each(|(key, value)| { + f(*key); + f(*value); + }), + _ => {} + } + } + + /// Mutable counterpart of [`for_each_child`](Self::for_each_child), used to + /// rebase ids when arenas are merged. + pub fn for_each_child_mut(&mut self, mut f: impl FnMut(&mut NodeId)) { + match self { + Self::List(ids) | Self::Tuple(ids) | Self::Set(ids) | Self::FrozenSet(ids) => ids.iter_mut().for_each(f), + Self::NamedTuple { values, .. } => values.iter_mut().for_each(f), + Self::Dict(pairs) => pairs.iter_mut().for_each(|(key, value)| { + f(key); + f(value); + }), + Self::ClassType(class) => class.attrs.iter_mut().for_each(|(key, value)| { + f(key); + f(value); + }), + Self::ClassInstance { class_type, attrs, .. } => { + f(class_type); + for (key, value) in attrs { + f(key); + f(value); + } + } + Self::Module { attrs, .. } => attrs.iter_mut().for_each(|(key, value)| { + f(key); + f(value); + }), + _ => {} + } + } + + /// The placeholder a reference back to this node renders as, matching + /// CPython's recursive `repr()` markers. + #[must_use] + pub fn cycle_placeholder(&self) -> &'static str { + match self { + Self::List(_) => "[...]", + Self::Tuple(_) | Self::NamedTuple { .. } => "(...)", + Self::Dict(_) => "{...}", + _ => "...", + } + } + + /// Whether the node holds no child ids. + #[must_use] + pub fn is_leaf(&self) -> bool { + let mut leaf = true; + self.for_each_child(|_| leaf = false); + leaf + } + + /// The host footprint of one owned string in a metadata vector, such as + /// a namedtuple's field names. + #[must_use] + pub const fn metadata_string_size(value: &str) -> usize { + size_of::().saturating_add(value.len()) + } + + /// Host footprint of this node once decoded: the fixed enum size plus the + /// bytes it owns directly (string, bytes and bigint payloads, field + /// names, and its child-id vectors). Children charge themselves, so an + /// arena's footprint is the plain sum over its nodes. + #[must_use] + pub fn decoded_size(&self) -> usize { + let name_len = |name: &Option| -> usize { name.as_ref().map_or(0, String::len) }; + let ids = |ids: &[NodeId]| ids.len().saturating_mul(size_of::()); + let pairs = |pairs: &[(NodeId, NodeId)]| pairs.len().saturating_mul(2 * size_of::()); + + let payload = match self { + Self::String(s) | Self::Path(s) | Self::Repr(s) | Self::Cycle(s) | Self::Decimal(s) => s.len(), + Self::Bytes(b) => b.len(), + // Saturate rather than truncate on a 32-bit `usize`: an over-large + // estimate only trips a budget sooner, which is the safe direction. + Self::BigInt(bi) => usize::try_from(bi.bits().div_ceil(8)).unwrap_or(usize::MAX), + Self::Exception { arg, .. } => name_len(arg), + Self::FileHandle(fh) => fh.path.len(), + Self::Function { name, docstring } => name.len().saturating_add(name_len(docstring)), + Self::DateTime(dt) => name_len(&dt.timezone_name), + Self::Time(t) => name_len(&t.timezone_name), + Self::TimeZone(tz) => name_len(&tz.name), + Self::List(items) | Self::Tuple(items) | Self::Set(items) | Self::FrozenSet(items) => ids(items), + Self::NamedTuple { + type_name, + field_names, + values, + } => { + let names: usize = field_names.iter().map(|name| Self::metadata_string_size(name)).sum(); + type_name.len().saturating_add(names).saturating_add(ids(values)) + } + Self::Dict(entries) => pairs(entries), + // The boxed payload is outside `size_of::()`, so charge it too. + Self::ClassType(class) => size_of::() + .saturating_add(class.name.len()) + .saturating_add(pairs(&class.attrs)), + Self::ClassInstance { attrs, .. } => pairs(attrs), + Self::Module { name, attrs, .. } => name.len().saturating_add(pairs(attrs)), + _ => 0, + }; + size_of::().saturating_add(payload) + } +} + +/// Payload of [`MontyNode::ClassType`]: a class shared by every instance of +/// it in the arena. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ClassTypeNode { + /// The Python-visible class name. + pub name: String, + /// Identity of the class, generated by whichever side defined it. + pub id: MontyUuid, + /// True for a host-defined class, false for a sandbox-defined one. + pub host_defined: bool, + /// Whether `dataclasses.is_dataclass` is true for the class. + pub is_dataclass: bool, + /// Eagerly-sent class attributes as `(name, value)` id pairs. + pub attrs: Vec<(NodeId, NodeId)>, +} + +impl PartialEq for MontyNode { + /// Per-node equality (child ids compare as ids); floats compare + /// bit-for-bit so `NaN` round-trips equal. + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::Ellipsis, Self::Ellipsis) + | (Self::NotImplemented, Self::NotImplemented) + | (Self::None, Self::None) => true, + (Self::Bool(a), Self::Bool(b)) => a == b, + (Self::Int(a), Self::Int(b)) => a == b, + (Self::BigInt(a), Self::BigInt(b)) => a == b, + (Self::Float(a), Self::Float(b)) => a.to_bits() == b.to_bits(), + (Self::Complex(a), Self::Complex(b)) => a.bits_eq(b), + (Self::String(a), Self::String(b)) + | (Self::Path(a), Self::Path(b)) + | (Self::Repr(a), Self::Repr(b)) + | (Self::Cycle(a), Self::Cycle(b)) + | (Self::Decimal(a), Self::Decimal(b)) => a == b, + (Self::Bytes(a), Self::Bytes(b)) => a == b, + (Self::Date(a), Self::Date(b)) => a == b, + (Self::DateTime(a), Self::DateTime(b)) => a == b, + (Self::Time(a), Self::Time(b)) => a == b, + (Self::TimeDelta(a), Self::TimeDelta(b)) => a == b, + (Self::TimeZone(a), Self::TimeZone(b)) => a == b, + ( + Self::Exception { + exc_type: a_type, + arg: a_arg, + }, + Self::Exception { + exc_type: b_type, + arg: b_arg, + }, + ) => a_type == b_type && a_arg == b_arg, + (Self::Type(a), Self::Type(b)) => a == b, + (Self::BuiltinFunction(a), Self::BuiltinFunction(b)) => a == b, + (Self::FileHandle(a), Self::FileHandle(b)) => { + a.path == b.path && a.mode == b.mode && a.position == b.position + } + ( + Self::Function { + name: a_name, + docstring: a_doc, + }, + Self::Function { + name: b_name, + docstring: b_doc, + }, + ) => a_name == b_name && a_doc == b_doc, + (Self::List(a), Self::List(b)) + | (Self::Tuple(a), Self::Tuple(b)) + | (Self::Set(a), Self::Set(b)) + | (Self::FrozenSet(a), Self::FrozenSet(b)) => a == b, + ( + Self::NamedTuple { + type_name: a_name, + field_names: a_fields, + values: a_values, + }, + Self::NamedTuple { + type_name: b_name, + field_names: b_fields, + values: b_values, + }, + ) => a_name == b_name && a_fields == b_fields && a_values == b_values, + (Self::Dict(a), Self::Dict(b)) => a == b, + (Self::ClassType(a), Self::ClassType(b)) => a == b, + ( + Self::ClassInstance { + class_type: a_class, + instance_id: a_id, + attrs: a_attrs, + }, + Self::ClassInstance { + class_type: b_class, + instance_id: b_id, + attrs: b_attrs, + }, + ) => a_class == b_class && a_id == b_id && a_attrs == b_attrs, + ( + Self::Module { + name: a_name, + id: a_id, + attrs: a_attrs, + }, + Self::Module { + name: b_name, + id: b_id, + attrs: b_attrs, + }, + ) => a_name == b_name && a_id == b_id && a_attrs == b_attrs, + _ => false, + } + } +} + +impl Eq for MontyNode {} + +/// A post-order node arena. +/// +/// [`push`](Self::push) and [`from_nodes`](Self::from_nodes) check the +/// invariants (see [`validate`](Self::validate)) and [`merge`](Self::merge) +/// preserves them, so readers index without re-checking. Roots are held by +/// the carrying message, so one arena serves every value in that message. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct MontyGraph { + nodes: Vec, +} + +impl MontyGraph { + /// An empty arena. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// An empty arena with room for `capacity` nodes. + #[must_use] + pub fn with_capacity(capacity: usize) -> Self { + Self { + nodes: Vec::with_capacity(capacity), + } + } + + /// Adopts already-built nodes after validating them. + pub fn from_nodes(nodes: Vec) -> Result { + Self::validate(&nodes)?; + Ok(Self { nodes }) + } + + /// Checks that child ids precede their holders and class-instance nodes + /// reference class-type nodes. + pub fn validate(nodes: &[MontyNode]) -> Result<(), GraphError> { + nodes + .iter() + .enumerate() + .try_for_each(|(index, node)| Self::check_node(nodes, index, node)) + } + + /// Appends a node, returning its id. + /// + /// # Panics + /// If the node violates the arena invariants; children must be pushed + /// before the node that holds them. + pub fn push(&mut self, node: MontyNode) -> NodeId { + let index = self.nodes.len(); + if let Err(err) = Self::check_node(&self.nodes, index, &node) { + panic!("invalid node pushed onto a MontyGraph: {err}"); + } + self.nodes.push(node); + Self::id_at(index) + } + + /// Appends every node of `other`, rebasing its ids, and returns the + /// offset added to them so the caller can rebase its own roots. + pub fn merge(&mut self, other: Self) -> u32 { + let offset = Self::id_at(self.nodes.len()).0; + self.nodes.reserve(other.nodes.len()); + for mut node in other.nodes { + node.for_each_child_mut(|id| id.0 += offset); + self.nodes.push(node); + } + offset + } + + /// Number of nodes. + #[must_use] + pub fn len(&self) -> usize { + self.nodes.len() + } + + /// Whether the arena has no nodes. + #[must_use] + pub fn is_empty(&self) -> bool { + self.nodes.is_empty() + } + + /// The node at `id`. + /// + /// # Panics + /// If `id` is out of range; ids come from this arena, so that is a bug. + #[must_use] + pub fn node(&self, id: NodeId) -> &MontyNode { + &self.nodes[id.index()] + } + + /// Mutable access to the node at `id`. Callers must keep the invariants: + /// replacing a node's child ids with lower ones is fine, raising them is not. + /// + /// # Panics + /// If `id` is out of range. + pub fn node_mut(&mut self, id: NodeId) -> &mut MontyNode { + &mut self.nodes[id.index()] + } + + /// Every node, in post-order, for editing payloads in place; reordering + /// nodes or raising a child id breaks the arena's invariants. + pub fn nodes_mut(&mut self) -> &mut [MontyNode] { + &mut self.nodes + } + + /// Every node, in post-order. + #[must_use] + pub fn nodes(&self) -> &[MontyNode] { + &self.nodes + } + + /// Takes the nodes out of the arena. + #[must_use] + pub fn into_nodes(self) -> Vec { + self.nodes + } + + /// Checks that `root` (an id received alongside this arena) is in range. + pub fn check_root(&self, root: NodeId) -> Result<(), GraphError> { + if root.index() < self.nodes.len() { + Ok(()) + } else { + Err(GraphError::RootOutOfRange { + root, + len: self.nodes.len(), + }) + } + } + + /// The Python type name of the value at `id`, e.g. `"list"`; a class + /// instance reports its class name. + #[must_use] + pub fn type_name(&self, id: NodeId) -> &str { + match self.node(id) { + MontyNode::None => "NoneType", + MontyNode::Ellipsis => "ellipsis", + MontyNode::NotImplemented => "NotImplementedType", + MontyNode::Bool(_) => "bool", + MontyNode::Int(_) | MontyNode::BigInt(_) => "int", + MontyNode::Float(_) => "float", + MontyNode::Complex(_) => "complex", + MontyNode::String(_) => "str", + MontyNode::Bytes(_) => "bytes", + MontyNode::List(_) => "list", + MontyNode::Tuple(_) => "tuple", + MontyNode::NamedTuple { .. } => "namedtuple", + MontyNode::Dict(_) => "dict", + MontyNode::Set(_) => "set", + MontyNode::FrozenSet(_) => "frozenset", + MontyNode::Date(_) => "date", + MontyNode::DateTime(_) => "datetime", + MontyNode::Time(_) => "time", + MontyNode::TimeDelta(_) => "timedelta", + MontyNode::TimeZone(_) => "timezone", + MontyNode::Decimal(_) => "Decimal", + MontyNode::Exception { .. } => "Exception", + MontyNode::Path(_) => "PosixPath", + MontyNode::FileHandle(handle) => handle.mode.type_name(), + MontyNode::ClassInstance { class_type, .. } => match self.node(*class_type) { + MontyNode::ClassType(class) => &class.name, + _ => "object", + }, + MontyNode::Type(_) | MontyNode::ClassType(_) => "type", + MontyNode::Module { .. } => "module", + MontyNode::BuiltinFunction(_) => "builtin_function_or_method", + MontyNode::Function { .. } => "function", + MontyNode::Repr(_) => "repr", + MontyNode::Cycle(_) => "cycle", + } + } + + /// Sum of [`MontyNode::decoded_size`] over every node: the arena's decoded + /// footprint, used by transport budgets. + #[must_use] + pub fn decoded_size(&self) -> usize { + self.nodes + .iter() + .fold(0usize, |size, node| size.saturating_add(node.decoded_size())) + } + + /// Validates one node against the nodes that precede it. + fn check_node(nodes: &[MontyNode], index: usize, node: &MontyNode) -> Result<(), GraphError> { + let holder = Self::id_at(index); + let mut result = Ok(()); + node.for_each_child(|child| { + if result.is_ok() && child.index() >= index { + result = Err(GraphError::IndexNotLower { node: holder, child }); + } + }); + result?; + match node { + MontyNode::ClassInstance { class_type, .. } + if !matches!(nodes[class_type.index()], MontyNode::ClassType(_)) => + { + Err(GraphError::ClassTypeNotAClass { node: holder }) + } + _ => Ok(()), + } + } + + /// The id of the node at `index`; panics past `u32::MAX` nodes. + fn id_at(index: usize) -> NodeId { + NodeId(u32::try_from(index).expect("MontyGraph exceeds u32::MAX nodes")) + } +} + +/// Why a node sequence is not a valid [`MontyGraph`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GraphError { + /// A node references a child at or above its own index. + IndexNotLower { + /// The holding node. + node: NodeId, + /// The offending child id. + child: NodeId, + }, + /// A class-instance node's `class_type` is not a class-type node. + ClassTypeNotAClass { + /// The instance node. + node: NodeId, + }, + /// A root id is outside the arena. + RootOutOfRange { + /// The root id. + root: NodeId, + /// The arena length. + len: usize, + }, +} + +impl fmt::Display for GraphError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::IndexNotLower { node, child } => { + write!(f, "value node {node} references node {child}, which is not below it") + } + Self::ClassTypeNotAClass { node } => write!(f, "class instance node {node} does not point at a class type"), + Self::RootOutOfRange { root, len } => { + write!(f, "value root {root} is out of range for an arena of {len} nodes") + } + } + } +} + +impl Error for GraphError {} diff --git a/crates/bashkit-monty-types/src/io.rs b/crates/bashkit-monty-types/src/io.rs new file mode 100644 index 000000000..bccac43dd --- /dev/null +++ b/crates/bashkit-monty-types/src/io.rs @@ -0,0 +1,345 @@ +//! Print-output plumbing: [`PrintStream`], [`PrintWriter`] and the +//! [`PrintWriterCallback`] trait used by hosts to capture `print()` output. + +use std::borrow::Cow; + +use crate::{ + exceptions::{ExcType, MontyException}, + resource::ResourceError, +}; + +/// Default cap for [`PrintWriter::CollectString`] / [`PrintWriter::CollectStreams`] +/// and the matching Python collectors. +/// +/// Host-side print buffers sit outside [`crate::ResourceLimits::max_memory`]; +/// without a cap, a print loop can OOM the host while sandbox limits stay green. +/// Pass `max_bytes: None` to opt out on trusted hosts. +pub const DEFAULT_MAX_PRINT_COLLECT_BYTES: usize = 10 * 1024 * 1024; + +/// Host bytes charged for each retained `(stream, text)` entry beyond its text. +/// +/// A retained entry costs about 32 bytes in the vector plus its `String`'s own +/// allocation, none of which is text. Charging only the text would let a run +/// that starts a fresh entry per byte — one that alternates between the two +/// streams — occupy roughly 64x the host memory the cap accounts for. +pub const COLLECT_STREAMS_ENTRY_OVERHEAD: usize = 64; + +/// Identifies the output stream for a single print fragment. +/// +/// `print()` writes to `Stdout` unless it is given `file=sys.stderr`, which is +/// the only way sandboxed code can reach `Stderr`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PrintStream { + /// Standard output, the default for a `print()` call with no `file=`. + Stdout, + /// Standard error, reached by `print(..., file=sys.stderr)`. + Stderr, +} + +/// Output handler for the `print()` builtin function. +/// +/// Provides common output modes as enum variants to avoid trait object overhead +/// in the typical cases (stdout, disabled, collect). For custom output handling, +/// use the `Callback` variant with a [`PrintWriterCallback`] implementation. +/// +/// # Variants +/// - `Disabled` — silently discards all output (useful for benchmarking or suppressing output). +/// - `Stdout` — writes to standard output (the default behavior). +/// - `CollectString` — accumulates output into a target `String` for programmatic access. +/// No stream labels are preserved; every fragment is appended in the order it was emitted. +/// The `Option` is an optional byte cap (`None` = unlimited); constructors +/// [`collect_string`](Self::collect_string) / default Python collectors use +/// [`DEFAULT_MAX_PRINT_COLLECT_BYTES`]. +/// - `CollectStreams` — accumulates output as `(stream, text)` pairs, merging consecutive +/// same-stream fragments into one tuple. Each write to the same stream extends the +/// trailing entry rather than producing a new one; a new tuple is only pushed when +/// the stream changes. Same optional byte cap as `CollectString`. +/// - `Callback` — delegates to a user-provided [`PrintWriterCallback`] implementation. +pub enum PrintWriter<'a> { + /// Silently discard all output. + Disabled, + /// Write to standard output. + Stdout, + /// Collect all output into a single `String`, in emit order, with no stream labels. + /// + /// Second field: max collected bytes (`None` = unlimited). Exceeding raises + /// `MemoryError` with the same message as [`ResourceError::Memory`]. + CollectString(&'a mut String, Option), + /// Collect all output as `(stream, text)` entries. + /// + /// The builtin `print()` implementation calls `write` for each argument and + /// `push` for each separator/terminator. To avoid one entry per fragment, + /// [`CollectedStreams`] appends to the trailing entry when it already + /// matches the current stream; a new entry is only pushed when the stream + /// changes. So a run that stays on one stream collects a single entry + /// however many fragments it wrote, and one that alternates collects one + /// per run. + /// + /// Second field: the cap the collector's charge is checked against (`None` + /// = unlimited), which counts [`COLLECT_STREAMS_ENTRY_OVERHEAD`] per entry + /// as well as the text. + CollectStreams(&'a mut CollectedStreams, Option), + /// Delegate to a custom callback. + Callback(&'a mut dyn PrintWriterCallback), +} + +impl PrintWriter<'_> { + /// Collect into `buf` with the default [`DEFAULT_MAX_PRINT_COLLECT_BYTES`] cap. + pub fn collect_string(buf: &mut String) -> PrintWriter<'_> { + PrintWriter::CollectString(buf, Some(DEFAULT_MAX_PRINT_COLLECT_BYTES)) + } + + /// Collect into `buf` with the default [`DEFAULT_MAX_PRINT_COLLECT_BYTES`] cap. + pub fn collect_streams(buf: &mut CollectedStreams) -> PrintWriter<'_> { + PrintWriter::CollectStreams(buf, Some(DEFAULT_MAX_PRINT_COLLECT_BYTES)) + } + + /// Creates a new [`PrintWriter`] that reborrows the same underlying target. + /// + /// This is useful in iterative execution (`start`/`resume` loops) where each + /// step takes [`PrintWriter`] by value but you want all steps to write to the + /// same output target. The original writer remains valid after the reborrowed + /// copy is dropped. + pub fn reborrow(&mut self) -> PrintWriter<'_> { + match self { + Self::Disabled => PrintWriter::Disabled, + Self::Stdout => PrintWriter::Stdout, + Self::CollectString(buf, max) => PrintWriter::CollectString(buf, *max), + Self::CollectStreams(buf, max) => PrintWriter::CollectStreams(buf, *max), + Self::Callback(cb) => PrintWriter::Callback(&mut **cb), + } + } + + /// Called once for each formatted argument passed to `print()`. + /// + /// This method writes only the given argument's text, without adding + /// separators or a trailing newline. Separators (spaces) and the final + /// terminator (newline) are emitted via [`push`](Self::push). + /// + /// `CollectString` keeps no stream labels, so a run that prints to both + /// streams interleaves them in one buffer. Use `CollectStreams` to tell + /// them apart. + pub fn write(&mut self, stream: PrintStream, output: Cow<'_, str>) -> Result<(), MontyException> { + match self { + Self::Disabled => Ok(()), + Self::Stdout => { + match stream { + PrintStream::Stdout => print!("{output}"), + PrintStream::Stderr => eprint!("{output}"), + } + Ok(()) + } + Self::CollectString(buf, max_bytes) => { + check_print_collect_limit(buf.len(), output.len(), *max_bytes)?; + buf.push_str(&output); + Ok(()) + } + Self::CollectStreams(buf, max_bytes) => buf.push_str(stream, &output, *max_bytes), + Self::Callback(cb) => match stream { + PrintStream::Stdout => cb.stdout_write(output), + PrintStream::Stderr => cb.stderr_write(output), + }, + } + } + + /// Appends a single character to the given stream. + /// + /// Generally called to add spaces (separators) and newlines (terminators) + /// within print output. + pub fn push(&mut self, stream: PrintStream, end: char) -> Result<(), MontyException> { + match self { + Self::Disabled => Ok(()), + Self::Stdout => { + match stream { + PrintStream::Stdout => print!("{end}"), + PrintStream::Stderr => eprint!("{end}"), + } + Ok(()) + } + Self::CollectString(buf, max_bytes) => { + check_print_collect_limit(buf.len(), end.len_utf8(), *max_bytes)?; + buf.push(end); + Ok(()) + } + Self::CollectStreams(buf, max_bytes) => buf.push_char(stream, end, *max_bytes), + Self::Callback(cb) => match stream { + PrintStream::Stdout => cb.stdout_push(end), + PrintStream::Stderr => cb.stderr_push(end), + }, + } + } + + /// [`write`](Self::write) to [`PrintStream::Stdout`]. + pub fn stdout_write(&mut self, output: Cow<'_, str>) -> Result<(), MontyException> { + self.write(PrintStream::Stdout, output) + } + + /// [`push`](Self::push) to [`PrintStream::Stdout`]. + pub fn stdout_push(&mut self, end: char) -> Result<(), MontyException> { + self.push(PrintStream::Stdout, end) + } + + /// Whether this writer wants [`poll_flush`](Self::poll_flush) called at all. + /// + /// Only `Callback` can buffer, so the VM hoists this out of its dispatch + /// loop and skips the poll (and its clock read) entirely for every other + /// variant. + #[must_use] + pub fn wants_poll(&self) -> bool { + matches!(self, Self::Callback(_)) + } + + /// Forwards the VM's periodic checkpoint to a buffering callback. + pub fn poll_flush(&mut self) -> Result<(), MontyException> { + match self { + Self::Callback(cb) => cb.poll_flush(), + _ => Ok(()), + } + } +} + +/// The buffer behind [`PrintWriter::CollectStreams`]: `(stream, text)` entries +/// plus the running charge their cap is checked against. +/// +/// The charge is carried rather than re-derived because the cap is checked on +/// every fragment: summing the entries each time is O(entries), which a run +/// alternating between the streams turns into quadratic work, since each switch +/// starts a new entry. `pydantic_monty`'s collector keeps the same running +/// charge for the same reason. +#[derive(Debug, Default)] +pub struct CollectedStreams { + entries: Vec<(PrintStream, String)>, + /// Text bytes plus [`COLLECT_STREAMS_ENTRY_OVERHEAD`] per entry, kept in + /// step with every append. + charged_bytes: usize, +} + +impl CollectedStreams { + /// The collected fragments, in the order the sandbox produced them. + #[must_use] + pub fn entries(&self) -> &[(PrintStream, String)] { + &self.entries + } + + /// Takes the collected fragments, leaving the buffer empty. + #[must_use] + pub fn into_entries(self) -> Vec<(PrintStream, String)> { + self.entries + } + + /// Appends a string fragment, merging into the trailing entry when the + /// stream matches. + fn push_str(&mut self, stream: PrintStream, text: &str, max_bytes: Option) -> Result<(), MontyException> { + let starts_entry = self.starts_entry(stream); + self.charge(text.len(), starts_entry, max_bytes)?; + match self.entries.last_mut() { + Some((s, existing)) if *s == stream => existing.push_str(text), + _ => self.entries.push((stream, text.to_owned())), + } + Ok(()) + } + + /// Appends a single character, merging into the trailing entry when the + /// stream matches. + fn push_char(&mut self, stream: PrintStream, ch: char, max_bytes: Option) -> Result<(), MontyException> { + let starts_entry = self.starts_entry(stream); + self.charge(ch.len_utf8(), starts_entry, max_bytes)?; + match self.entries.last_mut() { + Some((s, existing)) if *s == stream => existing.push(ch), + _ => self.entries.push((stream, String::from(ch))), + } + Ok(()) + } + + /// Whether a fragment on `stream` would start an entry rather than extend + /// the trailing one. + fn starts_entry(&self, stream: PrintStream) -> bool { + !matches!(self.entries.last(), Some((s, _)) if *s == stream) + } + + /// Checks a fragment's `add` text bytes against the cap and books them, + /// with [`COLLECT_STREAMS_ENTRY_OVERHEAD`] on top when it starts an entry. + /// The charge is left untouched when the cap refuses the fragment. + fn charge(&mut self, add: usize, starts_entry: bool, max_bytes: Option) -> Result<(), MontyException> { + let add = if starts_entry { + add.saturating_add(COLLECT_STREAMS_ENTRY_OVERHEAD) + } else { + add + }; + check_print_collect_limit(self.charged_bytes, add, max_bytes)?; + self.charged_bytes = self.charged_bytes.saturating_add(add); + Ok(()) + } +} + +/// Rejects a collect-buffer growth that would exceed `max_bytes`. +/// +/// `None` means unlimited. On overflow, returns the same `MemoryError` message +/// as [`ResourceError::Memory`] so hosts see one familiar limit string. +pub fn check_print_collect_limit( + current_len: usize, + add: usize, + max_bytes: Option, +) -> Result<(), MontyException> { + let Some(limit) = max_bytes else { + return Ok(()); + }; + let used = current_len.saturating_add(add); + if used > limit { + Err(MontyException::new( + ExcType::MemoryError, + Some(ResourceError::Memory { limit, used }.to_string()), + )) + } else { + Ok(()) + } +} + +/// Trait for custom output handling from the `print()` builtin function. +/// +/// Implement this trait and pass it via [`PrintWriter::Callback`] to capture +/// or redirect print output from sandboxed Python code. +pub trait PrintWriterCallback { + /// Called once for each formatted argument passed to `print()`. + /// + /// This method is responsible for writing only the given argument's text, and must + /// not add separators or a trailing newline. Separators (such as spaces) and the + /// final terminator (such as a newline) are emitted via [`stdout_push`](Self::stdout_push). + /// + /// # Arguments + /// * `output` - The formatted output string for a single argument (without + /// separators or trailing newline). + fn stdout_write(&mut self, output: Cow<'_, str>) -> Result<(), MontyException>; + + /// Add a single character to stdout. + /// + /// Generally called to add spaces and newlines within print output. + /// + /// # Arguments + /// * `end` - The character to print after the formatted output. + fn stdout_push(&mut self, end: char) -> Result<(), MontyException>; + + /// Called for each formatted argument of a `print(..., file=sys.stderr)`. + /// + /// Defaults to [`stdout_write`](Self::stdout_write), so a host written + /// before stderr existed still receives the text instead of losing it. + fn stderr_write(&mut self, output: Cow<'_, str>) -> Result<(), MontyException> { + self.stdout_write(output) + } + + /// Adds a single character to stderr. Defaults to + /// [`stdout_push`](Self::stdout_push), as [`stderr_write`](Self::stderr_write) does. + fn stderr_push(&mut self, end: char) -> Result<(), MontyException> { + self.stdout_push(end) + } + + /// Gives a buffering implementation a chance to release what it holds. + /// + /// The VM calls this from its periodic dispatch checkpoint, so a callback + /// that batches writes can bound how long output sits unsent while the + /// program computes without printing. Implementations that write straight + /// through do nothing here. + fn poll_flush(&mut self) -> Result<(), MontyException> { + Ok(()) + } +} diff --git a/crates/bashkit-monty-types/src/lib.rs b/crates/bashkit-monty-types/src/lib.rs new file mode 100644 index 000000000..1441e5113 --- /dev/null +++ b/crates/bashkit-monty-types/src/lib.rs @@ -0,0 +1,68 @@ +#![doc = include_str!("../README.md")] +// bashkit fork: upstream source is kept unchanged, so its lints are not +// bashkit's. Source attributes override `cargo clippy -- -D warnings`. +#![allow(warnings, clippy::all, clippy::pedantic)] + +/// The monty version this build was compiled as. +// bashkit fork: report the upstream release, not the bashkit crate version. +pub const MONTY_VERSION: &str = "1.4.0"; + +pub mod args; +mod builtins; +mod exceptions; +mod file_mode; +pub mod format; +mod graph; +mod io; +mod object; +mod os; +mod os_policy; +mod resource; +mod results; +mod run_options; +pub mod scan; +mod type_checking; +mod uuid; +mod virtual_path; + +pub use crate::{ + builtins::BuiltinsFunctions, + exceptions::{ + CodeLoc, ExcData, ExcType, JsonErrorData, MontyException, SourceRange, StackFrame, UnicodeErrorData, + UnicodeErrorObject, unicode_decode_error_msg, + }, + file_mode::FileMode, + format::{FormatComplex, FormatFloat, StringRepr, bytes_repr, bytes_repr_fmt, string_repr_fmt, utf8_error_reason}, + io::{ + COLLECT_STREAMS_ENTRY_OVERHEAD, CollectedStreams, DEFAULT_MAX_PRINT_COLLECT_BYTES, PrintStream, PrintWriter, + PrintWriterCallback, check_print_collect_limit, + }, + object::{ + CallArgs, ConversionError, InvalidInputError, MAX_TIMEZONE_OFFSET_SECONDS, MIN_TIMEZONE_OFFSET_SECONDS, + MontyComplex, MontyDate, MontyDateTime, MontyFileHandle, MontyObject, MontyTime, MontyTimeDelta, MontyTimeZone, + MontyType, NamedValues, ObjectRef, unstable, + }, + os::{ + GetenvArgs, IMPORT_CALL, IMPORT_STUBS_CALL, IMPORT_STUBS_CALL_ID, MAX_SLEEP_SECONDS, MkdirCallArgs, MontyPath, + OpenCallArgs, OsFunctionCall, PathBytesDataArgs, PathStringDataArgs, RenameCallArgs, SleepError, TimeCaller, + UrandomArgs, dir_stat, file_stat, sleep_duration, sleep_duration_saturating, stat_result, symlink_stat, + }, + os_policy::{ + DateTimeSource, NamedZone, OsPolicy, ProcessTime, RandomSeed, RandomStart, SandboxTimeZone, SleepMode, + UnknownTimeZone, ZoneConstants, local_wall_clock, unix_seconds, + }, + resource::{ + BASELINE_MEMORY, DEFAULT_GC_INTERVAL, DEFAULT_MAX_RECURSION_DEPTH, DEFAULT_MAX_SUSPENSIONS, + LARGE_RESULT_THRESHOLD, LIVE_MEMORY, OOM_EXIT_CODE, ResourceError, ResourceLimits, ResourceTracker, + TimeLimitScope, allocate_into_baseline, memory_limit_with_headroom, set_checkpoint_hook, set_memory_probe, // bashkit fork: hooks + }, + results::{ExtFunctionResult, NameLookupResult}, + run_options::{AssertMessageAnnotations, CompileOptions, SOURCE_SCAN_THRESHOLD}, + scan::ScanArgs, + type_checking::{ + CHECKER_MODULE_NAMES, ModuleStub, ModuleStubError, SANDBOX_MODULE_NAMES, TypeCheckState, TypeCheckingConfig, + TypeCheckingFormat, is_identifier, validate_module_name, + }, + uuid::MontyUuid, + virtual_path::{normalize_virtual_path, validate_cwd}, +}; diff --git a/crates/bashkit-monty-types/src/object.rs b/crates/bashkit-monty-types/src/object.rs new file mode 100644 index 000000000..1c8d49b59 --- /dev/null +++ b/crates/bashkit-monty-types/src/object.rs @@ -0,0 +1,1830 @@ +//! Boundary values: [`MontyObject`] (an owned value), +//! [`ObjectRef`] (a borrowed value), the message carriers +//! [`CallArgs`] and [`NamedValues`], and the leaf payloads they hold: +//! [`MontyType`], the datetime value types, [`MontyFileHandle`], and the +//! errors reading or importing a value raises. +//! +//! Hosts build inputs with the [`MontyObject`] constructors (`MontyObject::int`, +//! `MontyObject::list`, ...) and read results through [`ObjectRef`]'s typed +//! accessors, structural equality and Python `repr()`. Graph representation +//! access requires opting into [`unstable`]. + +pub mod unstable; + +use std::{ + borrow::Cow, + collections::HashSet, + error::Error, + fmt::{self, Write}, + hash::{Hash, Hasher}, + vec, +}; + +use ReprPiece::{Child, Text}; +use chrono::{NaiveDate, NaiveDateTime, NaiveTime, TimeDelta as ChronoTimeDelta}; +use num_bigint::BigInt; +use num_traits::{ToPrimitive, Zero}; + +use crate::{ + builtins::BuiltinsFunctions, + exceptions::ExcType, + file_mode::FileMode, + format::{FormatComplex, FormatFloat, StringRepr, bytes_repr_fmt, format_offset_timedelta_repr, string_repr_fmt}, + graph::{ClassTypeNode, GraphError, MontyGraph, MontyNode, NodeId}, + resource::ResourceError, + unstable::PushValue, + uuid::MontyUuid, +}; + +/// One owned Python value at the host boundary. +/// +/// Carried by `Complete`, resume results, name lookups and `os.getenv` +/// defaults, and the type hosts build inputs with. Equality is structural as +/// Python values, independent of storage layout. +#[derive(Debug, Clone, Eq, serde::Serialize, serde::Deserialize)] +pub struct MontyObject { + /// The arena holding the value and everything it references. + graph: MontyGraph, + /// The value's node. + root: NodeId, +} + +impl MontyObject { + /// Pairs an arena with a root, checking the root is in range. + fn new(graph: MontyGraph, root: NodeId) -> Result { + graph.check_root(root)?; + Ok(Self { graph, root }) + } + + /// A value made of one leaf node. + /// + /// # Panics + /// If `node` holds child ids. + #[must_use] + fn leaf(node: MontyNode) -> Self { + let mut graph = MontyGraph::with_capacity(1); + let root = graph.push(node); + Self { graph, root } + } + + /// Python `None`. + #[must_use] + pub fn none() -> Self { + Self::leaf(MontyNode::None) + } + + /// Python `Ellipsis`. + #[must_use] + pub fn ellipsis() -> Self { + Self::leaf(MontyNode::Ellipsis) + } + + /// Python `NotImplemented`. + #[must_use] + pub fn not_implemented() -> Self { + Self::leaf(MontyNode::NotImplemented) + } + + /// A `bool`. + #[must_use] + pub fn bool(value: bool) -> Self { + Self::leaf(MontyNode::Bool(value)) + } + + /// An `int` that fits in 64 bits. + #[must_use] + pub fn int(value: i64) -> Self { + Self::leaf(MontyNode::Int(value)) + } + + /// An `int` of any size. + #[must_use] + pub fn bigint(value: BigInt) -> Self { + Self::leaf(MontyNode::BigInt(value)) + } + + /// A `float`. + #[must_use] + pub fn float(value: f64) -> Self { + Self::leaf(MontyNode::Float(value)) + } + + /// A `complex` from its real and imaginary parts. + #[must_use] + pub fn complex(real: f64, imag: f64) -> Self { + Self::leaf(MontyNode::Complex(MontyComplex { real, imag })) + } + + /// A `str`. + #[must_use] + pub fn string(value: impl Into) -> Self { + Self::leaf(MontyNode::String(value.into())) + } + + /// A `bytes`. + #[must_use] + pub fn bytes(value: impl Into>) -> Self { + Self::leaf(MontyNode::Bytes(value.into())) + } + + /// A `pathlib.Path`, always a virtual POSIX path. + #[must_use] + pub fn path(value: impl Into) -> Self { + Self::leaf(MontyNode::Path(value.into())) + } + + /// A `datetime.date`. + #[must_use] + pub fn date(value: MontyDate) -> Self { + Self::leaf(MontyNode::Date(value)) + } + + /// A `datetime.datetime`. + #[must_use] + pub fn datetime(value: MontyDateTime) -> Self { + Self::leaf(MontyNode::DateTime(value)) + } + + /// A `datetime.time`. + #[must_use] + pub fn time(value: MontyTime) -> Self { + Self::leaf(MontyNode::Time(value)) + } + + /// A `datetime.timedelta`. + #[must_use] + pub fn timedelta(value: MontyTimeDelta) -> Self { + Self::leaf(MontyNode::TimeDelta(value)) + } + + /// A `datetime.timezone`. + #[must_use] + pub fn timezone(value: MontyTimeZone) -> Self { + Self::leaf(MontyNode::TimeZone(value)) + } + + /// A `decimal.Decimal` from its string form, as `str(d)` prints it. + /// + /// The sandbox parses the text as `Decimal(text)` does, so any numeric string is + /// accepted (`"1.20"`, `"1e5"`, `"-NaN"`); feeding it anything else fails there. + #[must_use] + pub fn decimal(value: impl Into) -> Self { + Self::leaf(MontyNode::Decimal(value.into())) + } + + /// An exception instance as a value (not raised), with its message. + #[must_use] + pub fn exception(exc_type: ExcType, arg: Option) -> Self { + Self::leaf(MontyNode::Exception { exc_type, arg }) + } + + /// A host function the sandbox calls back by `name`. + #[must_use] + pub fn function(name: impl Into, docstring: Option) -> Self { + Self::leaf(MontyNode::Function { + name: name.into(), + docstring, + }) + } + + /// A builtin function such as `len`. + #[must_use] + pub fn builtin_function(function: BuiltinsFunctions) -> Self { + Self::leaf(MontyNode::BuiltinFunction(function)) + } + + /// A builtin type object such as `int`. + #[must_use] + pub fn type_object(value: MontyType) -> Self { + Self::leaf(MontyNode::Type(value)) + } + + /// An open file object, as the result of an `open()` OS call. + #[must_use] + pub fn file_handle(value: MontyFileHandle) -> Self { + Self::leaf(MontyNode::FileHandle(value)) + } + + /// Output-only: a value's `repr()` where no faithful representation exists. + #[must_use] + pub fn repr(value: impl Into) -> Self { + Self::leaf(MontyNode::Repr(value.into())) + } + + /// Output-only: a reference back to an enclosing container, as its placeholder. + #[must_use] + pub fn cycle(placeholder: impl Into) -> Self { + Self::leaf(MontyNode::Cycle(placeholder.into())) + } + + /// A `list`. + #[must_use] + pub fn list(items: impl IntoIterator) -> Self { + Self::container(items, MontyNode::List) + } + + /// A `tuple`. + #[must_use] + pub fn tuple(items: impl IntoIterator) -> Self { + Self::container(items, MontyNode::Tuple) + } + + /// A `set`. + #[must_use] + pub fn set(items: impl IntoIterator) -> Self { + Self::container(items, MontyNode::Set) + } + + /// A `frozenset`. + #[must_use] + pub fn frozenset(items: impl IntoIterator) -> Self { + Self::container(items, MontyNode::FrozenSet) + } + + /// A `dict` from `(key, value)` pairs, in insertion order. + #[must_use] + pub fn dict(pairs: impl IntoIterator) -> Self { + let mut graph = MontyGraph::new(); + let pairs = push_pairs(pairs, &mut graph); + let root = graph.push(MontyNode::Dict(pairs)); + Self { graph, root } + } + + /// A namedtuple: `type_name(field=value, ...)`. + #[must_use] + pub fn named_tuple( + type_name: impl Into, + field_names: impl IntoIterator>, + values: impl IntoIterator, + ) -> Self { + let type_name = type_name.into(); + let field_names = field_names.into_iter().map(Into::into).collect(); + Self::container(values, |values| MontyNode::NamedTuple { + type_name, + field_names, + values, + }) + } + + /// A non-builtin class type object with its eager class attrs. + /// + /// `id` is generated by whichever side defined the class (a host uuid4, + /// or a worker uuid for sandbox classes); the sandbox keeps one type + /// object per id and routes instantiation and classmethod calls by it. + #[must_use] + pub fn class_type( + name: impl Into, + id: MontyUuid, + host_defined: bool, + is_dataclass: bool, + attrs: impl IntoIterator, + ) -> Self { + let mut graph = MontyGraph::new(); + let attrs = push_pairs(attrs, &mut graph); + let root = graph.push(MontyNode::ClassType(Box::new(ClassTypeNode { + name: name.into(), + id, + host_defined, + is_dataclass, + attrs, + }))); + Self { graph, root } + } + + /// An instance of `class_type` (a [`class_type`](Self::class_type) value) + /// with its eager attrs, identified by `instance_id`. + /// + /// # Panics + /// If `class_type` is not a class type object. + #[must_use] + pub fn class_instance( + class_type: Self, + instance_id: MontyUuid, + attrs: impl IntoIterator, + ) -> Self { + let mut graph = MontyGraph::new(); + let class_type = class_type.push_into(&mut graph); + let attrs = push_pairs(attrs, &mut graph); + let root = graph.push(MontyNode::ClassInstance { + class_type, + instance_id, + attrs, + }); + Self { graph, root } + } + + /// A host module named `name` with its attributes, identified by `id`; + /// it imports as a `module` object in the sandbox. + #[must_use] + pub fn module(name: impl Into, id: MontyUuid, attrs: impl IntoIterator) -> Self { + let mut graph = MontyGraph::new(); + let attrs = push_pairs(attrs, &mut graph); + let root = graph.push(MontyNode::Module { + name: name.into(), + id, + attrs, + }); + Self { graph, root } + } + + /// Resolves a builtin function by its Python name (e.g. `"len"`), the + /// name its `Display` renders. + #[must_use] + pub fn builtin_function_from_name(name: &str) -> Option { + name.parse::().ok().map(Self::builtin_function) + } + + /// Borrows the value for inspection without copying. + #[must_use] + pub fn as_ref(&self) -> ObjectRef<'_> { + ObjectRef { + graph: &self.graph, + id: self.root, + } + } + + /// The root node. + #[must_use] + fn root_node(&self) -> &MontyNode { + self.graph.node(self.root) + } + + /// The Python `repr()` of the value. + #[must_use] + pub fn py_repr(&self) -> String { + self.as_ref().py_repr() + } + + /// Whether the value is truthy under Python's rules; see [`ObjectRef::is_truthy`]. + #[must_use] + pub fn is_truthy(&self) -> bool { + self.as_ref().is_truthy() + } + + /// The Python type name of the value, e.g. `"list"`. + #[must_use] + pub fn type_name(&self) -> &str { + self.graph.type_name(self.root) + } + + /// Pushes every item, then the container node holding their ids. + fn container(items: impl IntoIterator, make: impl FnOnce(Vec) -> MontyNode) -> Self { + let mut graph = MontyGraph::new(); + let ids = items.into_iter().map(|item| item.push_into(&mut graph)).collect(); + let root = graph.push(make(ids)); + Self { graph, root } + } +} + +impl PartialEq for MontyObject { + /// Structural equality as Python values, independent of arena layout. + fn eq(&self, other: &Self) -> bool { + self.as_ref() == other.as_ref() + } +} + +impl PartialEq> for MontyObject { + fn eq(&self, other: &ObjectRef<'_>) -> bool { + self.as_ref() == *other + } +} + +impl fmt::Display for MontyObject { + /// The Python `str()` of the value: text as is, everything else its `repr()`. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.as_ref().fmt(f) + } +} + +impl TryFrom<&MontyObject> for i64 { + type Error = ConversionError; + + fn try_from(value: &MontyObject) -> Result { + value.as_ref().try_into() + } +} + +impl TryFrom<&MontyObject> for f64 { + type Error = ConversionError; + + fn try_from(value: &MontyObject) -> Result { + value.as_ref().try_into() + } +} + +impl TryFrom<&MontyObject> for String { + type Error = ConversionError; + + fn try_from(value: &MontyObject) -> Result { + value.as_ref().try_into() + } +} + +impl TryFrom<&MontyObject> for bool { + type Error = ConversionError; + + fn try_from(value: &MontyObject) -> Result { + value.as_ref().try_into() + } +} + +/// A borrowed Python value, for inspecting results, arguments and inputs without copying. +#[derive(Debug, Clone, Copy)] +pub struct ObjectRef<'a> { + /// The arena. + graph: &'a MontyGraph, + /// The value's node. + id: NodeId, +} + +impl<'a> ObjectRef<'a> { + /// The root node. + #[must_use] + fn node(&self) -> &'a MontyNode { + self.graph.node(self.id) + } + + /// The Python type name of the value, e.g. `"list"`. + #[must_use] + pub fn type_name(&self) -> &'a str { + self.graph.type_name(self.id) + } + + /// Copies into an owned value, preserving sharing within the value. + #[must_use] + pub fn to_owned(&self) -> MontyObject { + let mut graph = MontyGraph::new(); + let root = self.push_into(&mut graph); + MontyObject { graph, root } + } + + /// The child at `id` of the same arena. + #[must_use] + fn child(&self, id: NodeId) -> Self { + self.graph.value(id) + } + + /// The items of a list, tuple, set, frozenset or namedtuple; `None` for + /// any other value. + #[must_use] + pub fn items(&self) -> Option> { + match self.node() { + MontyNode::List(ids) + | MontyNode::Tuple(ids) + | MontyNode::Set(ids) + | MontyNode::FrozenSet(ids) + | MontyNode::NamedTuple { values: ids, .. } => Some(ids.iter().map(|id| self.child(*id)).collect()), + _ => None, + } + } + + /// The `(key, value)` pairs of a dict, or the attrs of a class instance, + /// class type object or module; `None` for any other value. + #[must_use] + pub fn pairs(&self) -> Option> { + let pairs = match self.node() { + MontyNode::Dict(pairs) + | MontyNode::ClassInstance { attrs: pairs, .. } + | MontyNode::Module { attrs: pairs, .. } => pairs, + MontyNode::ClassType(class) => &class.attrs, + _ => return None, + }; + Some( + pairs + .iter() + .map(|(key, value)| (self.child(*key), self.child(*value))) + .collect(), + ) + } + + /// The value as an `int`, if it fits in 64 bits. + #[must_use] + pub fn as_int(&self) -> Option { + match self.node() { + MontyNode::Int(value) => Some(*value), + MontyNode::BigInt(value) => value.to_i64(), + _ => None, + } + } + + /// The value as a `str`. + #[must_use] + pub fn as_str(&self) -> Option<&'a str> { + match self.node() { + MontyNode::String(value) => Some(value), + _ => None, + } + } + + /// The value as a `bool`. + #[must_use] + pub fn as_bool(&self) -> Option { + match self.node() { + MontyNode::Bool(value) => Some(*value), + _ => None, + } + } + + /// The value as a `float`; an `int` converts as Python's `float()` does, + /// with one too large for a float giving `None` where Python overflows. + #[must_use] + pub fn as_float(&self) -> Option { + match self.node() { + MontyNode::Float(value) => Some(*value), + MontyNode::Int(value) => Some(*value as f64), + MontyNode::BigInt(value) => value.to_f64().filter(|f| f.is_finite()), + _ => None, + } + } + + /// The string form of a `decimal.Decimal`, as `str(d)` prints it. + #[must_use] + pub fn as_decimal(&self) -> Option<&str> { + match self.node() { + MontyNode::Decimal(value) => Some(value), + _ => None, + } + } + + /// The value as a `complex`; an `int` or `float` converts as Python's + /// `complex()` does, with a zero imaginary part (see [`as_float`](Self::as_float) + /// for an `int` too large to convert). + #[must_use] + pub fn as_complex(&self) -> Option { + match self.node() { + MontyNode::Complex(value) => Some(*value), + _ => self.as_float().map(|real| MontyComplex { real, imag: 0.0 }), + } + } + + /// The Python `repr()` of the value. + /// + /// # Panics + /// Could panic if out of memory. + #[must_use] + pub fn py_repr(&self) -> String { + let mut s = String::new(); + self.repr_fmt(&mut s).expect("Unable to format repr display value"); + s + } + + /// Whether the value is truthy under Python's rules: `None`, `False`, + /// zero and empty containers are falsy; everything else is truthy. + #[must_use] + pub fn is_truthy(&self) -> bool { + match self.node() { + MontyNode::None => false, + MontyNode::Bool(b) => *b, + MontyNode::Int(i) => *i != 0, + MontyNode::BigInt(bi) => !bi.is_zero(), + MontyNode::Float(f) => *f != 0.0, + MontyNode::Complex(c) => c.real != 0.0 || c.imag != 0.0, + MontyNode::String(s) => !s.is_empty(), + MontyNode::Bytes(b) => !b.is_empty(), + MontyNode::List(items) + | MontyNode::Tuple(items) + | MontyNode::Set(items) + | MontyNode::FrozenSet(items) + | MontyNode::NamedTuple { values: items, .. } => !items.is_empty(), + MontyNode::Dict(pairs) => !pairs.is_empty(), + MontyNode::TimeDelta(delta) => delta.days != 0 || delta.seconds != 0 || delta.microseconds != 0, + MontyNode::Decimal(text) => !decimal_is_zero(text), + _ => true, + } + } + + /// Writes the Python `repr()`. Containers are walked on an explicit stack + /// of their [`ReprPiece`]s, so a deeply nested value costs heap rather than + /// native stack; a sub-object shared `n` times renders `n` times, as + /// CPython's `repr()` does. + fn repr_fmt(&self, f: &mut impl Write) -> fmt::Result { + let mut stack: Vec>> = Vec::new(); + let mut pending = Some(self.id); + loop { + if let Some(id) = pending.take() { + let value = self.child(id); + match value.repr_pieces() { + Some(pieces) => stack.push(pieces.into_iter()), + None => value.leaf_repr_fmt(f)?, + } + } + let Some(pieces) = stack.last_mut() else { + return Ok(()); + }; + match pieces.next() { + Some(ReprPiece::Text(text)) => f.write_str(text)?, + Some(ReprPiece::Child(child)) => pending = Some(child), + None => { + stack.pop(); + } + } + } + } + + /// The pieces of a container's `repr()` in order, or `None` for a leaf. + fn repr_pieces(&self) -> Option>> { + let mut pieces = Vec::new(); + match self.node() { + MontyNode::List(ids) => { + pieces.push(Text("[")); + push_repr_items(&mut pieces, ids); + pieces.push(Text("]")); + } + MontyNode::Tuple(ids) => { + pieces.push(Text("(")); + push_repr_items(&mut pieces, ids); + pieces.push(Text(")")); + } + MontyNode::NamedTuple { + type_name, + field_names, + values, + } => { + // type_name(field1=value1, field2=value2, ...) + pieces.extend([Text(type_name), Text("(")]); + for (i, (name, id)) in field_names.iter().zip(values).enumerate() { + push_repr_separator(&mut pieces, i); + pieces.extend([Text(name), Text("="), Child(*id)]); + } + pieces.push(Text(")")); + } + MontyNode::Dict(pairs) => { + pieces.push(Text("{")); + for (i, (key, value)) in pairs.iter().enumerate() { + push_repr_separator(&mut pieces, i); + pieces.extend([Child(*key), Text(": "), Child(*value)]); + } + pieces.push(Text("}")); + } + MontyNode::Set(ids) if ids.is_empty() => pieces.push(Text("set()")), + MontyNode::Set(ids) => { + pieces.push(Text("{")); + push_repr_items(&mut pieces, ids); + pieces.push(Text("}")); + } + MontyNode::FrozenSet(ids) => { + pieces.push(Text("frozenset(")); + if !ids.is_empty() { + pieces.push(Text("{")); + push_repr_items(&mut pieces, ids); + pieces.push(Text("}")); + } + pieces.push(Text(")")); + } + MontyNode::ClassInstance { attrs, .. } => { + // ClassName(attr1=value1, ...); a non-string key (possible in + // host-built input) renders via its repr rather than panicking. + pieces.extend([Text(self.type_name()), Text("(")]); + for (i, (key, value)) in attrs.iter().enumerate() { + push_repr_separator(&mut pieces, i); + match self.graph.node(*key) { + MontyNode::String(key) => pieces.push(Text(key)), + _ => pieces.push(Child(*key)), + } + pieces.extend([Text("="), Child(*value)]); + } + pieces.push(Text(")")); + } + _ => return None, + } + Some(pieces) + } + + /// Writes the `repr()` of a leaf node. + fn leaf_repr_fmt(&self, f: &mut impl Write) -> fmt::Result { + match self.node() { + MontyNode::Ellipsis => f.write_str("Ellipsis"), + MontyNode::NotImplemented => f.write_str("NotImplemented"), + MontyNode::None => f.write_str("None"), + MontyNode::Bool(true) => f.write_str("True"), + MontyNode::Bool(false) => f.write_str("False"), + MontyNode::Int(v) => write!(f, "{v}"), + MontyNode::BigInt(v) => write!(f, "{v}"), + MontyNode::Float(v) => write!(f, "{}", FormatFloat(*v)), + MontyNode::Complex(c) => write!( + f, + "{}", + FormatComplex { + real: c.real, + imag: c.imag + } + ), + MontyNode::String(s) => string_repr_fmt(s, f), + MontyNode::Bytes(b) => bytes_repr_fmt(b, f), + MontyNode::Date(date) => write!(f, "datetime.date({}, {}, {})", date.year, date.month, date.day), + MontyNode::DateTime(datetime) => { + write!( + f, + "datetime.datetime({}, {}, {}, {}, {}", + datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute + )?; + if datetime.second != 0 || datetime.microsecond != 0 { + write!(f, ", {}", datetime.second)?; + } + if datetime.microsecond != 0 { + write!(f, ", {}", datetime.microsecond)?; + } + if let Some(offset) = datetime.offset_seconds { + tzinfo_repr_fmt(f, offset, datetime.timezone_name.as_deref())?; + } + f.write_char(')') + } + MontyNode::Time(time) => { + write!(f, "datetime.time({}, {}", time.hour, time.minute)?; + // CPython prints `second` whenever either sub-minute field is + // set, so `time(1, 2, 0, 4)` reprs as `(1, 2, 0, 4)`. + if time.second != 0 || time.microsecond != 0 { + write!(f, ", {}", time.second)?; + } + if time.microsecond != 0 { + write!(f, ", {}", time.microsecond)?; + } + if let Some(offset) = time.offset_seconds { + tzinfo_repr_fmt(f, offset, time.timezone_name.as_deref())?; + } + if time.fold != 0 { + write!(f, ", fold={}", time.fold)?; + } + f.write_char(')') + } + MontyNode::TimeDelta(delta) => { + if delta.days == 0 && delta.seconds == 0 && delta.microseconds == 0 { + return f.write_str("datetime.timedelta(0)"); + } + f.write_str("datetime.timedelta(")?; + let mut first = true; + if delta.days != 0 { + write!(f, "days={}", delta.days)?; + first = false; + } + if delta.seconds != 0 { + if !first { + f.write_str(", ")?; + } + write!(f, "seconds={}", delta.seconds)?; + first = false; + } + if delta.microseconds != 0 { + if !first { + f.write_str(", ")?; + } + write!(f, "microseconds={}", delta.microseconds)?; + } + f.write_char(')') + } + MontyNode::Decimal(text) => write!(f, "Decimal('{text}')"), + MontyNode::TimeZone(tz) => { + if tz.offset_seconds == 0 && tz.name.is_none() { + return f.write_str("datetime.timezone.utc"); + } + let timedelta_repr = format_offset_timedelta_repr(tz.offset_seconds); + write!(f, "datetime.timezone({timedelta_repr}")?; + if let Some(name) = &tz.name { + write!(f, ", {}", StringRepr(name))?; + } + f.write_char(')') + } + MontyNode::Exception { exc_type, arg } => { + let type_str: &'static str = exc_type.into(); + write!(f, "{type_str}(")?; + if let Some(arg) = arg { + string_repr_fmt(arg, f)?; + } + f.write_char(')') + } + MontyNode::Path(p) => write!(f, "PosixPath('{p}')"), + MontyNode::FileHandle(handle) => write!(f, "{handle}"), + MontyNode::Type(t) => write!(f, ""), + MontyNode::ClassType(class) => write!(f, "", class.name), + MontyNode::BuiltinFunction(func) => write!(f, ""), + MontyNode::Function { name, .. } => write!(f, ""), + // a module's repr names it without listing its attrs, as CPython's does + MontyNode::Module { name, .. } => write!(f, "", StringRepr(name)), + MontyNode::Repr(s) => write!(f, "Repr({})", StringRepr(s)), + MontyNode::Cycle(placeholder) => f.write_str(placeholder), + MontyNode::List(_) + | MontyNode::Tuple(_) + | MontyNode::NamedTuple { .. } + | MontyNode::Dict(_) + | MontyNode::Set(_) + | MontyNode::FrozenSet(_) + | MontyNode::ClassInstance { .. } => unreachable!("containers render through repr_pieces"), + } + } +} + +/// One step of a container's `repr()`: literal text, or a child rendered in +/// place. Text borrows the arena (a type or field name) or is static. +enum ReprPiece<'a> { + Text(&'a str), + Child(NodeId), +} + +/// Pushes the children at `ids`, comma-separated. +fn push_repr_items(pieces: &mut Vec>, ids: &[NodeId]) { + for (i, id) in ids.iter().enumerate() { + push_repr_separator(pieces, i); + pieces.push(ReprPiece::Child(*id)); + } +} + +/// Pushes the `, ` that precedes every entry but the first. +fn push_repr_separator(pieces: &mut Vec>, index: usize) { + if index > 0 { + pieces.push(ReprPiece::Text(", ")); + } +} + +impl PartialEq for ObjectRef<'_> { + /// Structural equality as Python values: an `int` equals the same + /// `BigInt`, a namedtuple equals a tuple of its values, floats compare + /// bit-for-bit (so `NaN` round-trips equal), and a sub-object shared in + /// one arena equals its copies in another. Linear in the arenas: each + /// pair of nodes is compared once. + fn eq(&self, other: &Self) -> bool { + let mut pending = vec![(self.id, other.id)]; + let mut seen = HashSet::new(); + while let Some((a, b)) = pending.pop() { + if !seen.insert((a, b)) { + continue; + } + if !nodes_eq(self.graph.node(a), other.graph.node(b), &mut pending) { + return false; + } + } + true + } +} + +impl PartialEq for ObjectRef<'_> { + fn eq(&self, other: &MontyObject) -> bool { + *self == other.as_ref() + } +} + +impl fmt::Display for ObjectRef<'_> { + /// The Python `str()` of the value: text as is, everything else its `repr()`. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.node() { + MontyNode::String(s) | MontyNode::Cycle(s) => f.write_str(s), + _ => self.repr_fmt(f), + } + } +} + +impl TryFrom> for i64 { + type Error = ConversionError; + + fn try_from(value: ObjectRef<'_>) -> Result { + match value.node() { + MontyNode::Int(i) => Ok(*i), + _ => Err(ConversionError::new("int", value.type_name())), + } + } +} + +/// An `int` converts as Python's `float()` does. +impl TryFrom> for f64 { + type Error = ConversionError; + + fn try_from(value: ObjectRef<'_>) -> Result { + value + .as_float() + .ok_or_else(|| ConversionError::new("float", value.type_name())) + } +} + +impl TryFrom> for String { + type Error = ConversionError; + + fn try_from(value: ObjectRef<'_>) -> Result { + value + .as_str() + .map(str::to_owned) + .ok_or_else(|| ConversionError::new("str", value.type_name())) + } +} + +/// Only `True`/`False` convert; this is not Python truthiness (see [`ObjectRef::is_truthy`]). +impl TryFrom> for bool { + type Error = ConversionError; + + fn try_from(value: ObjectRef<'_>) -> Result { + value + .as_bool() + .ok_or_else(|| ConversionError::new("bool", value.type_name())) + } +} + +/// Writes the `, tzinfo=...` part of an aware datetime or time repr. +fn tzinfo_repr_fmt(f: &mut impl Write, offset: i32, name: Option<&str>) -> fmt::Result { + if offset == 0 && name.is_none() { + f.write_str(", tzinfo=datetime.timezone.utc") + } else { + let timedelta_repr = format_offset_timedelta_repr(offset); + write!(f, ", tzinfo=datetime.timezone({timedelta_repr}")?; + if let Some(name) = name { + write!(f, ", {}", StringRepr(name))?; + } + f.write_char(')') + } +} + +/// Compares two nodes' own payloads and queues their children pairwise; +/// `false` when the nodes differ in kind, payload or child count. +fn nodes_eq(a: &MontyNode, b: &MontyNode, pending: &mut Vec<(NodeId, NodeId)>) -> bool { + match (a, b) { + // Cross-compare Int and BigInt without allocating a temporary BigInt. + (MontyNode::Int(x), MontyNode::BigInt(y)) | (MontyNode::BigInt(y), MontyNode::Int(x)) => y.to_i64() == Some(*x), + // NamedTuple compares with Tuple by values only (matching Python semantics) + (MontyNode::NamedTuple { values: xs, .. }, MontyNode::Tuple(ys)) + | (MontyNode::Tuple(xs), MontyNode::NamedTuple { values: ys, .. }) => queue_items(xs, ys, pending), + (MontyNode::List(xs), MontyNode::List(ys)) + | (MontyNode::Tuple(xs), MontyNode::Tuple(ys)) + | (MontyNode::Set(xs), MontyNode::Set(ys)) + | (MontyNode::FrozenSet(xs), MontyNode::FrozenSet(ys)) => queue_items(xs, ys, pending), + ( + MontyNode::NamedTuple { + type_name: x_type, + field_names: x_fields, + values: xs, + }, + MontyNode::NamedTuple { + type_name: y_type, + field_names: y_fields, + values: ys, + }, + ) => x_type == y_type && x_fields == y_fields && queue_items(xs, ys, pending), + (MontyNode::Dict(xs), MontyNode::Dict(ys)) => queue_pairs(xs, ys, pending), + (MontyNode::ClassType(x), MontyNode::ClassType(y)) => { + x.name == y.name + && x.id == y.id + && x.host_defined == y.host_defined + && x.is_dataclass == y.is_dataclass + && queue_pairs(&x.attrs, &y.attrs, pending) + } + ( + MontyNode::ClassInstance { + class_type: x_class, + instance_id: x_id, + attrs: xs, + }, + MontyNode::ClassInstance { + class_type: y_class, + instance_id: y_id, + attrs: ys, + }, + ) => { + x_id == y_id && { + pending.push((*x_class, *y_class)); + queue_pairs(xs, ys, pending) + } + } + ( + MontyNode::Module { + name: x_name, + id: x_id, + attrs: xs, + }, + MontyNode::Module { + name: y_name, + id: y_id, + attrs: ys, + }, + ) => x_name == y_name && x_id == y_id && queue_pairs(xs, ys, pending), + // every other pairing is leaf against leaf, or a kind mismatch + _ => a.is_leaf() && b.is_leaf() && a == b, + } +} + +/// Queues two child lists pairwise; `false` when their lengths differ. +fn queue_items(xs: &[NodeId], ys: &[NodeId], pending: &mut Vec<(NodeId, NodeId)>) -> bool { + xs.len() == ys.len() && { + pending.extend(xs.iter().copied().zip(ys.iter().copied())); + true + } +} + +/// Queues two pair lists key-for-key and value-for-value; `false` when +/// their lengths differ. +fn queue_pairs(xs: &[(NodeId, NodeId)], ys: &[(NodeId, NodeId)], pending: &mut Vec<(NodeId, NodeId)>) -> bool { + xs.len() == ys.len() && { + for ((xk, xv), (yk, yv)) in xs.iter().zip(ys) { + pending.push((*xk, *yk)); + pending.push((*xv, *yv)); + } + true + } +} + +/// The positional and keyword arguments of one function or OS call. +/// A sub-object shared within an exported call stays shared at the host boundary. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct CallArgs { + /// The arena holding every argument. + graph: MontyGraph, + /// Ids of the positional arguments, in order. + arg_ids: Vec, + /// Ids of the keyword arguments as `(key, value)` pairs, in order; keys are usually strings. + kwarg_ids: Vec<(NodeId, NodeId)>, +} + +impl CallArgs { + /// No arguments. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Appends a positional argument. + pub fn push_arg(&mut self, value: MontyObject) { + unstable::push_arg(self, value); + } + + /// Appends a keyword argument with a string key. + pub fn push_kwarg(&mut self, name: &str, value: MontyObject) { + unstable::push_kwarg(self, name, value); + } + + /// The `index`th positional argument. + #[must_use] + pub fn arg(&self, index: usize) -> Option> { + self.arg_ids.get(index).map(|id| self.graph.value(*id)) + } + + /// The positional arguments, in order. + #[must_use = "iterators are lazy and do nothing unless consumed"] + pub fn args(&self) -> impl ExactSizeIterator> { + self.arg_ids.iter().map(|id| self.graph.value(*id)) + } + + /// The keyword arguments as `(key, value)` views, in order. + #[must_use = "iterators are lazy and do nothing unless consumed"] + pub fn kwargs(&self) -> impl ExactSizeIterator, ObjectRef<'_>)> { + self.kwarg_ids + .iter() + .map(|(key, value)| (self.graph.value(*key), self.graph.value(*value))) + } + + /// The keyword argument named `name`, if present. + #[must_use] + pub fn kwarg(&self, name: &str) -> Option> { + self.kwargs() + .find(|(key, _)| key.as_str() == Some(name)) + .map(|(_, value)| value) + } + + /// Checks every argument id is inside the arena; run on decoded messages. + fn check_roots(&self) -> Result<(), GraphError> { + self.arg_ids.iter().try_for_each(|id| self.graph.check_root(*id))?; + self.kwarg_ids + .iter() + .try_for_each(|(key, value)| self.graph.check_root(*key).and_then(|()| self.graph.check_root(*value))) + } +} + +/// Positional-only arguments; concrete so an empty `vec![]` infers. +impl From> for CallArgs { + fn from(args: Vec) -> Self { + Self::from((args, Vec::new())) + } +} + +/// Positional and keyword arguments, in order. +impl From<(Vec, Vec<(MontyObject, MontyObject)>)> for CallArgs { + fn from((args, kwargs): (Vec, Vec<(MontyObject, MontyObject)>)) -> Self { + let mut call = Self::new(); + for arg in args { + call.push_arg(arg); + } + call.kwarg_ids = push_pairs(kwargs, &mut call.graph); + call + } +} + +/// The named inputs of one feed, preserving sharing between exported values. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct NamedValues { + /// The arena holding every value. + graph: MontyGraph, + /// `(name, id)` pairs, in order. + names: Vec<(String, NodeId)>, +} + +impl NamedValues { + /// No values. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Appends a named value. + pub fn push(&mut self, name: impl Into, value: MontyObject) { + unstable::push_named(self, name, value); + } + + /// Number of named values. + #[must_use] + pub fn len(&self) -> usize { + self.names.len() + } + + /// Whether there are no named values. + #[must_use] + pub fn is_empty(&self) -> bool { + self.names.is_empty() + } + + /// The `(name, value)` pairs, in order. + #[must_use = "iterators are lazy and do nothing unless consumed"] + pub fn iter(&self) -> impl ExactSizeIterator)> { + self.names + .iter() + .map(|(name, id)| (name.as_str(), self.graph.value(*id))) + } + + /// Checks every id is inside the arena; run on decoded messages. + fn check_roots(&self) -> Result<(), GraphError> { + self.names.iter().try_for_each(|(_, id)| self.graph.check_root(*id)) + } +} + +/// Named values in order; concrete so an empty `vec![]` infers. +impl From> for NamedValues { + fn from(pairs: Vec<(String, MontyObject)>) -> Self { + let mut named = Self::new(); + for (name, value) in pairs { + named.push(name, value); + } + named + } +} + +impl MontyGraph { + /// Borrows the value rooted at `id`. + /// + /// # Panics + /// If `id` is out of range; ids come from this arena, so that is a bug. + #[must_use] + pub fn value(&self, id: NodeId) -> ObjectRef<'_> { + assert!(id.index() < self.len(), "node id {id} is out of range"); + ObjectRef { graph: self, id } + } +} + +impl PushValue for MontyObject { + /// Merges the value's arena in and returns its rebased root. + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + let offset = graph.merge(self.graph); + NodeId(self.root.0 + offset) + } +} + +impl PushValue for ObjectRef<'_> { + /// Copies the reachable nodes; a sub-object shared inside the value stays + /// shared. Linear sweeps over the value's index span, no recursion, so a + /// deep value from an untrusted worker costs heap rather than native stack. + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + let nodes = self.graph.nodes(); + let root = self.id.index(); + // Children are lower than their holder, so the value is inside + // `lowest..=root`. A merged arena keeps each value contiguous, so the + // sweeps cost the value rather than the whole arena before it. + let mut lowest = root; + let mut index = root; + loop { + nodes[index].for_each_child(|child| lowest = lowest.min(child.index())); + if index == lowest { + break; + } + index -= 1; + } + let span = &nodes[lowest..=root]; + // Sweeping downwards from the root visits each holder before its children. + let mut reachable = vec![false; span.len()]; + reachable[root - lowest] = true; + for (offset, node) in span.iter().enumerate().rev() { + if reachable[offset] { + node.for_each_child(|child| reachable[child.index() - lowest] = true); + } + } + // Copying upwards then meets every child before the node holding it. + let mut copied: Vec> = vec![None; span.len()]; + for (offset, node) in span.iter().enumerate() { + if reachable[offset] { + let mut node = node.clone(); + node.for_each_child_mut(|child| { + *child = copied[child.index() - lowest].expect("children are copied first"); + }); + copied[offset] = Some(graph.push(node)); + } + } + copied[root - lowest].expect("the root is copied") + } +} + +/// Pushes each key then value and collects the id pairs. +fn push_pairs( + pairs: impl IntoIterator, + graph: &mut MontyGraph, +) -> Vec<(NodeId, NodeId)> { + pairs + .into_iter() + .map(|(key, value)| { + let key = key.push_into(graph); + let value = value.push_into(graph); + (key, value) + }) + .collect() +} + +/// The Python type of a builtin at the host boundary: the public mirror of +/// the runtime `Type` enum, minus class types, which cross as their own +/// [`class_type`](MontyObject::class_type) value. Serializable and +/// displayable without heap access. +/// +/// Every runtime type is mirrored, not only those a host materialises as its +/// own class: the rest cross as a named proxy so the same type object can +/// round-trip back into the sandbox. +#[derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::EnumIter, + strum::EnumString, + strum::IntoStaticStr, + strum::VariantNames, +)] +#[strum(serialize_all = "lowercase")] +pub enum MontyType { + Ellipsis, + Type, + #[strum(serialize = "NoneType")] + NoneType, + Bool, + Int, + Float, + Complex, + Range, + Slice, + /// The four `datetime` classes carry the qualified names the runtime + /// `Type` uses (`datetime.date`, ...) rather than bare `date`, so a type + /// object keeps one name either side of the boundary. + #[strum(serialize = "datetime.date")] + Date, + #[strum(serialize = "datetime.datetime")] + DateTime, + #[strum(serialize = "datetime.timedelta")] + TimeDelta, + #[strum(serialize = "datetime.timezone")] + TimeZone, + Str, + Bytes, + List, + /// `collections.deque`. Qualified like `datetime.datetime` so the + /// host-boundary name matches the runtime `Type::Deque` (`collections.deque`) + /// rather than a bare `deque`. + #[strum(serialize = "collections.deque")] + Deque, + #[strum(serialize = "list_iterator")] + ListIterator, + #[strum(serialize = "callable_iterator")] + CallableIterator, + Tuple, + NamedTuple, + Dict, + #[strum(serialize = "dict_keys")] + DictKeys, + #[strum(serialize = "dict_items")] + DictItems, + #[strum(serialize = "dict_values")] + DictValues, + Set, + FrozenSet, + /// Exception types render/parse via `ExcType`'s own strum name + /// (`"ValueError"`, `"json.JSONDecodeError"`, ...), so this variant is + /// `#[strum(disabled)]`: [`name`](Self::name) and + /// [`from_type_name`](Self::from_type_name) peel `Exception` off + /// explicitly. + #[strum(disabled)] + Exception(ExcType), + Function, + #[strum(serialize = "builtin_function_or_method")] + BuiltinFunction, + Cell, + Iterator, + Coroutine, + Module, + #[strum(serialize = "_io.TextIOWrapper")] + TextIOWrapper, + #[strum(serialize = "_io.BufferedReader")] + BufferedReader, + #[strum(serialize = "_io.BufferedWriter")] + BufferedWriter, + #[strum(serialize = "_io.BufferedRandom")] + BufferedRandom, + #[strum(serialize = "typing._SpecialForm")] + SpecialForm, + #[strum(serialize = "PosixPath")] + Path, + Property, + #[strum(serialize = "re.Pattern")] + RePattern, + #[strum(serialize = "re.Match")] + ReMatch, + // Variants serialize by name into dumps: renaming one needs `#[serde(alias)]`. + #[strum(serialize = "tuple_iterator")] + TupleIterator, + #[strum(serialize = "str_ascii_iterator")] + StrAsciiIterator, + #[strum(serialize = "str_iterator")] + StrIterator, + #[strum(serialize = "bytes_iterator")] + BytesIterator, + #[strum(serialize = "range_iterator")] + RangeIterator, + #[strum(serialize = "dict_keyiterator")] + DictKeyIterator, + #[strum(serialize = "dict_itemiterator")] + DictItemIterator, + #[strum(serialize = "dict_valueiterator")] + DictValueIterator, + #[strum(serialize = "set_iterator")] + SetIterator, + #[strum(serialize = "itertools.count")] + ItertoolsCount, + #[strum(serialize = "itertools.repeat")] + ItertoolsRepeat, + /// A `dataclasses.Field` describing one field of a sandbox `@dataclass`, + /// as found in a class's `__dataclass_fields__`. + #[strum(serialize = "Field")] + Field, + #[strum(serialize = "itertools.pairwise")] + ItertoolsPairwise, + #[strum(serialize = "itertools.compress")] + ItertoolsCompress, + #[strum(serialize = "itertools.islice")] + ItertoolsIslice, + #[strum(serialize = "itertools.chain")] + ItertoolsChain, + #[strum(serialize = "itertools.cycle")] + ItertoolsCycle, + #[strum(serialize = "NotImplementedType")] + NotImplementedType, + /// The `__dataclass_params__` of a sandbox `@dataclass`: the options it was + /// decorated with, named as CPython's private class reports itself. + #[strum(serialize = "_DataclassParams")] + DataclassParams, + #[strum(serialize = "itertools.takewhile")] + ItertoolsTakeWhile, + #[strum(serialize = "itertools.dropwhile")] + ItertoolsDropWhile, + #[strum(serialize = "itertools.filterfalse")] + ItertoolsFilterFalse, + #[strum(serialize = "itertools.starmap")] + ItertoolsStarMap, + /// The builtin `object`, which the sandbox exposes as a name only — it is + /// not a base class and cannot be constructed. + Object, + #[strum(serialize = "datetime.time")] + Time, + /// `functools.partial`, qualified the way CPython's `tp_name` is. + #[strum(serialize = "functools.partial")] + Partial, + #[strum(serialize = "itertools.accumulate")] + ItertoolsAccumulate, + #[strum(serialize = "itertools.batched")] + ItertoolsBatched, + #[strum(serialize = "itertools.zip_longest")] + ItertoolsZipLongest, + /// `types.GenericAlias`, the type of `list[int]`, qualified the way CPython's `tp_name` is. + #[strum(serialize = "types.GenericAlias")] + GenericAlias, + /// `typing.Union`, the type of `int | None` (one object with `types.UnionType` since 3.14). + #[strum(serialize = "typing.Union")] + Union, + #[strum(serialize = "itertools.combinations")] + ItertoolsCombinations, + #[strum(serialize = "itertools.combinations_with_replacement")] + ItertoolsCombinationsWithReplacement, + #[strum(serialize = "itertools.permutations")] + ItertoolsPermutations, + #[strum(serialize = "itertools.product")] + ItertoolsProduct, + #[strum(serialize = "itertools.groupby")] + ItertoolsGroupBy, + #[strum(serialize = "itertools._grouper")] + ItertoolsGrouper, + #[strum(serialize = "itertools._tee")] + ItertoolsTee, + #[strum(serialize = "itertools._tee_dataobject")] + ItertoolsTeeDataObject, + /// The wrapper `functools.lru_cache` / `functools.cache` returns. + #[strum(serialize = "functools._lru_cache_wrapper")] + LruCacheWrapper, + /// `decimal.Decimal`, qualified the way CPython's `tp_name` is. + #[strum(serialize = "decimal.Decimal")] + Decimal, +} + +impl fmt::Display for MontyType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +impl MontyType { + /// The Python-visible name of this type (`"int"`, `"datetime.datetime"`, + /// `"ValueError"`). + #[must_use] + pub fn name(&self) -> &str { + match self { + Self::Exception(exc_type) => (*exc_type).into(), + // Every remaining variant is named by strum's `IntoStaticStr` + // (`Exception` is peeled off above). + other => other.into(), + } + } + + /// Parses builtin and exception type names produced by [`Display`](fmt::Display)/[`name`](Self::name). + /// Unrecognized names return `None`; `"object"` parses to [`Object`](Self::Object). + #[must_use] + pub fn from_type_name(name: &str) -> Option { + name.parse::() + .ok() + .or_else(|| name.parse::().ok().map(Self::Exception)) + } +} + +/// A Python `datetime.date` value with year, month, and day components. +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct MontyDate { + /// Gregorian year in range 1..=9999. + pub year: i32, + /// Month component in range 1..=12. + pub month: u8, + /// Day component valid for the given month/year. + pub day: u8, +} + +/// A Python `datetime.datetime` value with date, time, and optional timezone components. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct MontyDateTime { + /// Gregorian year in range 1..=9999. + pub year: i32, + /// Month component in range 1..=12. + pub month: u8, + /// Day component valid for the given month/year. + pub day: u8, + /// Hour in range 0..=23. + pub hour: u8, + /// Minute in range 0..=59. + pub minute: u8, + /// Second in range 0..=59. + pub second: u8, + /// Microsecond in range 0..=999_999. + pub microsecond: u32, + /// Fixed offset seconds for aware datetimes, or `None` for naive values. + /// + /// Within [`MIN_TIMEZONE_OFFSET_SECONDS`]..=[`MAX_TIMEZONE_OFFSET_SECONDS`] when set. + pub offset_seconds: Option, + /// Optional explicit timezone name for aware datetimes. + /// + /// Must be `None` when `offset_seconds` is `None`. + pub timezone_name: Option, +} + +/// A Python `datetime.time` value: a wall clock with no date attached. +/// +/// `fold` is carried so the flag survives the boundary, but neither monty nor +/// this type interprets it — as in CPython it takes no part in equality. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct MontyTime { + /// Hour in range 0..=23. + pub hour: u8, + /// Minute in range 0..=59. + pub minute: u8, + /// Second in range 0..=59. + pub second: u8, + /// Microsecond in range 0..=999_999. + pub microsecond: u32, + /// Fixed offset seconds for aware times, or `None` for naive values. + /// + /// Within [`MIN_TIMEZONE_OFFSET_SECONDS`]..=[`MAX_TIMEZONE_OFFSET_SECONDS`] when set. + pub offset_seconds: Option, + /// Optional explicit timezone name for aware times. + /// + /// Must be `None` when `offset_seconds` is `None`. + pub timezone_name: Option, + /// Fold flag, 0 or 1. + pub fold: u8, +} + +/// A Python `complex` value as its two `float` parts. +/// +/// Compared bit-for-bit inside a graph (see `MontyNode`'s `PartialEq`), so a +/// `NaN` part round-trips equal and `-0.0` stays distinct from `0.0`. +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +pub struct MontyComplex { + /// The real part. + pub real: f64, + /// The imaginary part. + pub imag: f64, +} + +impl MontyComplex { + /// Bit-for-bit equality of both parts. + #[must_use] + pub fn bits_eq(&self, other: &Self) -> bool { + self.real.to_bits() == other.real.to_bits() && self.imag.to_bits() == other.imag.to_bits() + } +} + +/// A Python `datetime.timedelta` value representing a duration. +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct MontyTimeDelta { + /// Day component. + pub days: i32, + /// Seconds component in normalized range 0..86400. + pub seconds: i32, + /// Microseconds component in normalized range 0..1_000_000. + pub microseconds: i32, +} + +/// Smallest UTC offset `datetime.timezone` accepts, -23:59:59. +/// +/// CPython requires an offset strictly inside ±24 hours. Shared with the wire +/// decoder so a forged offset is rejected at the boundary rather than by the +/// sandbox-side constructor, which by then can only report a generic bad value. +pub const MIN_TIMEZONE_OFFSET_SECONDS: i32 = -86_399; +/// Largest UTC offset `datetime.timezone` accepts, +23:59:59. +/// +/// See [`MIN_TIMEZONE_OFFSET_SECONDS`]. +pub const MAX_TIMEZONE_OFFSET_SECONDS: i32 = 86_399; + +/// A Python `datetime.timezone` fixed-offset timezone. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct MontyTimeZone { + /// Fixed UTC offset in seconds, within [`MIN_TIMEZONE_OFFSET_SECONDS`]..=[`MAX_TIMEZONE_OFFSET_SECONDS`]. + pub offset_seconds: i32, + /// Optional display name. + pub name: Option, +} + +/// Wall-clock microseconds since midnight, before any offset is applied. +/// +/// Every field is range-bounded by its type, so this is total and cannot +/// overflow — unlike the datetime equivalent, which can fail on an invalid date. +fn monty_time_local_micros(time: &MontyTime) -> i64 { + i64::from(time.hour) * 3_600_000_000 + + i64::from(time.minute) * 60_000_000 + + i64::from(time.second) * 1_000_000 + + i64::from(time.microsecond) +} + +/// Comparison key: offset-adjusted microseconds for an aware time, wall-clock +/// microseconds for a naive one. +/// +/// The adjusted value is deliberately NOT wrapped into a 24-hour day — a bare +/// time has no date to carry into, so `time(1, 0, utc)` differs from +/// `time(23, 0, minus_two)`, as in CPython. +fn monty_time_key(time: &MontyTime) -> i64 { + monty_time_local_micros(time) - i64::from(time.offset_seconds.unwrap_or(0)) * 1_000_000 +} + +/// Aware and naive times never compare equal, and `fold` takes no part — +/// both matching CPython. +impl PartialEq for MontyTime { + fn eq(&self, other: &Self) -> bool { + self.offset_seconds.is_some() == other.offset_seconds.is_some() && monty_time_key(self) == monty_time_key(other) + } +} + +impl Eq for MontyTime {} + +impl Hash for MontyTime { + fn hash(&self, state: &mut H) { + // Must agree with `PartialEq`: awareness and the adjusted key only, + // never `fold`. + self.offset_seconds.is_some().hash(state); + monty_time_key(self).hash(state); + } +} + +impl PartialEq for MontyDateTime { + fn eq(&self, other: &Self) -> bool { + let self_aware = self.offset_seconds.is_some(); + let other_aware = other.offset_seconds.is_some(); + if self_aware != other_aware { + return false; + } + + if self_aware { + return monty_datetime_utc_micros(self) + .zip(monty_datetime_utc_micros(other)) + .is_some_and(|(lhs, rhs)| lhs == rhs) + || monty_datetime_raw_eq(self, other); + } + + monty_datetime_local_micros(self) + .zip(monty_datetime_local_micros(other)) + .is_some_and(|(lhs, rhs)| lhs == rhs) + || monty_datetime_raw_eq(self, other) + } +} + +impl Eq for MontyDateTime {} + +impl Hash for MontyDateTime { + fn hash(&self, state: &mut H) { + if self.offset_seconds.is_some() + && let Some(utc_micros) = monty_datetime_utc_micros(self) + { + utc_micros.hash(state); + return; + } + if let Some(local_micros) = monty_datetime_local_micros(self) { + local_micros.hash(state); + return; + } + + // Invalid carrier values should still hash deterministically instead of panicking. + self.year.hash(state); + self.month.hash(state); + self.day.hash(state); + self.hour.hash(state); + self.minute.hash(state); + self.second.hash(state); + self.microsecond.hash(state); + self.offset_seconds.hash(state); + self.timezone_name.hash(state); + } +} + +impl PartialEq for MontyTimeZone { + fn eq(&self, other: &Self) -> bool { + self.offset_seconds == other.offset_seconds + } +} + +impl Eq for MontyTimeZone {} + +impl Hash for MontyTimeZone { + fn hash(&self, state: &mut H) { + self.offset_seconds.hash(state); + } +} + +/// Error returned when a [`MontyObject`] cannot be converted to the requested Rust type. +/// +/// Returned by the `TryFrom` implementations when an [`ObjectRef`] holds a +/// different kind of value than the one requested. +#[derive(Debug)] +pub struct ConversionError { + /// The type name that was expected (e.g., "int", "str"). + pub expected: &'static str, + /// The actual type name of the value (e.g., "list", "NoneType", or a + /// class instance's class name). + pub actual: String, +} + +impl ConversionError { + /// Creates a new [`ConversionError`] with the expected and actual type names. + #[must_use] + pub fn new(expected: &'static str, actual: impl Into) -> Self { + Self { + expected, + actual: actual.into(), + } + } +} + +impl fmt::Display for ConversionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "expected {}, got {}", self.expected, self.actual) + } +} + +impl Error for ConversionError {} + +/// Error returned when a value cannot be used as an input to code execution. +/// +/// This can occur when: +/// - A value (like [`MontyObject::repr`]) is only valid as an output, not an input +/// - A resource limit is exceeded during conversion +#[derive(Debug, Clone)] +pub enum InvalidInputError { + /// The input type is not valid for conversion to a runtime Value. + /// Message explaining why the type is invalid. + InvalidType(Cow<'static, str>), + /// A resource limit was exceeded during conversion. + Resource(ResourceError), +} + +impl InvalidInputError { + /// Creates a new [`InvalidInputError`] for the given type name. + #[must_use] + pub fn invalid_type(msg: impl Into>) -> Self { + Self::InvalidType(msg.into()) + } +} + +impl fmt::Display for InvalidInputError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidType(msg) => write!(f, "{msg}"), + Self::Resource(e) => write!(f, "{e}"), + } + } +} + +impl Error for InvalidInputError {} + +impl From for InvalidInputError { + fn from(err: ResourceError) -> Self { + Self::Resource(err) + } +} + +/// An open file object (the result of `open()`). +/// +/// This is the boundary representation of Monty's heap `OpenFile` +/// wrapper. It carries everything needed to service a file operation from a +/// host that holds no live OS handle: the virtual `path`, the `mode`, and +/// the byte `position` for seek-aware reads. +/// +/// The host produces a `FileHandle` as the result of an +/// [`OsFunctionCall::Open`](crate::os::OsFunctionCall::Open) call; the +/// interpreter then builds its heap file wrapper from it. Conversely, a heap file +/// object passed as an argument to a `read`/`write` OS call is converted +/// back to a `FileHandle` so the host receives this state. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct MontyFileHandle { + /// The virtual (sandbox) path of the file. Never a host path. + pub path: String, + /// The parsed `open()` mode. + pub mode: FileMode, + /// Position for sized/line/seek operations: char index in text mode, + /// byte index in binary mode. `0` for a freshly opened file. + pub position: u64, +} + +impl fmt::Display for MontyFileHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "<{} name={} mode={}>", + self.mode.file_type_name(), + StringRepr(&self.path), + StringRepr(self.mode.as_str()) + ) + } +} + +fn monty_datetime_local_micros(datetime: &MontyDateTime) -> Option { + monty_datetime_naive(datetime).map(|naive| naive.and_utc().timestamp_micros()) +} + +fn monty_datetime_raw_eq(a: &MontyDateTime, b: &MontyDateTime) -> bool { + a.year == b.year + && a.month == b.month + && a.day == b.day + && a.hour == b.hour + && a.minute == b.minute + && a.second == b.second + && a.microsecond == b.microsecond + && a.offset_seconds == b.offset_seconds + && a.timezone_name == b.timezone_name +} + +fn monty_datetime_utc_micros(datetime: &MontyDateTime) -> Option { + let offset_seconds = datetime.offset_seconds?; + let offset_delta = ChronoTimeDelta::try_seconds(i64::from(offset_seconds))?; + let utc = monty_datetime_naive(datetime)?.checked_sub_signed(offset_delta)?; + Some(utc.and_utc().timestamp_micros()) +} + +fn monty_datetime_naive(datetime: &MontyDateTime) -> Option { + let date = NaiveDate::from_ymd_opt(datetime.year, u32::from(datetime.month), u32::from(datetime.day))?; + let time = NaiveTime::from_hms_micro_opt( + u32::from(datetime.hour), + u32::from(datetime.minute), + u32::from(datetime.second), + datetime.microsecond, + )?; + Some(date.and_time(time)) +} + +/// Whether a `Decimal` string form is a (signed) zero: every mantissa digit is `0`. +/// +/// NaNs and infinities contain letters before any exponent, so they are never zero. +/// Surrounding whitespace and underscores are ignored, as `Decimal(text)` ignores them. +fn decimal_is_zero(text: &str) -> bool { + let unsigned = text.trim().trim_start_matches(['+', '-']); + let mantissa = unsigned.split(['e', 'E']).next().unwrap_or_default(); + mantissa.bytes().any(|b| b == b'0') && mantissa.bytes().all(|b| matches!(b, b'0' | b'.' | b'_')) +} diff --git a/crates/bashkit-monty-types/src/object/unstable.rs b/crates/bashkit-monty-types/src/object/unstable.rs new file mode 100644 index 000000000..e9b73fb71 --- /dev/null +++ b/crates/bashkit-monty-types/src/object/unstable.rs @@ -0,0 +1,221 @@ +//! Representation access for bindings and transport adapters. +//! +//! These APIs expose the current storage of boundary values and carry no API +//! compatibility guarantee: they may change or be removed in any release. +//! Prefer [`MontyObject::as_ref`] and its value accessors when possible. + +use num_bigint::BigInt; + +use super::{CallArgs, MontyObject, NamedValues, ObjectRef}; +pub use crate::graph::{ClassTypeNode, GraphError, MontyGraph, MontyNode, NodeId}; +use crate::{file_mode::FileMode, os::TimeCaller}; + +/// The owned arena, positional roots and keyword roots of a call. +pub type CallArgsParts = (MontyGraph, Vec, Vec<(NodeId, NodeId)>); +/// Borrowed call storage, without copying nodes or roots. +pub type CallArgsPartsRef<'a> = (&'a MontyGraph, &'a [NodeId], &'a [(NodeId, NodeId)]); +/// Mutable call storage for graph-level construction. +pub type CallArgsPartsMut<'a> = (&'a mut MontyGraph, &'a mut Vec, &'a mut Vec<(NodeId, NodeId)>); + +/// Borrows the current arena and its root without copying. +/// This exposes storage rather than a stable value interface. +/// +/// ``` +/// use monty_types::{MontyObject, unstable}; +/// let value = MontyObject::int(42); +/// let (graph, root) = unstable::graph_parts(&value); +/// assert_eq!(graph.value(root), value.as_ref()); +/// ``` +#[must_use] +pub fn graph_parts(value: &MontyObject) -> (&MontyGraph, NodeId) { + (&value.graph, value.root) +} + +/// Takes the current arena and root without copying. +/// Rebuild an edited graph with [`object_from_graph`] to check the root pairing. +#[must_use] +pub fn into_graph_parts(value: MontyObject) -> (MontyGraph, NodeId) { + (value.graph, value.root) +} + +/// Pairs an arena with a root, checking the root is in range. +pub fn object_from_graph(graph: MontyGraph, root: NodeId) -> Result { + MontyObject::new(graph, root) +} + +/// Builds a value from a single node. +/// +/// # Panics +/// If the node holds child ids or otherwise fails graph validation. +#[must_use] +pub fn object_from_node(node: MontyNode) -> MontyObject { + MontyObject::leaf(node) +} + +/// Borrows the stored root node, exposing its arena-relative child ids. +#[must_use] +pub fn root_node(value: &MontyObject) -> &MontyNode { + value.root_node() +} + +/// Borrows the stored node of a value view, exposing its arena-relative child ids. +#[must_use] +pub fn node(value: ObjectRef<'_>) -> &MontyNode { + value.node() +} + +/// Borrows another node from the view's arena. +/// +/// # Panics +/// If `id` is out of range; ids must come from this arena. +#[must_use] +pub fn child(value: ObjectRef<'_>, id: NodeId) -> ObjectRef<'_> { + value.child(id) +} + +/// Borrows the arena and roots of a call without copying. +#[must_use] +pub fn call_args_parts(args: &CallArgs) -> CallArgsPartsRef<'_> { + (&args.graph, &args.arg_ids, &args.kwarg_ids) +} + +/// Borrows call storage for graph-level construction. +/// Restore valid roots before inspecting or transmitting the arguments. +#[must_use] +pub fn call_args_parts_mut(args: &mut CallArgs) -> CallArgsPartsMut<'_> { + (&mut args.graph, &mut args.arg_ids, &mut args.kwarg_ids) +} + +/// Takes the arena and roots of a call without copying. +#[must_use] +pub fn into_call_args_parts(args: CallArgs) -> CallArgsParts { + (args.graph, args.arg_ids, args.kwarg_ids) +} + +/// Builds a call from graph storage, rejecting out-of-range argument roots. +pub fn call_args_from_parts( + graph: MontyGraph, + arg_ids: Vec, + kwarg_ids: Vec<(NodeId, NodeId)>, +) -> Result { + let args = CallArgs { + graph, + arg_ids, + kwarg_ids, + }; + args.check_roots()?; + Ok(args) +} + +/// Borrows the arena and named roots of a feed without copying. +#[must_use] +pub fn named_values_parts(values: &NamedValues) -> (&MontyGraph, &[(String, NodeId)]) { + (&values.graph, &values.names) +} + +/// Takes the arena and named roots of a feed without copying. +#[must_use] +pub fn into_named_values_parts(values: NamedValues) -> (MontyGraph, Vec<(String, NodeId)>) { + (values.graph, values.names) +} + +/// Builds feed inputs from graph storage, rejecting out-of-range value roots. +pub fn named_values_from_parts(graph: MontyGraph, names: Vec<(String, NodeId)>) -> Result { + let values = NamedValues { graph, names }; + values.check_roots()?; + Ok(values) +} + +/// Appends an argument directly to the call's arena and returns its node id. +pub fn push_arg(args: &mut CallArgs, value: impl PushValue) -> NodeId { + let id = value.push_into(&mut args.graph); + args.arg_ids.push(id); + id +} + +/// Appends a keyword argument directly to the call's arena. +pub fn push_kwarg(args: &mut CallArgs, name: &str, value: impl PushValue) { + let key = args.graph.push(MontyNode::String(name.to_owned())); + let value = value.push_into(&mut args.graph); + args.kwarg_ids.push((key, value)); +} + +/// Appends a named value directly to the feed's arena and returns its node id. +pub fn push_named(values: &mut NamedValues, name: impl Into, value: impl PushValue) -> NodeId { + let id = value.push_into(&mut values.graph); + values.names.push((name.into(), id)); + id +} + +/// Consumes `self` into a node of `graph`, returning its id. +/// Composite values push their children first so the arena stays post-order. +pub trait PushValue { + /// Appends a value with its children below it, returning its arena-relative id. + fn push_into(self, graph: &mut MontyGraph) -> NodeId; +} + +impl PushValue for MontyNode { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + graph.push(self) + } +} + +impl PushValue for String { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + graph.push(MontyNode::String(self)) + } +} + +impl PushValue for Vec { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + graph.push(MontyNode::Bytes(self)) + } +} + +impl PushValue for i64 { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + graph.push(MontyNode::Int(self)) + } +} + +/// Counts above `i64::MAX` cross as `BigInt`, so a host handler receives the +/// exact value and its own cap decides what to do with it. +impl PushValue for u64 { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + graph.push(i64::try_from(self).map_or_else(|_| MontyNode::BigInt(BigInt::from(self)), MontyNode::Int)) + } +} + +impl PushValue for u32 { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + graph.push(MontyNode::Int(i64::from(self))) + } +} + +/// `None` crosses as Python `None`. +impl PushValue for Option { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + match self { + Some(value) => value.push_into(graph), + None => graph.push(MontyNode::None), + } + } +} + +impl PushValue for bool { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + graph.push(MontyNode::Bool(self)) + } +} + +impl PushValue for FileMode { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + graph.push(MontyNode::String(self.as_str().to_owned())) + } +} + +impl PushValue for TimeCaller { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + graph.push(MontyNode::String(self.as_str().to_owned())) + } +} diff --git a/crates/bashkit-monty-types/src/os.rs b/crates/bashkit-monty-types/src/os.rs new file mode 100644 index 000000000..704b271e8 --- /dev/null +++ b/crates/bashkit-monty-types/src/os.rs @@ -0,0 +1,787 @@ +//! OS-level operations that require host system access. +//! +//! Defines [`OsFunctionCall`] — a tagged dispatch value whose variants carry +//! the typed args each OS-call accepts. Sandboxed code suspends with one of +//! these; the host (a `MountTable`, an `os` callback) decides whether to +//! permit it. The interpreter itself never performs I/O. +//! +//! The fs/ layer matches on the enum directly (no value introspection); +//! host bindings get a generic `(positional, keyword)` view via +//! [`OsFunctionCall::to_args`]. + +use std::{borrow::Cow, fmt, ops::Deref, time::Duration}; + +use crate::{ + args::ToArgs, + exceptions::{ExcType, MontyException}, + file_mode::FileMode, + format::StringRepr, + graph::{MontyGraph, MontyNode, NodeId}, + object::{CallArgs, MontyObject, MontyTimeZone}, + scan::ScanArgs, + unstable::{self, PushValue}, + virtual_path::normalize_virtual_path, +}; +// ============================================================================= +// OsFunctionCall — the central public dispatch value. +// ============================================================================= + +/// [`OsFunctionCall::Import`]'s dispatch name. Hosts resolve it from their modules before other OS handlers. +pub const IMPORT_CALL: &str = "import"; + +/// [`OsFunctionCall::ImportStubs`]'s dispatch name, handled like [`IMPORT_CALL`]. +pub const IMPORT_STUBS_CALL: &str = "import_stubs"; + +/// Reserved pre-feed [`OsFunctionCall::ImportStubs`] ID, outside the interpreter's IDs counted from zero. +pub const IMPORT_STUBS_CALL_ID: u32 = u32::MAX; + +/// Tagged dispatch value for OS-level operations. +/// +/// Each variant carries the strongly-typed args/kwargs the corresponding OS +/// call needs. The fs/ layer matches on this enum directly (no value +/// introspection); host bindings get a generic `(positional, keyword)` view +/// via [`OsFunctionCall::to_args`]. +/// +/// See the module docs for how to add a new variant. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, strum::IntoStaticStr)] +pub enum OsFunctionCall { + // ---- FS read / check (single path) ------------------------------------ + /// Check if a path exists. + #[strum(serialize = "Path.exists")] + Exists(MontyPath), + /// Check if path is a regular file. + #[strum(serialize = "Path.is_file")] + IsFile(MontyPath), + /// Check if path is a directory. + #[strum(serialize = "Path.is_dir")] + IsDir(MontyPath), + /// Check if path is a symbolic link. + #[strum(serialize = "Path.is_symlink")] + IsSymlink(MontyPath), + /// Read file contents as text. + #[strum(serialize = "Path.read_text")] + ReadText(MontyPath), + /// Read file contents as bytes. + #[strum(serialize = "Path.read_bytes")] + ReadBytes(MontyPath), + /// `stat()` — return a stat result tuple. + #[strum(serialize = "Path.stat")] + Stat(MontyPath), + /// List directory contents. + #[strum(serialize = "Path.iterdir")] + Iterdir(MontyPath), + /// Read a bounded subtree in one call, for `os.scandir`, `os.walk`, + /// `Path.walk`, `Path.glob` and `Path.rglob` (see [`crate::scan`]). + #[strum(serialize = "Path.scan")] + Scan(ScanArgs), + /// Resolve symlinks and return absolute path. + #[strum(serialize = "Path.resolve")] + Resolve(MontyPath), + /// Absolute path without symlink resolution. + #[strum(serialize = "Path.absolute")] + Absolute(MontyPath), + + // ---- FS write (path + data) ------------------------------------------- + /// Write text to file (truncating). + #[strum(serialize = "Path.write_text")] + WriteText(PathStringDataArgs), + /// Append text to file. + #[strum(serialize = "Path.append_text")] + AppendText(PathStringDataArgs), + /// Write bytes to file (truncating). + #[strum(serialize = "Path.write_bytes")] + WriteBytes(PathBytesDataArgs), + /// Append bytes to file. + #[strum(serialize = "Path.append_bytes")] + AppendBytes(PathBytesDataArgs), + + // ---- FS mutate (custom shapes) ---------------------------------------- + /// Open a file. The host performs the open-time effect (truncate for + /// `w`/`w+`, create-if-missing for `a`/`a+`, existence check for `r`/`r+`) + /// and returns a [`MontyFileHandle`](crate::MontyFileHandle) — it never holds a live OS + /// handle across calls. + #[strum(serialize = "open")] + Open(OpenCallArgs), + /// Create directory (`parents`/`exist_ok` kwargs). + #[strum(serialize = "Path.mkdir")] + Mkdir(MkdirCallArgs), + /// Remove file. + #[strum(serialize = "Path.unlink")] + Unlink(MontyPath), + /// Remove directory. + #[strum(serialize = "Path.rmdir")] + Rmdir(MontyPath), + /// Rename / move (src → dst). + #[strum(serialize = "Path.rename")] + Rename(RenameCallArgs), + + // ---- Non-FS ----------------------------------------------------------- + /// Get an environment variable value. + #[strum(serialize = "os.getenv")] + Getenv(GetenvArgs), + /// Get the entire environment as a dictionary. + #[strum(serialize = "os.environ")] + GetEnviron, + /// Get today's date from the host system (for `date.today()`). + #[strum(serialize = "date.today")] + DateToday, + /// Get the current date/time from the host system (for `datetime.now(tz=...)`). + /// Carries the timezone argument, `None` for a naive result. + #[strum(serialize = "datetime.now")] + DateTimeNow(Option), + /// Read `size` bytes of entropy from the host (for `os.urandom(size)`, and + /// how the `random` module seeds an unseeded generator). + #[strum(serialize = "os.urandom")] + Urandom(UrandomArgs), + /// Read the host clock as `time.time()` does: seconds since the Unix + /// epoch, answered with [`MontyObject::float`]. Every clock-reading `time` + /// function arrives here; [`TimeCaller`], the call's only argument, says which. + #[strum(serialize = "time.time")] + Time(TimeCaller), + /// `time.sleep(seconds)` under `SleepMode::CallHost` — the host's `os` + /// handler waits, then answers with any value (`time.sleep` discards it + /// and evaluates to `None`). + #[strum(serialize = "time.sleep")] + Sleep(Duration), + /// `time.sleep(seconds)` under `SleepMode::System`, capped at its maximum. + /// The host charges `max_total_sleep`, waits and returns `None` without its + /// `os` handler. The distinct name identifies the policy for the host. + #[strum(serialize = "system.sleep")] + SystemSleep(Duration), + /// `asyncio.sleep(delay)` — like [`Sleep`](Self::Sleep), except the + /// sandbox turns the answer into an awaitable, so a host that runs an + /// event loop should answer with a future (`ExtFunctionResult::Future`) + /// and resolve it when the delay elapses, letting sibling tasks run + /// meanwhile. The answer's value is ignored: the sandbox keeps the + /// `result` argument itself and produces it from the `await`. + #[strum(serialize = "asyncio.sleep")] + AsyncSleep(Duration), + /// `asyncio.sleep(delay)` under `SleepMode::System`: the awaitable form of + /// [`SystemSleep`](Self::SystemSleep), which a host running an event loop + /// answers with a future it resolves once the delay elapses. + #[strum(serialize = "system.async_sleep")] + AsyncSystemSleep(Duration), + + // ---- Host modules ------------------------------------------------------ + /// Requests a missing module by top-level name. The host returns its value, an exception, + /// or `not_found` / `not_handled` to raise `ModuleNotFoundError`. + /// `from m import a` and `import m.sub` then load attributes from that value. + #[strum(serialize = "import")] // IMPORT_CALL + Import(String), + /// Requests stubs for previously unrequested top-level imports before type-checking a feed. + /// The host returns a dict of dotted module paths to stub source (or `None`), + /// or `not_found` / `not_handled` for no stubs. + #[strum(serialize = "import_stubs")] // IMPORT_STUBS_CALL + ImportStubs(Vec), +} + +impl OsFunctionCall { + /// Whether this [`name`](Self::name) accepts `ExtFunctionResult::Future`, + /// letting other tasks run until the host resolves it. Only `asyncio.sleep` + /// qualifies, in either sleep mode; all other calls require an immediate answer. + #[must_use] + pub fn accepts_future(name: &str) -> bool { + matches!(name, "asyncio.sleep" | "system.async_sleep") + } + + /// Stable string name for this OS function — surfaces in + /// [`Self::on_no_handler`] errors, host `os` callbacks, and serialised + /// snapshots. The strum `serialize` string on each variant. + #[must_use] + pub fn name(&self) -> &'static str { + self.into() + } + + /// Projects this call's args into the [`CallArgs`] delivered to a host + /// callback, with lexically normalized paths. Empty paths stay empty. The + /// interpreter checks NUL bytes before dispatch; hosts constructing calls + /// must use [`Self::check_path_null_bytes`] first. Mounts must validate + /// length limits on the original typed call. + #[must_use] + pub fn to_args(mut self) -> CallArgs { + for path in self.fs_paths_mut() { + if !path.is_empty() + && let Cow::Owned(normalized) = normalize_virtual_path(path) + { + *path = MontyPath::new(normalized); + } + } + match self { + // Single-path variants — just the path in positionals. + Self::Exists(p) + | Self::IsFile(p) + | Self::IsDir(p) + | Self::IsSymlink(p) + | Self::ReadText(p) + | Self::ReadBytes(p) + | Self::Stat(p) + | Self::Iterdir(p) + | Self::Resolve(p) + | Self::Absolute(p) + | Self::Unlink(p) + | Self::Rmdir(p) => single_arg(p), + // Multi-field variants delegate to their derived `ToArgs`. + Self::WriteText(a) | Self::AppendText(a) => a.to_args(), + Self::WriteBytes(a) | Self::AppendBytes(a) => a.to_args(), + Self::Open(a) => a.to_args(), + Self::Mkdir(a) => a.to_args(), + Self::Rename(a) => a.to_args(), + Self::Scan(a) => a.to_args(), + Self::Getenv(a) => a.to_args(), + Self::Urandom(a) => a.to_args(), + // Unit & single-value non-FS variants. + Self::GetEnviron | Self::DateToday => CallArgs::new(), + Self::Time(caller) => single_arg(caller), + Self::DateTimeNow(tz) => single_arg(tz.map_or(MontyNode::None, MontyNode::TimeZone)), + Self::Sleep(delay) | Self::SystemSleep(delay) | Self::AsyncSleep(delay) | Self::AsyncSystemSleep(delay) => { + single_arg(MontyNode::Float(delay.as_secs_f64())) + } + Self::Import(name) => single_arg(MontyObject::string(name)), + Self::ImportStubs(names) => single_arg(MontyObject::list(names.into_iter().map(MontyObject::string))), + } + } + + /// Whether this call mutates filesystem state — the read-only-mount gate. + /// `Open`'s write-ness is mode-dependent (`w`/`w+`/`a`/`a+` write; `r`/`r+` + /// don't). + #[must_use] + pub fn is_write(&self) -> bool { + match self { + Self::WriteText(_) + | Self::WriteBytes(_) + | Self::AppendText(_) + | Self::AppendBytes(_) + | Self::Mkdir(_) + | Self::Unlink(_) + | Self::Rmdir(_) + | Self::Rename(_) => true, + Self::Open(args) => args.mode.create(), + _ => false, + } + } + + /// Whether this operation checks existence without reading content. + /// Existence checks return `false` for nonexistent paths rather than + /// raising `FileNotFoundError`, matching CPython's `pathlib.Path`. + #[must_use] + pub fn is_existence_check(&self) -> bool { + matches!( + self, + Self::Exists(_) | Self::IsFile(_) | Self::IsDir(_) | Self::IsSymlink(_) + ) + } + + /// Checks both raw filesystem paths before normalization can hide a NUL byte. + /// Returns the operation-specific `ValueError` message; existence predicates + /// should return `False` instead of raising it. + pub fn check_path_null_bytes(&self) -> Result<(), &'static str> { + if self.fs_primary_path().is_some_and(|path| path.contains('\0')) { + Err(self.embedded_null_message(false)) + } else if self.rename_destination().is_some_and(|path| path.contains('\0')) { + Err(self.embedded_null_message(true)) + } else { + Ok(()) + } + } + + /// CPython's `ValueError` message for a path containing a null byte. + /// + /// The wording is not uniform in CPython: it comes from whichever layer + /// first inspects the path, so the content operations go through `open()` + /// and say `embedded null byte`, while the metadata ones are named by the + /// syscall their `os` wrapper was about to make. `for_destination` picks + /// the rename argument that carried the byte. + #[must_use] + pub fn embedded_null_message(&self, for_destination: bool) -> &'static str { + match self { + Self::Mkdir(_) => "mkdir: embedded null character in path", + Self::Unlink(_) => "unlink: embedded null character in path", + Self::Rmdir(_) => "rmdir: embedded null character in path", + Self::Stat(_) => "stat: embedded null character in path", + // `pathlib.Path.iterdir` reaches `os.scandir`, not `os.listdir`. + Self::Iterdir(_) | Self::Scan(_) => "scandir: embedded null character in path", + Self::Rename(_) if for_destination => "rename: embedded null character in dst", + Self::Rename(_) => "rename: embedded null character in src", + // `resolve()` lstats each component before returning. + Self::Resolve(_) => "lstat: embedded null character in path", + // Reads, writes, appends and `open` all land in `io.open`. + // `absolute()` shares that generic wording: it is pure string work + // that CPython never raises from, so naming a syscall would be a + // fiction (see `limitations/filesystem.md`). The predicates never + // reach here — they answer `False`. + _ => "embedded null byte", + } + } + + /// The call's primary path if it's a FS operation, `None` otherwise. + /// + /// Used for routing and error reporting. + #[must_use] + pub fn fs_primary_path(&self) -> Option<&str> { + match self { + Self::Exists(p) + | Self::IsFile(p) + | Self::IsDir(p) + | Self::IsSymlink(p) + | Self::ReadText(p) + | Self::ReadBytes(p) + | Self::Stat(p) + | Self::Iterdir(p) + | Self::Resolve(p) + | Self::Absolute(p) + | Self::Unlink(p) + | Self::Rmdir(p) => Some(p.as_str()), + Self::WriteText(a) | Self::AppendText(a) => Some(a.path.as_str()), + Self::WriteBytes(a) | Self::AppendBytes(a) => Some(a.path.as_str()), + Self::Open(a) => Some(a.path.as_str()), + Self::Mkdir(a) => Some(a.path.as_str()), + Self::Scan(a) => Some(a.path.as_str()), + Self::Rename(a) => Some(a.src.as_str()), + Self::Getenv(_) + | Self::GetEnviron + | Self::DateToday + | Self::DateTimeNow(_) + | Self::Urandom(_) + | Self::Time(_) + | Self::Sleep(_) + | Self::SystemSleep(_) + | Self::AsyncSleep(_) + | Self::AsyncSystemSleep(_) + | Self::Import(_) + | Self::ImportStubs(_) => None, + } + } + + /// The rename destination path, or `None` for every other variant — the + /// second routing key a mount table needs (both rename endpoints must + /// resolve to the same mount). + #[must_use] + pub fn rename_destination(&self) -> Option<&str> { + match self { + Self::Rename(a) => Some(a.dst.as_str()), + _ => None, + } + } + + /// Every path this call carries, mutably: the primary path plus the + /// rename destination. The interpreter resolves relative paths against + /// the sandbox working directory here before the call reaches the host, + /// so host backends only ever see absolute virtual paths. + pub fn fs_paths_mut(&mut self) -> impl Iterator { + let (primary, dst) = match self { + Self::Exists(p) + | Self::IsFile(p) + | Self::IsDir(p) + | Self::IsSymlink(p) + | Self::ReadText(p) + | Self::ReadBytes(p) + | Self::Stat(p) + | Self::Iterdir(p) + | Self::Resolve(p) + | Self::Absolute(p) + | Self::Unlink(p) + | Self::Rmdir(p) => (Some(p), None), + Self::WriteText(a) | Self::AppendText(a) => (Some(&mut a.path), None), + Self::WriteBytes(a) | Self::AppendBytes(a) => (Some(&mut a.path), None), + Self::Open(a) => (Some(&mut a.path), None), + Self::Mkdir(a) => (Some(&mut a.path), None), + Self::Scan(a) => (Some(&mut a.path), None), + Self::Rename(a) => (Some(&mut a.src), Some(&mut a.dst)), + Self::Getenv(_) + | Self::GetEnviron + | Self::DateToday + | Self::DateTimeNow(_) + | Self::Urandom(_) + | Self::Time(_) + | Self::Sleep(_) + | Self::SystemSleep(_) + | Self::AsyncSleep(_) + | Self::AsyncSystemSleep(_) + | Self::Import(_) + | Self::ImportStubs(_) => (None, None), + }; + primary.into_iter().chain(dst) + } + + /// Exception to raise when no handler accepted this call: `PermissionError` + /// for FS ops (with the path), `ModuleNotFoundError` for an import, + /// `RuntimeError` for the other non-FS ops. + #[must_use] + pub fn on_no_handler(&self) -> MontyException { + if let Self::Import(name) = self { + MontyException::new( + ExcType::ModuleNotFoundError, + Some(format!("No module named {}", StringRepr(name))), + ) + } else if let Some(path) = self.fs_primary_path() { + let path = if path.is_empty() { + Cow::Borrowed(path) + } else { + normalize_virtual_path(path) + }; + MontyException::new( + ExcType::PermissionError, + Some(format!("Permission denied: {}", StringRepr(&path))), + ) + } else { + MontyException::new( + ExcType::RuntimeError, + Some(format!("'{}' is not supported in this environment", self.name())), + ) + } + } +} + +impl fmt::Display for OsFunctionCall { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// Which `time` function is reading the clock in an [`OsFunctionCall::Time`]. +/// +/// All share the `time.time` call name since all want the current instant as epoch +/// seconds; the caller, passed as the call's single positional argument spelled as +/// the Python function (`"time.perf_counter"`), lets a host that cares answer them +/// differently (say a virtual clock advancing only for `time.monotonic`). +#[derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::EnumIter, + strum::EnumString, + strum::IntoStaticStr, +)] +pub enum TimeCaller { + /// `time.time()`. + #[strum(serialize = "time.time")] + Time, + /// `time.time_ns()`. + #[strum(serialize = "time.time_ns")] + TimeNs, + /// `time.monotonic()`. + #[strum(serialize = "time.monotonic")] + Monotonic, + /// `time.monotonic_ns()`. + #[strum(serialize = "time.monotonic_ns")] + MonotonicNs, + /// `time.perf_counter()`. + #[strum(serialize = "time.perf_counter")] + PerfCounter, + /// `time.perf_counter_ns()`. + #[strum(serialize = "time.perf_counter_ns")] + PerfCounterNs, + /// `time.gmtime()` with no argument. + #[strum(serialize = "time.gmtime")] + Gmtime, + /// `time.localtime()` with no argument. + #[strum(serialize = "time.localtime")] + Localtime, + /// `time.asctime()` with no argument. + #[strum(serialize = "time.asctime")] + Asctime, + /// `time.ctime()` with no argument. + #[strum(serialize = "time.ctime")] + Ctime, + /// `time.strftime(format)` with no time argument. + #[strum(serialize = "time.strftime")] + Strftime, +} + +impl TimeCaller { + /// The Python function's name, as the host receives it. + #[must_use] + pub fn as_str(self) -> &'static str { + self.into() + } +} + +impl fmt::Display for TimeCaller { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// A call with one positional argument. +fn single_arg(value: impl PushValue) -> CallArgs { + let mut call = CallArgs::new(); + unstable::push_arg(&mut call, value); + call +} + +// ============================================================================= +// Args structs — per-variant payloads carried by `OsFunctionCall`. +// ============================================================================= +// +// Each variant carries a struct that derives `ToArgs` for projection to +// `CallArgs`. Zero-arg variants use empty structs so `to_args()` has no +// special arms. Producers construct these directly via struct literals (see +// `types/path.rs`, `builtins/open.rs`, etc.). + +/// `path + str data` shape used by `WriteText` and `AppendText`. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, monty_macros::ToArgs)] +pub struct PathStringDataArgs { + pub path: MontyPath, + pub data: String, +} + +/// `path + bytes data` shape used by `WriteBytes` and `AppendBytes`. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, monty_macros::ToArgs)] +pub struct PathBytesDataArgs { + pub path: MontyPath, + #[serde(with = "serde_bytes")] + pub data: Vec, +} + +/// Arguments to `open()`: a virtual path and a parsed file mode. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, monty_macros::ToArgs)] +pub struct OpenCallArgs { + pub path: MontyPath, + pub mode: FileMode, +} + +/// `mkdir(path, parents=False, exist_ok=False)` shape. `parents`/`exist_ok` +/// are kw-only so [`ToArgs`](crate::args::ToArgs) emits them as kwargs (matching CPython). +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, monty_macros::ToArgs)] +pub struct MkdirCallArgs { + pub path: MontyPath, + #[from_args(kw_only)] + pub parents: bool, + #[from_args(kw_only)] + pub exist_ok: bool, +} + +/// `rename(src, dst)` shape. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, monty_macros::ToArgs)] +pub struct RenameCallArgs { + pub src: MontyPath, + pub dst: MontyPath, +} + +/// `os.getenv(key, default=None)` shape. The host decides whether to +/// substitute `default` when the variable is unset. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, monty_macros::ToArgs)] +pub struct GetenvArgs { + pub key: String, + pub default: MontyObject, +} + +/// `os.urandom(size)` shape. The interpreter rejects a negative `size` before +/// suspending, so the count is unsigned; the host answers with exactly `size` +/// bytes. `size` is sandbox-controlled, so a handler should cap it before allocating. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, monty_macros::ToArgs)] +pub struct UrandomArgs { + pub size: u64, +} + +/// Longest sleep the sleep calls accept, matching the point where CPython's +/// `PyTime_t` (nanoseconds in an `i64`) overflows. +pub const MAX_SLEEP_SECONDS: f64 = 9_223_372_036.854_775; + +/// Why a requested sleep length cannot be carried by an OS call. +/// +/// The caller picks the Python-level consequence: `time.sleep` raises +/// (`ValueError` for the first two, `OverflowError` for the third) while +/// `asyncio.sleep` raises only for NaN and clamps the rest, as CPython does. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SleepError { + /// The delay was NaN. + NotANumber, + /// The delay was negative. + Negative, + /// The delay was past [`MAX_SLEEP_SECONDS`] (infinity included). + TooLarge, +} + +/// Converts a Python sleep argument into the [`Duration`] an OS call carries. +/// +/// Sleep payloads are `Duration` rather than raw seconds precisely so no host +/// is ever handed a NaN, negative or unrepresentable span to convert — the +/// obvious `Duration::from_secs_f64` panics on all three. Both producers, the +/// interpreter and the wire decoder, go through here. +pub fn sleep_duration(seconds: f64) -> Result { + // Range before sign, as CPython converts to `PyTime_t` before checking + // the sign: `-inf` and huge negatives overflow rather than being negative. + if seconds.is_nan() { + Err(SleepError::NotANumber) + } else if seconds.abs() > MAX_SLEEP_SECONDS { + Err(SleepError::TooLarge) + } else if seconds < 0.0 { + Err(SleepError::Negative) + } else { + Duration::try_from_secs_f64(seconds).map_err(|_| SleepError::TooLarge) + } +} + +/// Like [`sleep_duration`], but for `asyncio.sleep`, which clamps rather than +/// raising: a negative delay becomes no wait at all (CPython returns +/// immediately) and an over-long one saturates at [`MAX_SLEEP_SECONDS`]. Only +/// NaN is refused, the one delay CPython rejects there. +pub fn sleep_duration_saturating(seconds: f64) -> Result { + match sleep_duration(seconds) { + Ok(delay) => Ok(delay), + // `delay <= 0` returns at once in CPython, however far below zero. + Err(SleepError::Negative) => Ok(Duration::ZERO), + Err(SleepError::TooLarge) if seconds < 0.0 => Ok(Duration::ZERO), + Err(SleepError::TooLarge) => Ok(Duration::from_secs_f64(MAX_SLEEP_SECONDS)), + Err(err @ SleepError::NotANumber) => Err(err), + } +} + +// ============================================================================= +// MontyPath — owned virtual-sandbox path used by every path-bearing variant. +// ============================================================================= + +/// Owned virtual (sandbox) path carried by OS-call args. +/// +/// Preserves the supplied string, including invalid components, for host validation. +/// Derefs to `&str` for routing. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct MontyPath(String); + +impl MontyPath { + /// Stores the path without validation or normalization; hosts validate before I/O. + #[must_use] + pub fn new(path: String) -> Self { + Self(path) + } + + /// Borrows the original spelling for host validation and error messages. + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } + + /// Takes the original string without copying it. + #[must_use] + pub fn into_string(self) -> String { + self.0 + } +} + +impl Deref for MontyPath { + type Target = str; + + fn deref(&self) -> &str { + &self.0 + } +} + +impl From for MontyPath { + fn from(s: String) -> Self { + Self(s) + } +} + +impl From<&str> for MontyPath { + fn from(s: &str) -> Self { + Self(s.to_owned()) + } +} + +impl PushValue for MontyPath { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + graph.push(MontyNode::Path(self.0)) + } +} +// ============================================================================= +// stat_result builders — separate utility API used by host backends. +// ============================================================================= +// +// These functions create namedtuple values that match Python's +// os.stat_result structure. The stat_result has 10 fields: +// st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime. + +/// Creates a `stat_result` for a regular file. +/// +/// The file type bits (`0o100_000`) are automatically added if not present. +/// +/// # Arguments +/// * `mode` - File permissions as octal. Common values: +/// - `0o644` - rw-r--r-- (owner read/write, others read) +/// - `0o600` - rw------- (owner read/write only) +/// - `0o755` - rwxr-xr-x (executable, owner full, others read/execute) +/// - `0o100644` - same as 0o644 with explicit file type bits +/// * `size` - File size in bytes +/// * `mtime` - Modification time as Unix timestamp +#[must_use] +pub fn file_stat(mode: i64, size: i64, mtime: f64) -> MontyObject { + let mode = if mode < 0o1000 { mode | 0o100_000 } else { mode }; + stat_result(mode, 0, 0, 1, 0, 0, size, mtime, mtime, mtime) +} + +/// Creates a `stat_result` for a directory. +/// +/// The directory type bits (`0o040_000`) are automatically added if not present. +/// +/// # Arguments +/// * `mode` - Directory permissions as octal. Common values: +/// - `0o755` - rwxr-xr-x (owner full, others read/execute) +/// - `0o700` - rwx------ (owner only) +/// - `0o040755` - same as 0o755 with explicit directory type bits +/// * `mtime` - Modification time as Unix timestamp +#[must_use] +pub fn dir_stat(mode: i64, mtime: f64) -> MontyObject { + let mode = if mode < 0o1000 { mode | 0o040_000 } else { mode }; + stat_result(mode, 0, 0, 2, 0, 0, 4096, mtime, mtime, mtime) +} + +/// Creates a `stat_result` for a symbolic link. +/// +/// The symlink type bits (`0o120_000`) are automatically added if not present. +/// +/// # Arguments +/// * `mode` - Symlink permissions as octal. Common values: +/// - `0o777` - rwxrwxrwx (symlinks typically have full permissions) +/// - `0o120777` - same as 0o777 with explicit symlink type bits +/// * `mtime` - Modification time as Unix timestamp +#[must_use] +pub fn symlink_stat(mode: i64, mtime: f64) -> MontyObject { + let mode = if mode < 0o1000 { mode | 0o120_000 } else { mode }; + stat_result(mode, 0, 0, 1, 0, 0, 0, mtime, mtime, mtime) +} + +/// Creates a full `stat_result` with all 10 fields specified. +/// +/// This is the low-level builder; prefer `file_stat()`, `dir_stat()`, or `symlink_stat()` +/// for common cases. +#[must_use] +#[expect(clippy::too_many_arguments)] +pub fn stat_result( + st_mode: i64, + st_ino: i64, + st_dev: i64, + st_nlink: i64, + st_uid: i64, + st_gid: i64, + st_size: i64, + st_atime: f64, + st_mtime: f64, + st_ctime: f64, +) -> MontyObject { + MontyObject::named_tuple( + STAT_RESULT_TYPE_NAME, + STAT_RESULT_FIELDS.iter().copied(), + [ + MontyObject::int(st_mode), + MontyObject::int(st_ino), + MontyObject::int(st_dev), + MontyObject::int(st_nlink), + MontyObject::int(st_uid), + MontyObject::int(st_gid), + MontyObject::int(st_size), + MontyObject::float(st_atime), + MontyObject::float(st_mtime), + MontyObject::float(st_ctime), + ], + ) +} + +const STAT_RESULT_TYPE_NAME: &str = "StatResult"; +const STAT_RESULT_FIELDS: &[&str] = &[ + "st_mode", "st_ino", "st_dev", "st_nlink", "st_uid", "st_gid", "st_size", "st_atime", "st_mtime", "st_ctime", +]; diff --git a/crates/bashkit-monty-types/src/os_policy.rs b/crates/bashkit-monty-types/src/os_policy.rs new file mode 100644 index 000000000..613d6c8a4 --- /dev/null +++ b/crates/bashkit-monty-types/src/os_policy.rs @@ -0,0 +1,374 @@ +//! Session policies for clocks, sleeps and initial random state. + +use std::{error::Error, fmt, time::Duration}; + +use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, TimeDelta, Timelike, Utc}; +use jiff::{ + Timestamp, civil, + tz::{AmbiguousOffset, TimeZone}, +}; +use num_bigint::BigInt; + +use crate::object::MontyTimeZone; + +/// Policies for clocks, sleeps and initial random state on every execution path. +/// `CallHost` suspends to the host, or raises `NotImplementedError` without one; +/// the zone is always resolved in the sandbox. +/// Defaults use the system clock, the UTC zone, OS entropy, a zero process clock, +/// and sleeps capped at ten seconds. Hosts perform those sleeps without their +/// `os` handler; standard execution waits inline. +#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)] +pub struct OsPolicy { + /// The instant `date.today()`, `datetime.now()` and `time.time()` read. + pub datetime: DateTimeSource, + /// The local zone: naive `datetime.now()` and `date.today()` read it, + /// `astimezone()`, `time.timezone`/`tzname` and `%Z` report it. + pub timezone: SandboxTimeZone, + /// What `time.sleep()` and `asyncio.sleep()` do. + pub sleep: SleepMode, + /// What `time.process_time()` and `time.thread_time()` report. + pub process_time: ProcessTime, + /// Where an unseeded `random` generator gets its first state. + pub random_start: RandomStart, +} + +/// Where the clock calls read the instant. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +pub enum DateTimeSource { + /// The process's own clock. + #[default] + System, + /// Suspend to the host, which answers each call. + CallHost, + /// Every call reads this instant. Years outside 1..=9999 raise `OverflowError`. + Fixed { + /// Seconds since the Unix epoch, UTC. + unix_seconds: i64, + /// Sub-second component, 0..=999_999. Anything larger raises. + microsecond: u32, + }, +} + +impl DateTimeSource { + /// Reads the instant in UTC. Returns `None` for [`CallHost`](Self::CallHost) + /// or a [`Fixed`](Self::Fixed) instant Python's `datetime` cannot represent. + #[must_use] + pub fn read(self) -> Option { + let utc = match self { + Self::System => Utc::now().naive_utc(), + Self::CallHost => return None, + Self::Fixed { + unix_seconds, + microsecond, + } => { + // Chrono accepts leap seconds; Python requires microseconds below 1_000_000. + let nanoseconds = microsecond.checked_mul(1_000).filter(|ns| *ns < 1_000_000_000)?; + DateTime::from_timestamp(unix_seconds, nanoseconds)?.naive_utc() + } + }; + // Apply datetime's year range to time.time() too. + local_wall_clock(utc, 0).map(|_| utc) + } +} + +/// The sandbox's local zone, UTC unless configured. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum SandboxTimeZone { + /// A fixed offset from UTC, with the name `datetime.timezone(offset, name)` + /// would carry. No DST: every instant has the same offset and name. + Fixed { + /// Offset from UTC, in seconds. + offset_seconds: i32, + /// The zone's name, if it has one. + name: Option, + }, + /// An IANA zone with its transition rules, built only by [`named`](Self::named). + /// Serialises as its name, so each side of the wire resolves it against its + /// own database. + Named(NamedZone), +} + +impl Default for SandboxTimeZone { + fn default() -> Self { + Self::utc() + } +} + +impl SandboxTimeZone { + /// UTC named `UTC`, as CPython reports the zone under `TZ=UTC`. + #[must_use] + pub fn utc() -> Self { + Self::Fixed { + offset_seconds: 0, + name: Some("UTC".to_owned()), + } + } + + /// Resolves an IANA zone name such as `Europe/London` against the tz database + /// the `tzdb` or `tzdb-bundled` feature provides. Without either, or for a + /// name the database lacks, returns [`UnknownTimeZone`]. + pub fn named(name: &str) -> Result { + NamedZone::resolve(name).map(Self::Named) + } + + /// The IANA name of a [`Named`](Self::Named) zone; `None` for a fixed offset. + #[must_use] + pub fn iana_name(&self) -> Option<&str> { + match self { + Self::Fixed { .. } => None, + Self::Named(zone) => Some(zone.name()), + } + } + + /// The offset and name in force at the UTC instant `utc`: the `timezone` + /// that `astimezone()` attaches and `%Z` prints. A fixed zone's name is + /// `None` when it was not given one. + #[must_use] + pub fn at(&self, utc: NaiveDateTime) -> MontyTimeZone { + match self { + Self::Fixed { offset_seconds, name } => MontyTimeZone { + offset_seconds: *offset_seconds, + name: name.clone(), + }, + Self::Named(zone) => { + let info = zone.zone.to_offset_info(timestamp(utc)); + MontyTimeZone { + offset_seconds: info.offset().seconds(), + name: Some(info.abbreviation().to_owned()), + } + } + } + } + + /// The offset in force for a naive wall-clock time in this zone. An ambiguous + /// time (a DST fold) takes its first occurrence and a skipped time (a gap) the + /// offset from before it, CPython's `fold=0` reading. `None` only outside the + /// civil year range, which is wider than `datetime`'s. + #[must_use] + pub fn offset_for_local(&self, local: NaiveDateTime) -> Option { + match self { + Self::Fixed { offset_seconds, .. } => Some(*offset_seconds), + // The offset rather than the instant: jiff's timestamps stop short of the + // last day a `datetime` holds, and `timestamp()` reaches past it anyway. + Self::Named(zone) => match zone.zone.to_ambiguous_timestamp(civil_datetime(local)?).offset() { + AmbiguousOffset::Unambiguous { offset } + | AmbiguousOffset::Gap { before: offset, .. } + | AmbiguousOffset::Fold { before: offset, .. } => Some(offset.seconds()), + }, + } + } + + /// The UTC instant a naive wall-clock time in this zone denotes, or `None` + /// outside years 1..=9999. + #[must_use] + pub fn utc_from_local(&self, local: NaiveDateTime) -> Option { + local_wall_clock(local, self.offset_for_local(local)?.checked_neg()?) + } + + /// The `time` module's `timezone`, `altzone`, `daylight` and `tzname`, read + /// as CPython does from the zone's state on 1 January and 1 July of `year`. + /// A fixed zone ignores `year`; a named one needs it, so `None` gives `None`. + #[must_use] + pub fn constants(&self, year: Option) -> Option { + let (january, july) = match self { + Self::Fixed { .. } => { + let zone = self.at(DateTime::UNIX_EPOCH.naive_utc()); + (zone.clone(), zone) + } + Self::Named(_) => { + let year = year?; + let at = |month| Some(self.at(NaiveDate::from_ymd_opt(year, month, 1)?.and_time(NaiveTime::MIN))); + (at(1)?, at(7)?) + } + }; + // `time.timezone` is seconds *west* of UTC; standard time is the one + // further west, which swaps the halves in the southern hemisphere. + let (standard, daylight) = if january.offset_seconds < july.offset_seconds { + (january, july) + } else { + (july, january) + }; + Some(ZoneConstants { + daylight: standard.offset_seconds != daylight.offset_seconds, + standard, + daylight_zone: daylight, + }) + } +} + +/// A zone resolved from the tz database by [`SandboxTimeZone::named`], which is +/// the only way to build one: every value carries the database's name for it. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct NamedZone { + name: String, + zone: TimeZone, +} + +impl NamedZone { + /// The zone's IANA name as the database spells it. + #[must_use] + pub fn name(&self) -> &str { + &self.name + } + + fn resolve(name: &str) -> Result { + // The chars IANA keys use, with no `.`/`..` components, so nothing + // traversal-shaped reaches the database's path lookup. + let valid_part = |part: &str| { + !matches!(part, "" | "." | "..") && part.bytes().all(|b| b.is_ascii_alphanumeric() || b"._+-".contains(&b)) + }; + let unknown = || UnknownTimeZone(name.to_owned()); + if name.len() > 100 || !name.split('/').all(valid_part) { + return Err(unknown()); + } + let zone = TimeZone::get(name).map_err(|_| unknown())?; + // `Etc/Unknown` resolves to jiff's nameless placeholder zone. + let name = zone.iana_name().ok_or_else(unknown)?.to_owned(); + Ok(Self { name, zone }) + } +} + +impl TryFrom for NamedZone { + type Error = UnknownTimeZone; + + fn try_from(name: String) -> Result { + Self::resolve(&name) + } +} + +impl From for String { + fn from(zone: NamedZone) -> Self { + zone.name + } +} + +/// A zone name [`SandboxTimeZone::named`] could not resolve: malformed, or +/// absent from the tz database available to this build. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UnknownTimeZone(pub String); + +impl fmt::Display for UnknownTimeZone { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "unknown timezone '{}'", self.0) + } +} + +impl Error for UnknownTimeZone {} + +/// The zone's standard and daylight halves as the `time` module reports them. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ZoneConstants { + /// Standard time: `-offset_seconds` is `time.timezone`, `name` is `tzname[0]`. + pub standard: MontyTimeZone, + /// Daylight time, equal to `standard` when the zone has none: `time.altzone`, `tzname[1]`. + pub daylight_zone: MontyTimeZone, + /// `time.daylight`: whether the two halves differ. + pub daylight: bool, +} + +/// `utc` as a jiff instant, clamped to jiff's range: its timestamps end about a +/// day before `datetime`'s do, so that every offset still renders as a civil +/// datetime. No zone changes offset on 31 December, so the clamp reports the +/// same offset and name the instant itself would. +fn timestamp(utc: NaiveDateTime) -> Timestamp { + let utc = utc.and_utc(); + let seconds = utc.timestamp(); + let nanoseconds = i32::try_from(utc.timestamp_subsec_nanos()).unwrap_or(0); + Timestamp::new(seconds, nanoseconds).unwrap_or(if seconds < 0 { Timestamp::MIN } else { Timestamp::MAX }) +} + +/// `local` as a jiff civil datetime, `None` outside jiff's year range. +fn civil_datetime(local: NaiveDateTime) -> Option { + civil::DateTime::new( + i16::try_from(local.year()).ok()?, + i8::try_from(local.month()).ok()?, + i8::try_from(local.day()).ok()?, + i8::try_from(local.hour()).ok()?, + i8::try_from(local.minute()).ok()?, + i8::try_from(local.second()).ok()?, + i32::try_from(local.nanosecond()).ok()?, + ) + .ok() +} + +/// The wall clock `offset_seconds` from UTC at `utc`, or `None` outside the +/// 1..=9999 years Python's `datetime` can hold. +#[must_use] +pub fn local_wall_clock(utc: NaiveDateTime, offset_seconds: i32) -> Option { + let shifted = utc.checked_add_signed(TimeDelta::seconds(i64::from(offset_seconds)))?; + (1..=9999).contains(&shifted.year()).then_some(shifted) +} + +/// The instant as `time.time()` reports it: seconds since the Unix epoch. +#[must_use] +pub fn unix_seconds(utc: NaiveDateTime) -> f64 { + let epoch = utc.and_utc(); + epoch.timestamp() as f64 + f64::from(epoch.timestamp_subsec_micros()) / 1_000_000.0 +} + +/// What the sleep calls do. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum SleepMode { + /// Cap each delay at this duration, then suspend to the host to wait without + /// its `os` handler. The host charges `ResourceLimits::max_total_sleep` before + /// waiting; waits do not count as execution time. Standard execution waits + /// inline without a cumulative limit. Longer delays are capped, not rejected. + System(Duration), + /// Delegate to the host's `os` handler without capping or charging the delay. + CallHost, + /// Return at once without waiting. + Zero, +} + +impl SleepMode { + /// Default per-call cap for [`System`](Self::System). + pub const DEFAULT_MAX: Duration = Duration::from_secs(10); +} + +impl Default for SleepMode { + fn default() -> Self { + Self::System(Self::DEFAULT_MAX) + } +} + +/// What `time.process_time()` and `time.thread_time()` report. +/// +/// Separate from [`DateTimeSource`] because these clocks exclude sleeps and +/// time suspended on the host, which no wall clock can express. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +pub enum ProcessTime { + /// Always zero, so a [`DateTimeSource::Fixed`] session stays blind to time passing. + #[default] + Zero, + /// The session's accumulated execution time, as `ResourceTracker::elapsed` + /// measures it. Wall time while running, not CPU time. + Elapsed, +} + +/// Where an unseeded `random` generator gets its first state. +#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)] +pub enum RandomStart { + /// From the sandbox's own OS entropy. + #[default] + System, + /// Request one state vector (2496 bytes) from the host via `os.urandom` on the first draw. + CallHost, + /// The module-level generator starts exactly as `random.seed(seed)` leaves + /// it; unseeded `random.Random()` instances take deterministic states + /// derived from the same seed. + Seed(RandomSeed), +} + +/// Explicit seeds for [`RandomStart::Seed`], using CPython's `random.seed()` semantics. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub enum RandomSeed { + /// Any size; CPython seeds from the absolute value. + Int(BigInt), + /// Seeded from the float's CPython `hash()`. + Float(f64), + /// Seeded from the SHA-512-extended text, as `seed(str)` does. + Str(String), + /// Seeded from the SHA-512-extended bytes, as `seed(bytes)` does. + Bytes(#[serde(with = "serde_bytes")] Vec), +} diff --git a/crates/bashkit-monty-types/src/resource.rs b/crates/bashkit-monty-types/src/resource.rs new file mode 100644 index 000000000..43cda59af --- /dev/null +++ b/crates/bashkit-monty-types/src/resource.rs @@ -0,0 +1,828 @@ +//! Resource limits: the [`ResourceTracker`] used by the interpreter heap/VM +//! and its [`ResourceLimits`] configuration. + +#[cfg(target_arch = "wasm32")] +use std::hint; +#[cfg(not(target_arch = "wasm32"))] +use std::thread; +#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] +use std::time::Instant; +use std::{ + cell::Cell, + error::Error, + fmt, + sync::{ + OnceLock, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; + +// `std::time::Instant::now()` panics ("time not implemented on this platform") +// on `wasm32-unknown-unknown`, so any duration limit aborts there. Swap in +// `web_time::Instant` (a `performance.now()`-backed drop-in) only for that +// target; every other target (native, WASI) keeps std, so the `web-time` +// dependency is pulled in only where it's needed (see Cargo.toml). +#[cfg(all(target_arch = "wasm32", target_os = "unknown"))] +use web_time::Instant; + +/// Exit code a worker uses when it exceeded its memory limit or the allocator +/// refused an allocation, so the parent can report `MemoryError` instead of an +/// unclassifiable `SIGABRT`. +/// +/// `EX_DATAERR` from BSD `sysexits.h`. See . +pub const OOM_EXIT_CODE: i32 = 65; +/// Allocator-backed live bytes requested through the global allocator +pub static LIVE_MEMORY: AtomicUsize = AtomicUsize::new(0); +/// What the worker costs to exist: the leanest the process has ever been at an +/// arming point, plus structures it keeps for life (see [`allocate_into_baseline`]). +pub static BASELINE_MEMORY: AtomicUsize = AtomicUsize::new(usize::MAX); + +// bashkit fork: host memory probe + checkpoint hook (pydantic/monty#740). +static MEMORY_PROBE: OnceLock usize> = OnceLock::new(); +static CHECKPOINT_HOOK: OnceLock Result<(), ResourceError>> = OnceLock::new(); + +/// Replaces the default `LIVE_MEMORY` minus `BASELINE_MEMORY` read behind the +/// tracker's memory checks (pydantic/monty#740), so an in-process host with +/// several concurrent interpreters can give each run its own numbers. +/// Install once; a later install is refused and the first probe stays. +pub fn set_memory_probe(probe: fn() -> usize) -> Result<(), &'static str> { + MEMORY_PROBE.set(probe).map_err(|_| "memory probe already installed") +} + +/// Installs a host callback run at every time checkpoint inside the VM, before +/// the tracker's own time budgets. An `Err` stops the run uncatchably, so a +/// host can enforce cancellation or a shared work budget mid-loop. +/// Install once; a later install is refused and the first hook stays. +pub fn set_checkpoint_hook(hook: fn() -> Result<(), ResourceError>) -> Result<(), &'static str> { + CHECKPOINT_HOOK.set(hook).map_err(|_| "checkpoint hook already installed") +} + +/// Runs `build` and adds what it leaves allocated to [`BASELINE_MEMORY`], so a +/// structure the worker keeps for life (such as typeshed) is not charged to the +/// session that happened to build it first. +/// +/// Only accurate while no other thread changes [`LIVE_MEMORY`]. An unset baseline is +/// left alone: the first arming counts the structure anyway. +pub fn allocate_into_baseline(build: impl FnOnce() -> T) -> T { + let before = LIVE_MEMORY.load(Ordering::Relaxed); + let value = build(); + let cost = LIVE_MEMORY.load(Ordering::Relaxed).saturating_sub(before); + // `Err` just means the baseline is still unset + let _ = BASELINE_MEMORY.try_update(Ordering::Relaxed, Ordering::Relaxed, |baseline| { + (baseline != usize::MAX).then(|| baseline.saturating_add(cost)) + }); + value +} + +/// Headroom for exception machinery and work between interpreter checkpoints. +const MEMORY_LIMIT_HEADROOM: usize = 4 * 1024 * 1024; +/// Extra headroom for type-checker stubs and caches outside Python execution. +const TYPE_CHECK_MEMORY_LIMIT_HEADROOM: usize = 32 * 1024 * 1024; + +/// Converts an interpreter soft memory limit into a worker allocator budget. +/// +/// The returned budget includes operational headroom but remains relative to +/// the worker baseline, which `monty-alloc` adds when arming its hard ceiling. +#[must_use] +pub fn memory_limit_with_headroom(max_memory: Option, type_check: bool) -> Option { + max_memory.map(|bytes| { + let headroom = if type_check { + TYPE_CHECK_MEMORY_LIMIT_HEADROOM + } else { + MEMORY_LIMIT_HEADROOM + }; + bytes.saturating_add(headroom) + }) +} + +/// Threshold in bytes above which `check_large_result` is called. +/// +/// Operations that may produce results larger than this threshold (100KB) should call +/// `check_large_result` before performing the operation. This prevents DoS attacks +/// where operations like `2 ** 10_000_000` allocate huge amounts of memory before +/// the memory check can catch them. +pub const LARGE_RESULT_THRESHOLD: usize = 100_000; +/// Error returned when a resource limit is exceeded during execution. +/// +/// This allows the sandbox to enforce strict limits on execution time +/// and memory usage. +/// +/// All variants except `Recursion` are **uncatchable** inside the sandbox: +/// untrusted code must never intercept resource enforcement. `Recursion` +/// surfaces as a catchable `RecursionError`, matching CPython. +#[derive(Debug, Clone)] +pub enum ResourceError { + /// One of the two execution-time budgets was exceeded; `scope` says which. + Time { + scope: TimeLimitScope, + limit: Duration, + elapsed: Duration, + }, + /// Maximum memory usage exceeded. + Memory { limit: usize, used: usize }, + /// Maximum recursion depth exceeded. + Recursion { limit: usize, depth: usize }, +} + +/// Which of the two nested execution-time budgets a [`ResourceError::Time`] +/// refers to. +/// +/// Both read the same clock and differ only in when they are reset, so a +/// turn's time is charged to its feed as well: `Feed >= Turn` always holds. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TimeLimitScope { + /// [`ResourceLimits::max_feed_duration`] — reset at each feed. + Feed, + /// [`ResourceLimits::max_turn_duration`] — reset at each feed and each + /// resume. + Turn, +} + +impl TimeLimitScope { + /// The word naming this scope in an error message. + fn prefix(self) -> &'static str { + match self { + Self::Feed => "feed ", + Self::Turn => "turn ", + } + } +} + +impl fmt::Display for ResourceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Time { scope, limit, elapsed } => { + write!(f, "{}time limit exceeded: {elapsed:?} > {limit:?}", scope.prefix()) + } + Self::Memory { limit, used } => { + write!(f, "memory limit exceeded: {used} bytes > {limit} bytes") + } + Self::Recursion { .. } => { + write!(f, "maximum recursion depth exceeded") + } + } + } +} + +impl Error for ResourceError {} + +/// Configuration for resource limits. +/// +/// The time/memory/GC limits are optional — set to `None` to disable — but +/// recursion depth and the suspension budget are always bounded (defaults +/// [`DEFAULT_MAX_RECURSION_DEPTH`] and [`DEFAULT_MAX_SUSPENSIONS`]): unbounded +/// recursion would let sandboxed code overflow the native stack and abort the +/// process, and unbounded suspensions would let it loop on host calls. Use +/// `ResourceLimits::default()` for the recursion-only defaults, or build +/// custom limits with the builder pattern. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ResourceLimits { + /// Maximum execution time for a single feed (`feed_start`, `feed_run` or + /// `call_function`), summed over the turns it takes and excluding time + /// suspended on the host. Bounds one snippet, not the session. + pub max_feed_duration: Option, + /// Maximum execution time for a single host turn, reset at each feed and + /// each resume. Bounds the stretch of sandbox code between two host round + /// trips, so a host can bound its own response time per call. + pub max_turn_duration: Option, + /// Maximum allocator-backed memory in bytes. + /// + /// Requires the executable to install and arm `monty-alloc`. + pub max_memory: Option, + /// Run garbage collection every N GC-tracked allocations; `None` uses [`DEFAULT_GC_INTERVAL`]. + pub gc_interval: Option, + /// Maximum recursion depth (function call stack depth). + pub max_recursion_depth: usize, + /// Maximum suspensions the host may service (default + /// [`DEFAULT_MAX_SUSPENSIONS`]; always bounded, like recursion depth). + /// The interpreter only stores this limit; hosts must enforce it. + pub max_suspensions: usize, + /// Maximum cumulative sleep under `SleepMode::System`, enforced by the host. + /// Sleeps do not count toward execution duration; without this limit, sleeping + /// loops need `max_suspensions` or a host deadline. + pub max_total_sleep: Option, +} + +/// Recommended maximum recursion depth if not otherwise specified. +pub const DEFAULT_MAX_RECURSION_DEPTH: usize = 1000; + +/// GC-tracked allocations between cycle collections when `gc_interval` is `None`. +/// Builds with monty's `memory-model-checks` feature collect on every allocation instead. +pub const DEFAULT_GC_INTERVAL: usize = 100_000; + +/// Maximum suspensions a host services per session if not otherwise +/// specified: a backstop against a sandbox looping on host calls while the +/// execution clock is paused. +pub const DEFAULT_MAX_SUSPENSIONS: usize = 1000; + +/// Creates a new ResourceLimits with all limits disabled, except max recursion +/// depth and max suspensions, which are set to 1000. +impl Default for ResourceLimits { + fn default() -> Self { + Self { + max_feed_duration: None, + max_turn_duration: None, + max_memory: None, + gc_interval: None, + max_recursion_depth: DEFAULT_MAX_RECURSION_DEPTH, + max_suspensions: DEFAULT_MAX_SUSPENSIONS, + max_total_sleep: None, + } + } +} + +impl ResourceLimits { + /// Sets the maximum execution duration for any single feed. + #[must_use] + pub fn max_feed_duration(mut self, limit: Duration) -> Self { + self.max_feed_duration = Some(limit); + self + } + + /// Sets the maximum execution duration for any single host turn. + #[must_use] + pub fn max_turn_duration(mut self, limit: Duration) -> Self { + self.max_turn_duration = Some(limit); + self + } + + /// Sets allocator-backed maximum memory usage in bytes. + /// + /// Requires the executable to install and arm `monty-alloc`; otherwise + /// the limit is silently not enforced. + #[must_use] + pub fn max_memory(mut self, limit: usize) -> Self { + self.max_memory = Some(limit); + self + } + + /// Sets the garbage collection interval (run GC every N GC-tracked allocations). + #[must_use] + pub fn gc_interval(mut self, interval: usize) -> Self { + self.gc_interval = Some(interval); + self + } + + /// Sets the maximum recursion depth (function call stack depth). + #[must_use] + pub fn max_recursion_depth(mut self, limit: usize) -> Self { + self.max_recursion_depth = limit; + self + } + + /// Sets the host-enforced maximum number of suspensions. + #[must_use] + pub fn max_suspensions(mut self, limit: usize) -> Self { + self.max_suspensions = limit; + self + } + + /// Sets the maximum cumulative time hosts wait on system sleeps; each capped delay is charged before the wait. + #[must_use] + pub fn max_total_sleep(mut self, limit: Duration) -> Self { + self.max_total_sleep = Some(limit); + self + } +} + +/// A resource tracker that enforces configurable limits. +/// +/// Checks allocator-backed memory usage and tracks execution time, returning +/// errors when limits are exceeded. It also schedules garbage collection. +/// +/// Uses `Cell` for mutable timing and recursion state behind shared references. +/// +/// The two duration limits share one *execution time* clock: it runs only +/// between the outermost `on_execution_start`/`on_execution_stop` pair, so it +/// is paused while suspended on the host and between REPL feeds. They differ +/// only in when their accumulator resets — at +/// [`on_feed_start`](Self::on_feed_start), at [`on_turn_start`](Self::on_turn_start) +/// — and the feed total is serialized, so a session loaded mid-feed resumes +/// that budget rather than restarting from zero. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct ResourceTracker { + limits: ResourceLimits, + /// Execution time accumulated by completed `on_execution_start`/`stop` + /// windows. Bounds nothing — it is what [`elapsed`](Self::elapsed) reports + /// to hosts for telemetry — but is serialized so a loaded session keeps + /// counting from where it left off. + total_execution_time: Cell, + /// Execution time accumulated since the last [`on_feed_start`](Self::on_feed_start). + /// Serialized like `total_execution_time`: a dump taken mid-feed resumes + /// that feed, so its budget must survive the round trip. + feed_execution_time: Cell, + /// Execution time accumulated since the last [`on_turn_start`](Self::on_turn_start). + /// Not serialized — a dump is taken between turns, and the resume that + /// loads it starts a fresh turn. + #[serde(skip)] + turn_execution_time: Cell, + /// When the current execution window started; `None` while suspended or + /// idle. Never serialized — a snapshot is by definition taken while not + /// executing. + #[serde(skip)] + running_since: Cell>, + /// Optional override applied on top of `limits.max_recursion_depth`. + /// + /// `None` (the default — also the value any pre-`test-hooks` snapshot + /// deserializes to) means "no override, use the configured ceiling". + /// `Some(N)` means "use `N` as the live recursion ceiling instead", and + /// is only ever populated by + /// [`lower_recursion_limit`](Self::lower_recursion_limit) + /// under the `test-hooks` feature — `sys.setrecursionlimit` uses it to + /// tighten the bound from Python code without escaping the + /// host-configured ceiling. `None` means the configured limit applies. + recursion_limit_override: Cell>, +} + +impl Default for ResourceTracker { + fn default() -> Self { + Self::new(ResourceLimits::default()) + } +} + +impl ResourceTracker { + /// Tightens restored limits to the destination policy without resetting execution clocks. + /// A snapshot can retain stricter limits but cannot increase the destination's allowance. + pub fn tighten_limits(&mut self, ceiling: &ResourceLimits) { + self.limits.max_memory = tighter_limit(self.limits.max_memory, ceiling.max_memory); + self.limits.max_feed_duration = tighter_limit(self.limits.max_feed_duration, ceiling.max_feed_duration); + self.limits.max_turn_duration = tighter_limit(self.limits.max_turn_duration, ceiling.max_turn_duration); + self.limits.max_total_sleep = tighter_limit(self.limits.max_total_sleep, ceiling.max_total_sleep); + self.limits.gc_interval = tighter_gc_interval(self.limits.gc_interval, ceiling.gc_interval); + self.limits.max_recursion_depth = self.limits.max_recursion_depth.min(ceiling.max_recursion_depth); + self.limits.max_suspensions = self.limits.max_suspensions.min(ceiling.max_suspensions); + if let Some(limit) = self.recursion_limit_override.get() { + self.recursion_limit_override + .set(Some(limit.min(self.limits.max_recursion_depth))); + } + } + + /// Creates a new ResourceTracker with the given limits. + /// + /// The execution-time clock starts at zero and only runs while the VM + /// executes, so the tracker can be created any amount of time before + /// the first run without consuming a duration budget. A configured + /// `max_memory` requires `monty-alloc` installed as the global allocator + /// and armed via `set_hard_limit(memory_limit_with_headroom(...))`; + /// otherwise it is silently not enforced. + #[must_use] + pub fn new(limits: ResourceLimits) -> Self { + Self { + limits, + total_execution_time: Cell::new(Duration::ZERO), + feed_execution_time: Cell::new(Duration::ZERO), + turn_execution_time: Cell::new(Duration::ZERO), + running_since: Cell::new(None), + recursion_limit_override: Cell::new(None), + } + } + + /// Returns the live recursion ceiling: the override if one is in effect, + /// otherwise the configured `max_recursion_depth`. + #[inline] + fn active_recursion_limit(&self) -> usize { + self.recursion_limit_override + .get() + .unwrap_or(self.limits.max_recursion_depth) + } + + /// Returns the cumulative execution time: bytecode-execution wall time + /// accumulated across runs/feeds, excluding time suspended on the host + /// or idle between feeds. Includes the in-progress window if the VM is + /// currently executing. + /// + /// Nothing is bounded by this — it is reported to the host for telemetry. + /// The budgets are [`feed_elapsed`](Self::feed_elapsed) and + /// [`turn_elapsed`](Self::turn_elapsed). + #[must_use] + pub fn elapsed(&self) -> Duration { + self.total_execution_time.get() + self.running_window() + } + + /// Returns the execution time consumed by the current feed; see + /// [`elapsed`](Self::elapsed), which reports the same clock over the + /// whole session. + #[must_use] + pub fn feed_elapsed(&self) -> Duration { + self.feed_execution_time.get() + self.running_window() + } + + /// Returns the execution time consumed by the current host turn; see + /// [`elapsed`](Self::elapsed), which reports the same clock over the + /// whole session. + #[must_use] + pub fn turn_elapsed(&self) -> Duration { + self.turn_execution_time.get() + self.running_window() + } + + /// The in-progress execution window, or zero when not executing. Read + /// once per check so both budgets are compared against one clock reading + /// rather than two. + #[inline] + fn running_window(&self) -> Duration { + self.running_since.get().map_or(Duration::ZERO, |t| t.elapsed()) + } + + /// Returns the configured per-feed execution time limit, if any. + #[must_use] + pub fn max_feed_duration(&self) -> Option { + self.limits.max_feed_duration + } + + /// Returns the configured per-turn execution time limit, if any. + #[must_use] + pub fn max_turn_duration(&self) -> Option { + self.limits.max_turn_duration + } + + /// Returns the configured memory budget, if any. Hosts that bound a worker + /// process from outside the interpreter size that bound from this. + #[must_use] + pub fn max_memory(&self) -> Option { + self.limits.max_memory + } + + /// Returns the host-enforced suspension budget (default + /// [`DEFAULT_MAX_SUSPENSIONS`]; never unlimited). + #[must_use] + pub fn max_suspensions(&self) -> usize { + self.limits.max_suspensions + } + + /// Cumulative sleep limit for the host to enforce, including after restore. + #[must_use] + pub fn max_total_sleep(&self) -> Option { + self.limits.max_total_sleep + } + + /// Returns whether the VM has a memory or time limit configured. + #[must_use] + pub fn has_memory_time_limit(&self) -> bool { + self.limits.max_memory.is_some() || self.has_time_limit() + } + + /// Returns whether either execution-time budget is configured. + /// + /// Public so callers that pay for finer-grained clock polling only when a + /// budget exists (`fstring`'s incremental large-result path) can ask. + #[must_use] + #[inline] + pub fn has_time_limit(&self) -> bool { + self.limits.max_feed_duration.is_some() || self.limits.max_turn_duration.is_some() + } + + /// Sets the per-feed execution limit as a fresh budget from now, resetting + /// the feed (and so the turn) clock. + /// + /// This lets a host enforce a different (typically shorter) time limit + /// for a resumed phase — e.g. allowing a long build phase, then giving + /// `repr()` of the result only a few milliseconds. Time spent suspended + /// in the host never counts toward the budget either way. + pub fn set_max_feed_duration(&mut self, duration: Duration) { + self.limits.max_feed_duration = Some(duration); + self.on_feed_start(); + } + + /// Sets the per-turn execution limit as a fresh budget from now, resetting + /// the turn clock. + pub fn set_max_turn_duration(&mut self, duration: Duration) { + self.limits.max_turn_duration = Some(duration); + self.on_turn_start(); + } + + /// Checks whether one up-front allocation fits the memory budget. + /// + /// Use this before reserving a buffer that could cross both the soft and + /// hard allocator limits before execution reaches another checkpoint. + #[inline] + pub fn check_allocation(&self, additional: usize) -> Result<(), ResourceError> { + if let Some(limit) = self.limits.max_memory { + let used = probe_memory().saturating_add(additional); + if used > limit { + return Err(ResourceError::Memory { limit, used }); + } + } + Ok(()) + } + + /// Called periodically to check allocator-backed memory and time limits. + /// + /// Returns `Ok(())` while configured limits are respected, or the relevant + /// resource error once either limit is exceeded. + /// + /// Takes `&self` rather than `&mut self` because checking elapsed time is a + /// read-only operation. This allows time checks in contexts that only have + /// an immutable heap reference, such as `py_repr_fmt`. + #[inline] + pub fn check_memory_time(&self) -> Result<(), ResourceError> { + if let Some(limit) = self.limits.max_memory { + let used = probe_memory(); + if used > limit { + return Err(ResourceError::Memory { limit, used }); + } + } + + self.check_time() + } + + /// Called periodically to check both execution-time budgets. + /// + /// Each clock is monotonic within its scope, so once a budget is exceeded + /// every later call in that scope fails too. The feed budget is tested + /// first, since it is the one a new turn cannot recover from. + #[inline] + pub fn check_time(&self) -> Result<(), ResourceError> { + // bashkit fork: host checkpoint hook. + if let Some(hook) = CHECKPOINT_HOOK.get() { + hook()?; + } + if !self.has_time_limit() { + return Ok(()); + } + // One clock reading shared by both comparisons. + let running = self.running_window(); + check_budget( + TimeLimitScope::Feed, + self.limits.max_feed_duration, + self.feed_execution_time.get() + running, + ) + .and_then(|()| { + check_budget( + TimeLimitScope::Turn, + self.limits.max_turn_duration, + self.turn_execution_time.get() + running, + ) + }) + } + + /// Items processed between full checks in amortized per-item Rust loops + /// (see [`check_time_every`](Self::check_time_every)). A limit can be + /// overshot by up to this many items' work before the next check — an + /// accepted trade for cheap loops; the process-level hard limits backstop + /// pathological cases. + pub const LOOP_CHECK_INTERVAL: usize = 64; + + /// Amortized per-item time check for Rust-side loops: a full clock read + /// once per [`LOOP_CHECK_INTERVAL`](Self::LOOP_CHECK_INTERVAL) calls, + /// free otherwise. Key `i` on the loop's index or a monotonically + /// increasing counter. Fires at the *end* of each block (`i % N == N-1`) + /// so loops shorter than the interval pay no clock read at all — the VM + /// dispatch checkpoint covers cadence between short calls. + #[inline] + pub fn check_time_every(&self, i: usize) -> Result<(), ResourceError> { + if i % Self::LOOP_CHECK_INTERVAL == Self::LOOP_CHECK_INTERVAL - 1 { + self.check_time() + } else { + Ok(()) + } + } + + /// Amortized per-item memory + time check; the memory-probing sibling of + /// [`check_time_every`](Self::check_time_every), for loops that allocate + /// per item. Between full checks the allocator's hard limit still bounds + /// runaway growth. + #[inline] + pub fn check_memory_time_every(&self, i: usize) -> Result<(), ResourceError> { + if i % Self::LOOP_CHECK_INTERVAL == Self::LOOP_CHECK_INTERVAL - 1 { + self.check_memory_time() + } else { + Ok(()) + } + } + + /// Preflights the reallocation that pushing one more element onto a dense + /// buffer causes; a push that fits the existing capacity costs nothing. + /// + /// A `Vec` charges its whole doubling in one allocation, so a push + /// straddling the soft limit can land past the allocator's fixed + /// hard-limit headroom, killing the worker with no checkpoint in between + /// at which to raise `MemoryError`. Only for the one-push shape: a bulk + /// reservation needs [`ResourceTracker::check_allocation`] sized for the + /// whole result, since preflighting less than the final buffer — one + /// operand of a merge, say — leaves the same window open. + #[inline] + pub fn check_growth(&self, len: usize, capacity: usize, elem_size: usize) -> Result<(), ResourceError> { + self.check_pending_allocation(Self::growth_bytes(len, capacity, elem_size)) + } + + /// The bytes [`check_growth`](Self::check_growth) would preflight, or zero + /// if the push allocates nothing. + /// + /// Split out for containers that grow two buffers on one insertion, such + /// as a dict's entry vector and index table: checking each increment alone + /// passes both while their sum clears the headroom, so the caller sums + /// them and passes the total to + /// [`check_pending_allocation`](Self::check_pending_allocation). + #[inline] + #[must_use] + pub fn growth_bytes(len: usize, capacity: usize, elem_size: usize) -> usize { + if len < capacity { + 0 + } else { + // A buffer growing from nothing jumps straight to + // `RawVec::MIN_NON_ZERO_CAP`, which is also what stops the + // increment coming out as zero. + let min_non_zero_capacity = match elem_size { + 1 => 8, + 2..=1024 => 4, + _ => 1, + }; + let new_capacity = capacity + .saturating_mul(2) + .max(len.saturating_add(1)) + .max(min_non_zero_capacity); + new_capacity.saturating_sub(capacity).saturating_mul(elem_size) + } + } + + /// [`check_allocation`](Self::check_allocation) for preflights whose + /// increment may be zero: a push that allocates nothing must not pay for + /// the usage probe. + #[inline] + pub fn check_pending_allocation(&self, additional: usize) -> Result<(), ResourceError> { + if additional == 0 { + Ok(()) + } else { + self.check_allocation(additional) + } + } + + /// Called before pushing a new call frame to check recursion depth. + /// + /// Returns `Ok(())` if within recursion limit, or `Err(ResourceError::Recursion)` + /// if the limit would be exceeded. `current_depth` is the call stack depth + /// before the new frame is pushed. + #[inline] + pub fn check_recursion_depth(&self, current_depth: usize) -> Result<(), ResourceError> { + let limit = self.active_recursion_limit(); + // current_depth is before push, so new depth would be current_depth + 1 + if current_depth >= limit { + return Err(ResourceError::Recursion { + limit, + depth: current_depth + 1, + }); + } + Ok(()) + } + + /// Called before operations that may produce large results (>100KB). + /// + /// This allows pre-emptive rejection of operations like `2 ** 10_000_000` + /// before the memory is actually allocated. The check only happens for + /// estimated result sizes above [`LARGE_RESULT_THRESHOLD`] to avoid overhead + /// on small operations. + #[inline] + pub fn check_large_result(&self, estimated_bytes: usize) -> Result<(), ResourceError> { + self.check_allocation(estimated_bytes) + } + + /// Returns the configured garbage collection interval, in GC-tracked + /// allocations. + /// + /// The cycle collector runs at most once per `gc_interval` GC-tracked + /// allocations, and additionally short-circuits when no cycle candidates + /// are pending — so programs that never form cycles pay no collector + /// cost regardless of their allocation rate. `None` tells the heap to use + /// its built-in default scheduling threshold. + #[must_use] + #[inline] + pub fn gc_interval(&self) -> Option { + self.limits.gc_interval + } + + /// Called when the VM enters its execution loop from a host boundary + /// (`VM::run_external`), starting one execution window. + /// + /// Paired with [`on_execution_stop`](Self::on_execution_stop) and never + /// nested — VM-internal re-entry (task switches, host-initiated function + /// evaluation) uses the raw run loop, so its time falls inside the + /// enclosing window. The execution-time clock runs between the pair; it is + /// *not* running while execution is suspended waiting on the host + /// (external function calls) or between feeds. + pub fn on_execution_start(&self) { + debug_assert!( + self.running_since.get().is_none(), + "nested on_execution_start: VM-internal re-entry must use the raw run loop, not run_external" + ); + self.running_since.set(Some(Instant::now())); + } + + /// Called when the VM leaves its execution loop — on completion, error, + /// or suspension at an external call. See [`on_execution_start`](Self::on_execution_start). + pub fn on_execution_stop(&self) { + if let Some(started) = self.running_since.take() { + let window = started.elapsed(); + for clock in [ + &self.total_execution_time, + &self.feed_execution_time, + &self.turn_execution_time, + ] { + clock.set(clock.get() + window); + } + } + } + + /// Called when the host begins a new feed, resetting the `max_feed_duration` + /// budget (and, since a feed opens a turn, the `max_turn_duration` one). + /// + /// A feed spans every turn its snippet takes, so this must fire only at + /// the snippet's first turn — not at the resumes that continue it. + pub fn on_feed_start(&self) { + self.feed_execution_time.set(Duration::ZERO); + self.on_turn_start(); + } + + /// Called when the host hands control back to the interpreter — at a feed + /// or a resume — resetting the `max_turn_duration` budget. + /// + /// Continuations the VM resolves without the host (an already-settled + /// future, a task switch) stay inside the turn that started them. + pub fn on_turn_start(&self) { + self.turn_execution_time.set(Duration::ZERO); + } + + /// Performs a standard-execution sleep without charging `max_feed_duration`. + /// Restarts the execution clock only if it was running before the wait. + /// All interpreter waits use `block_for` for platform-specific blocking. + pub fn sandbox_sleep(&self, duration: Duration) { + let was_running = self.running_since.get().is_some(); + self.on_execution_stop(); + block_for(duration); + if was_running { + self.on_execution_start(); + } + } + + /// Lowers the live recursion ceiling to `new_limit`, refusing to raise it. + /// + /// Exposed under the `test-hooks` feature so `sys.setrecursionlimit` can + /// tighten the depth ceiling from inside fixture code. The constructed + /// limit (`limits.max_recursion_depth`) acts as the hard upper bound — + /// raising it would let sandboxed code escape the host-imposed safety + /// bound. A `new_limit` above the active ceiling is rejected with + /// `Err(current)`, which callers surface as a `ValueError` in the + /// Python layer. + #[cfg(feature = "test-hooks")] + pub fn lower_recursion_limit(&self, new_limit: usize) -> Result<(), usize> { + let limit = self.active_recursion_limit(); + if new_limit > limit { + return Err(limit); + } + self.recursion_limit_override.set(Some(new_limit)); + Ok(()) + } +} + +/// Combines optional ceilings, where an absent limit permits any value. +fn tighter_limit(existing: Option, ceiling: Option) -> Option { + match (existing, ceiling) { + (Some(existing), Some(ceiling)) => Some(existing.min(ceiling)), + (existing, ceiling) => existing.or(ceiling), + } +} + +/// [`tighter_limit`] for `gc_interval`, where `None` is [`DEFAULT_GC_INTERVAL`], not unlimited. +fn tighter_gc_interval(existing: Option, ceiling: Option) -> Option { + let effective = existing + .unwrap_or(DEFAULT_GC_INTERVAL) + .min(ceiling.unwrap_or(DEFAULT_GC_INTERVAL)); + existing.or(ceiling).map(|_| effective) +} + +/// Reports `elapsed` against one optional budget, naming `scope` in the error. +#[inline] +fn check_budget(scope: TimeLimitScope, limit: Option, elapsed: Duration) -> Result<(), ResourceError> { + match limit { + Some(limit) if elapsed > limit => Err(ResourceError::Time { scope, limit, elapsed }), + _ => Ok(()), + } +} + +/// Returns memory used in bytes +fn probe_memory() -> usize { + // bashkit fork: host memory probe. + match MEMORY_PROBE.get() { + Some(probe) => probe(), + None => LIVE_MEMORY + .load(Ordering::Relaxed) + .saturating_sub(BASELINE_MEMORY.load(Ordering::Relaxed)), + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn block_for(duration: Duration) { + thread::sleep(duration); +} + +/// Blocks for `duration` on wasm by spinning on the monotonic clock: +/// `std::thread::sleep` needs `wasi:io/poll`, which a browser host serves +/// only asynchronously. Only standard execution waits here; the wasm worker +/// suspends its sleeps to the JavaScript host instead. +#[cfg(target_arch = "wasm32")] +fn block_for(duration: Duration) { + let started = Instant::now(); + while started.elapsed() < duration { + hint::spin_loop(); + } +} diff --git a/crates/bashkit-monty-types/src/results.rs b/crates/bashkit-monty-types/src/results.rs new file mode 100644 index 000000000..b631cca34 --- /dev/null +++ b/crates/bashkit-monty-types/src/results.rs @@ -0,0 +1,72 @@ +//! Host-supplied results fed back into a suspended run: +//! [`NameLookupResult`] and [`ExtFunctionResult`]. + +use crate::{exceptions::MontyException, object::MontyObject}; +/// Result of a name lookup from the host. +/// +/// When the VM encounters an unresolved name (or a lazy attribute on a +/// host-backed object), the host provides one of these: +/// - `Value(obj)`: The name resolves to this value (a plain name is cached in +/// its namespace slot; an attribute is re-consulted on every access). +/// - `Undefined`: The name does not exist — `NameError` for a plain name, +/// `AttributeError` for an attribute. +/// - `Error(exc)`: Resolving it raised on the host — the exception is raised +/// inside the sandbox, so `hasattr()` / `getattr()` defaults do not apply. +#[derive(Debug)] +pub enum NameLookupResult { + /// The name resolves to this value. + Value(MontyObject), + /// The name is undefined — the VM raises `NameError` / `AttributeError`. + Undefined, + /// Resolving the name raised this exception on the host; the VM raises + /// it where the lookup suspended, like a failed external call. + Error(MontyException), +} + +impl From for NameLookupResult { + fn from(value: MontyObject) -> Self { + Self::Value(value) + } +} + +impl From> for NameLookupResult { + /// `Some` resolves the name, `None` leaves it undefined. + fn from(value: Option) -> Self { + value.map_or(Self::Undefined, Self::Value) + } +} + +impl From for NameLookupResult { + fn from(exception: MontyException) -> Self { + Self::Error(exception) + } +} + +/// Return value or exception from an external function. +#[derive(Debug)] +pub enum ExtFunctionResult { + /// Continues execution with the return value from the external function. + Return(MontyObject), + /// Continues execution with the exception raised by the external function. + Error(MontyException), + /// Pending future — the external function is a coroutine. + /// + /// The `u32` is the `call_id` from the `FunctionCall` that created this + /// snapshot. It is used to track the pending future so it can be resolved + /// later via `ResolveFutures::resume()`. + Future(u32), + /// Raises `NameError`, or `ModuleNotFoundError` for an `import` call. + NotFound(String), +} + +impl From for ExtFunctionResult { + fn from(value: MontyObject) -> Self { + Self::Return(value) + } +} + +impl From for ExtFunctionResult { + fn from(exception: MontyException) -> Self { + Self::Error(exception) + } +} diff --git a/crates/bashkit-monty-types/src/run_options.rs b/crates/bashkit-monty-types/src/run_options.rs new file mode 100644 index 000000000..1e2da2ef3 --- /dev/null +++ b/crates/bashkit-monty-types/src/run_options.rs @@ -0,0 +1,96 @@ +//! Compile-time configuration: [`CompileOptions`] and the +//! [`AssertMessageAnnotations`] introspected-assert setting. + +use std::num::NonZeroU32; + +/// Byte length up to which a source is compiled without the pre-parse nesting +/// scan; the default for [`CompileOptions::source_scan_threshold`]. +/// +/// ruff grows its parser stack on demand, outside the sandbox allocator, at +/// roughly 2 KiB per nesting level, and a source cannot nest deeper than it is +/// long. 4 KiB (about 40 lines of 100 characters) caps that untracked growth +/// at ~8 MiB while sparing ordinary programs the extra lexer pass. +pub const SOURCE_SCAN_THRESHOLD: usize = 4 * 1024; + +/// Options controlling how Monty behavior diverges from plain CPython. +/// +/// Consumed when code is compiled: a `MontyRun` bakes the choices into the +/// program at construction, while a `MontyRepl` stores them so every snippet +/// fed to the session compiles the same way. +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +pub struct CompileOptions { + /// Give failed `assert` statements pytest-style introspected messages, + /// deliberately diverging from CPython; see `limitations/assert.md`. + /// On by default with a 120-byte operand-repr truncation. + pub assert_message_annotations: AssertMessageAnnotations, + /// Sources longer than this many bytes are scanned for parser nesting + /// before ruff sees them (see `limitations/language.md`); `0` scans every + /// source and `usize::MAX` none. Defaults to [`SOURCE_SCAN_THRESHOLD`]. + pub source_scan_threshold: usize, +} + +impl Default for CompileOptions { + fn default() -> Self { + Self { + assert_message_annotations: AssertMessageAnnotations::default(), + source_scan_threshold: SOURCE_SCAN_THRESHOLD, + } + } +} + +/// Controls the pytest-style introspected `assert` failure messages of +/// [`CompileOptions::assert_message_annotations`]. +/// +/// The choice is baked in at compile time (whether the introspecting opcodes +/// are emitted) but the truncation limit is applied at runtime, so it also +/// travels with serialized sessions. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum AssertMessageAnnotations { + /// Disable introspection; bare asserts use CPython's empty message. + Off, + /// Retain at most this many UTF-8 bytes per operand before any `…` suffix. + /// Non-zero because `0` encodes [`Off`](Self::Off) on the wire. + MaxBytes(NonZeroU32), +} + +impl AssertMessageAnnotations { + /// Operand-repr truncation used by [`Default`] and `From`. + pub const DEFAULT_MAX_BYTES: NonZeroU32 = NonZeroU32::new(120).expect("120 is non-zero"); + + /// Whether the compiler should emit introspecting assert opcodes. + #[must_use] + pub fn enabled(self) -> bool { + !matches!(self, Self::Off) + } + + /// Returns the wire value: `0` when disabled, otherwise the UTF-8 byte cap. + #[must_use] + pub fn max_bytes(self) -> u32 { + match self { + Self::Off => 0, + Self::MaxBytes(n) => n.get(), + } + } + + /// Decodes the wire value: `0` is off and any other value is the byte cap. + #[must_use] + pub fn from_max_bytes(value: u32) -> Self { + match NonZeroU32::new(value) { + Some(n) => Self::MaxBytes(n), + None => Self::Off, + } + } +} + +impl Default for AssertMessageAnnotations { + fn default() -> Self { + Self::MaxBytes(Self::DEFAULT_MAX_BYTES) + } +} + +impl From for AssertMessageAnnotations { + /// `true` enables the 120-byte default; `false` disables annotations. + fn from(enabled: bool) -> Self { + if enabled { Self::default() } else { Self::Off } + } +} diff --git a/crates/bashkit-monty-types/src/scan.rs b/crates/bashkit-monty-types/src/scan.rs new file mode 100644 index 000000000..334718a80 --- /dev/null +++ b/crates/bashkit-monty-types/src/scan.rs @@ -0,0 +1,1197 @@ +//! Directory-tree scans: the one OS call behind `os.scandir`, `os.walk`, +//! `Path.walk`, `Path.glob` and `Path.rglob`. +//! +//! The sandbox cannot suspend part-way through an iterator, so it asks the host +//! for a whole bounded subtree in one [`OsFunctionCall::Scan`](crate::OsFunctionCall::Scan) +//! and walks or globs the reply itself. +//! +//! A glob pattern rides along so the host can prune. A host may reply with the +//! tree, which needs only *at least* the entries the sandbox needs: every entry +//! [`GlobSelector`] visits when run against the real tree. Extra entries are +//! harmless because the sandbox re-runs the selector over the reply, so a host +//! that ignores the pattern and returns everything within `max_depth` (descending +//! symlinks when `follow_symlinks` says so) is still correct. Or it may run the +//! selector itself and reply with the matches ([`ScanReply::Matches`]), which +//! the sandbox uses as they are. [`collect_scan`] is the implementation hosts +//! can share; it replies with matches unless they outnumber the entries read. + +use std::{ + borrow::Cow, + collections::{BTreeMap, HashMap, HashSet}, + convert::Infallible, + rc::Rc, + sync::Arc, +}; + +use crate::{ + graph::{MontyGraph, MontyNode, NodeId}, + object::MontyObject, + os::MontyPath, + unstable::{self, PushValue}, +}; + +/// Arguments of a [`Scan`](crate::OsFunctionCall::Scan) call. +/// +/// Hosts that ignore `pattern` honour `max_depth` and `follow_symlinks`; hosts +/// that prune with it use `pattern`, `case_sensitive` and `recurse_symlinks` +/// (see [`collect_scan`]). Construct with [`ScanArgs::listing`] or [`ScanArgs::glob`], +/// which keep the two views consistent. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, monty_macros::ToArgs)] +pub struct ScanArgs { + /// Root of the scan; reply paths are relative to it. + pub path: MontyPath, + /// Deepest entry to return: `Some(0)` is the root alone, `Some(1)` its + /// children (`scandir`), `None` the whole tree. + #[from_args(kw_only)] + pub max_depth: Option, + /// Whether to descend into symlinked directories when not pruning with `pattern`. + #[from_args(kw_only)] + pub follow_symlinks: bool, + /// `Path.glob` pattern parts relative to `path`, as CPython parses them + /// (a trailing `''` means "directories only"); a pruning hint only. + #[from_args(kw_only)] + pub pattern: Option>, + /// CPython's `case_sensitive` argument: `None` matches case-sensitively and + /// looks literal parts up directly; an explicit value lists every part. + #[from_args(kw_only)] + pub case_sensitive: Option, + /// Whether `**` in `pattern` descends into symlinked directories. + #[from_args(kw_only)] + pub recurse_symlinks: bool, +} + +impl ScanArgs { + /// A plain listing to `max_depth` (`os.scandir`, `os.walk`, `Path.walk`). + #[must_use] + pub fn listing(path: MontyPath, max_depth: Option, follow_symlinks: bool) -> Self { + Self { + path, + max_depth, + follow_symlinks, + pattern: None, + case_sensitive: None, + recurse_symlinks: false, + } + } + + /// A `Path.glob` scan of the parts left after [`split_literal_prefix`]. + /// + /// Derives the fallback `max_depth` and `follow_symlinks` a pattern-ignoring + /// host needs to return a superset: wildcard parts other than the last may + /// match a symlinked directory and then descend into it. + #[must_use] + pub fn glob(path: MontyPath, parts: Vec, case_sensitive: Option, recurse_symlinks: bool) -> Self { + let recursive = parts.iter().any(|part| part == "**"); + let depth = parts.iter().filter(|part| !is_special(part)).count(); + let descends_wildcard = parts + .iter() + .take(parts.len().saturating_sub(1)) + .any(|part| part != "**" && !is_special(part)); + Self { + path, + max_depth: if recursive { + None + } else { + Some(u32::try_from(depth).unwrap_or(u32::MAX)) + }, + follow_symlinks: recurse_symlinks || descends_wildcard, + pattern: Some(parts), + case_sensitive, + recurse_symlinks, + } + } +} + +/// What a scan knows about one entry, with `os.DirEntry` semantics: +/// `is_dir` and `is_file` follow a symlink, `is_symlink` does not. +/// +/// A broken symlink is `is_symlink` alone; something that is none of the three +/// (a socket, a FIFO) is all `false`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct EntryInfo { + /// The entry is, or links to, a directory. + pub is_dir: bool, + /// The entry is, or links to, a regular file. + pub is_file: bool, + /// The entry itself is a symbolic link. + pub is_symlink: bool, +} + +/// One entry of a scan reply: its path relative to the scan root (`""` for the +/// root itself, `/`-separated below it) and what it is. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScanEntry { + /// Relative path, normalized: no `.`, `..` or empty components. + pub path: String, + /// Kind of entry. + pub info: EntryInfo, +} + +/// What a host answers a scan with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ScanReply { + /// Entries for the sandbox to walk, list or glob itself. + Tree(Vec), + /// A glob's matches as [`GlobSelector::select`] returns them, already + /// selected, so the sandbox skips selection; valid only for a glob scan. + Matches(Vec), +} + +impl ScanReply { + /// Encodes the reply: the tree as [`scan_reply`] does, matches as + /// `{'matches': [path, ...]}`. + #[must_use] + pub fn into_object(self) -> MontyObject { + match self { + Self::Tree(entries) => scan_reply(entries), + Self::Matches(matches) => MontyObject::dict([( + MontyObject::string(MATCHES_KEY.to_owned()), + MontyObject::list(matches.into_iter().map(MontyObject::string)), + )]), + } + } +} + +/// The key of a [`ScanReply::Matches`] reply's one-entry dict. +const MATCHES_KEY: &str = "matches"; + +/// Encodes a tree scan reply as the host returns it: a list of +/// `(path, is_dir, is_file, is_symlink)` tuples, including the root as `""`. +#[must_use] +pub fn scan_reply(entries: impl IntoIterator) -> MontyObject { + MontyObject::list(entries.into_iter().map(|entry| { + MontyObject::tuple([ + MontyObject::string(entry.path), + MontyObject::bool(entry.info.is_dir), + MontyObject::bool(entry.info.is_file), + MontyObject::bool(entry.info.is_symlink), + ]) + })) +} + +/// Decodes a host's scan reply (see [`ScanReply::into_object`]); tree entries +/// may be tuples, lists or named tuples, and paths `str` or `Path`. +/// +/// The error describes what was wrong for the sandbox's `RuntimeError`. Paths +/// are normalized, and one that is absolute or climbs above the root is refused. +pub fn parse_scan_reply(reply: &MontyObject) -> Result { + let (graph, _) = unstable::graph_parts(reply); + match unstable::root_node(reply) { + MontyNode::List(ids) => ids + .iter() + .map(|&id| parse_entry(graph, id)) + .collect::>() + .map(ScanReply::Tree), + MontyNode::Dict(pairs) => match matches_list(graph, pairs) { + Some(ids) => ids + .iter() + .map(|&id| parse_match(graph, id)) + .collect::>() + .map(ScanReply::Matches), + None => Err(format!( + "expected {{'{MATCHES_KEY}': [path, ...]}}, got a different dict" + )), + }, + _ => Err(format!( + "expected a list of (path, is_dir, is_file, is_symlink) tuples, got {}", + reply.as_ref().type_name() + )), + } +} + +/// The match list of a `{'matches': [...]}` dict, `None` for any other dict. +fn matches_list<'g>(graph: &'g MontyGraph, pairs: &[(NodeId, NodeId)]) -> Option<&'g [NodeId]> { + let [(key, value)] = pairs else { + return None; + }; + match (graph.node(*key), graph.node(*value)) { + (MontyNode::String(key), MontyNode::List(ids)) if key == MATCHES_KEY => Some(ids), + _ => None, + } +} + +/// Decodes one match: a relative path, normalized, keeping a trailing `/`. +fn parse_match(graph: &MontyGraph, id: NodeId) -> Result { + let (MontyNode::String(path) | MontyNode::Path(path)) = graph.node(id) else { + return Err(format!( + "expected glob matches to be paths, got {}", + graph.type_name(id) + )); + }; + let trimmed = path.trim_end_matches('/'); + let normalized = if path.starts_with('/') { + None + } else { + normalize_relative(trimmed) + } + .ok_or_else(|| format!("glob match {path:?} is not relative to the scan root"))?; + let mut normalized = normalized.into_owned(); + if trimmed.len() < path.len() && !normalized.is_empty() { + normalized.push('/'); + } + Ok(normalized) +} + +/// Bytes [`parse_scan_reply`] and [`ScanTree::new`] allocate for `reply`, roughly: +/// each path is held three times (parsed, keyed, listed) plus per-entry overhead. +/// A match is charged the same, which covers it being parsed and then spelled. +/// +/// Lets the sandbox charge its memory limit before indexing a reply, without allocating. +#[must_use] +pub fn indexed_size(reply: &MontyObject) -> usize { + /// Map slots, list slots and flags per entry, generously. + const ENTRY_OVERHEAD: usize = 160; + let (graph, _) = unstable::graph_parts(reply); + let ids = match unstable::root_node(reply) { + MontyNode::List(ids) => ids.as_slice(), + MontyNode::Dict(pairs) => matches_list(graph, pairs).unwrap_or_default(), + _ => return 0, + }; + ids.iter() + .map(|&id| { + let path_len = match graph.node(id) { + MontyNode::String(path) | MontyNode::Path(path) => path.len(), + MontyNode::Tuple(items) | MontyNode::List(items) | MontyNode::NamedTuple { values: items, .. } => { + match items.first().map(|&path| graph.node(path)) { + Some(MontyNode::String(path) | MontyNode::Path(path)) => path.len(), + _ => 0, + } + } + _ => 0, + }; + path_len.saturating_mul(3).saturating_add(ENTRY_OVERHEAD) + }) + .fold(0, usize::saturating_add) +} + +/// Decodes one `(path, is_dir, is_file, is_symlink)` tuple. +fn parse_entry(graph: &MontyGraph, id: NodeId) -> Result { + let invalid = || { + format!( + "expected (path, is_dir, is_file, is_symlink) tuples, got {}", + graph.type_name(id) + ) + }; + let (MontyNode::Tuple(items) | MontyNode::List(items) | MontyNode::NamedTuple { values: items, .. }) = + graph.node(id) + else { + return Err(invalid()); + }; + let [path, is_dir, is_file, is_symlink] = items.as_slice() else { + return Err(invalid()); + }; + let flag = |id: &NodeId| match graph.node(*id) { + MontyNode::Bool(value) => Ok(*value), + _ => Err(invalid()), + }; + let (MontyNode::String(path) | MontyNode::Path(path)) = graph.node(*path) else { + return Err(invalid()); + }; + let normalized = if path.starts_with('/') { + None + } else { + normalize_relative(path) + } + .ok_or_else(|| format!("scan entry path {path:?} is not relative to the scan root"))?; + Ok(ScanEntry { + path: normalized.into_owned(), + info: EntryInfo { + is_dir: flag(is_dir)?, + is_file: flag(is_file)?, + is_symlink: flag(is_symlink)?, + }, + }) +} + +impl PushValue for Vec { + fn push_into(self, graph: &mut MontyGraph) -> NodeId { + let items = self.into_iter().map(|item| item.push_into(graph)).collect(); + graph.push(MontyNode::List(items)) + } +} + +// ============================================================================= +// Sources: what the selector reads a tree through. +// ============================================================================= + +/// A directory tree the glob selector and [`collect_scan`] read, with paths +/// relative to the scan root (`""` is the root). +/// +/// Paths may carry `..` from a pattern's literal parts; implementations +/// normalize them and treat one that climbs above the root as absent. +pub trait ScanSource { + /// A failure that aborts the scan, as opposed to an unreadable directory. + type Error; + + /// Lists `dir`'s children, or `None` when it cannot be listed (missing, + /// not a directory, unreadable) — CPython's glob skips those silently. + fn list(&mut self, dir: &str) -> Result, Self::Error>; + + /// Describes `path` without following a final symlink (`os.path.lexists`), + /// `None` when it does not exist. + fn lookup(&mut self, path: &str) -> Result, Self::Error>; + + /// Called once per entry a scan examines, so a host can cap the work a + /// pathological pattern (`*/**/*/**/...`) or a symlink cycle costs. + /// + /// No default: a host-side source, or a wrapper that fails to forward + /// this, would leave that work unbounded without anything failing. + fn visit(&mut self) -> Result<(), Self::Error>; + + /// Charged with the bytes of each glob state a scan holds, which a pattern + /// can multiply per entry read (`*/../*/../*`), so a host can bound them + /// with the entries. + /// + /// No default, for the same reason as [`Self::visit`]. + fn charge(&mut self, bytes: usize) -> Result<(), Self::Error>; + + /// Most matches [`GlobSelector::select`] collects from this source before + /// it stops collecting them; unlimited by default. + fn match_capacity(&self) -> usize { + usize::MAX + } +} + +/// A directory's children by name, shared so memoized and indexed listings +/// are handed out without copying their names. +pub type Listing = Arc<[(String, EntryInfo)]>; + +/// Runs a scan against `source` for a host and returns its reply, or `None` +/// when the root does not exist. +/// +/// Listings are memoized, so each directory is read at most once however many +/// pattern states reach it. With a pattern only the entries [`GlobSelector`] +/// visits are read, and the reply is the matches, unless they outnumber those +/// entries (`**/*/**` yields an entry once per ancestor); then it is every +/// entry read, root included, as it is without a pattern for the tree to `max_depth`. +pub fn collect_scan(args: &ScanArgs, source: &mut impl ScanSource) -> Result, E> { + let mut recorder = Recorder { + source, + listed: HashMap::new(), + entries: BTreeMap::new(), + }; + let Some(root) = recorder.lookup("")? else { + return Ok(None); + }; + if root.is_dir { + match &args.pattern { + Some(parts) => { + let selector = GlobSelector::new(parts, args.case_sensitive, args.recurse_symlinks); + if let Some(matches) = selector.select(&mut recorder)? { + return Ok(Some(ScanReply::Matches(matches))); + } + } + None => walk_to_depth(&mut recorder, args.max_depth, args.follow_symlinks)?, + } + } + let entries = recorder + .entries + .into_iter() + .map(|(path, info)| ScanEntry { path, info }) + .collect(); + Ok(Some(ScanReply::Tree(entries))) +} + +/// Lists every directory shallower than `max_depth`, descending symlinked ones +/// only when `follow_symlinks`. +fn walk_to_depth( + source: &mut impl ScanSource, + max_depth: Option, + follow_symlinks: bool, +) -> Result<(), E> { + let mut stack = vec![(String::new(), 0_u32)]; + while let Some((dir, depth)) = stack.pop() { + if max_depth.is_some_and(|max| depth >= max) { + continue; + } + for (name, info) in source.list(&dir)?.unwrap_or_default().iter() { + source.visit()?; + if info.is_dir && (follow_symlinks || !info.is_symlink) { + stack.push((join(&dir, name), depth + 1)); + } + } + } + Ok(()) +} + +/// Memoizes a host source's listings, sorted by name as the sandbox's +/// [`ScanTree`] sorts them so matches come out in the same order, and records +/// every entry they return. +struct Recorder<'s, S> { + source: &'s mut S, + /// Listings by normalized directory path. + listed: HashMap>, + /// Every entry seen, by normalized path; becomes the reply. + entries: BTreeMap, +} + +impl> ScanSource for Recorder<'_, S> { + type Error = E; + + fn list(&mut self, dir: &str) -> Result, E> { + let Some(dir) = normalize_relative(dir) else { + return Ok(None); + }; + if let Some(listing) = self.listed.get(dir.as_ref()) { + return Ok(listing.clone()); + } + // Record the directory itself too: a literal part reaches it without a + // listing of its parent, and the sandbox only lists what it knows is a directory. + if self.lookup(&dir)?.is_none_or(|info| !info.is_dir) { + self.listed.insert(dir.into_owned(), None); + return Ok(None); + } + let mut listing = self.source.list(&dir)?; + // Copied only if the source still shares an unsorted listing. + if let Some(children) = &mut listing + && !children.is_sorted_by(|(a, _), (b, _)| a <= b) + { + Arc::make_mut(children).sort_by(|(a, _), (b, _)| a.cmp(b)); + } + for (name, info) in listing.iter().flat_map(|children| children.iter()) { + self.entries.insert(join(&dir, name), *info); + } + self.listed.insert(dir.into_owned(), listing.clone()); + Ok(listing) + } + + fn lookup(&mut self, path: &str) -> Result, E> { + let Some(path) = normalize_relative(path) else { + return Ok(None); + }; + if let Some(info) = self.entries.get(path.as_ref()) { + return Ok(Some(*info)); + } + let info = self.source.lookup(&path)?; + if let Some(info) = info { + self.entries.insert(path.into_owned(), info); + } + Ok(info) + } + + fn visit(&mut self) -> Result<(), E> { + self.source.visit() + } + + fn charge(&mut self, bytes: usize) -> Result<(), E> { + self.source.charge(bytes) + } + + /// Matches stay a smaller reply than the entries they are drawn from + /// unless a pattern yields an entry more than once. + fn match_capacity(&self) -> usize { + self.entries.len() + } +} + +/// A scan reply indexed for the sandbox: the [`ScanSource`] its glob reads and +/// the per-directory listings its walks read. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub struct ScanTree { + /// Every entry by normalized relative path; the root is `""`. + entries: HashMap, + /// Children of each directory, sorted by name. + children: HashMap, +} + +impl ScanTree { + /// Indexes reply entries; a later duplicate of a path replaces the earlier one. + #[must_use] + pub fn new(entries: Vec) -> Self { + let entries: HashMap = entries.into_iter().map(|entry| (entry.path, entry.info)).collect(); + let mut children: HashMap> = HashMap::new(); + for (path, info) in &entries { + if !path.is_empty() { + let (parent, name) = path.rsplit_once('/').unwrap_or(("", path)); + let child = (name.to_owned(), *info); + match children.get_mut(parent) { + Some(siblings) => siblings.push(child), + None => { + children.insert(parent.to_owned(), vec![child]); + } + } + } + } + let children = children + .into_iter() + .map(|(dir, mut siblings)| { + siblings.sort_by(|(a, _), (b, _)| a.cmp(b)); + (dir, Listing::from(siblings)) + }) + .collect(); + Self { entries, children } + } + + /// The root entry; a reply that omits it is taken to describe a directory. + #[must_use] + pub fn root(&self) -> EntryInfo { + self.entries.get("").copied().unwrap_or(EntryInfo { + is_dir: true, + is_file: false, + is_symlink: false, + }) + } + + /// The root entry if the reply described it, unlike [`Self::root`]. + #[must_use] + pub fn described_root(&self) -> Option { + self.entries.get("").copied() + } + + /// The sorted children of the normalized directory `dir`. + #[must_use] + pub fn children(&self, dir: &str) -> &[(String, EntryInfo)] { + self.children.get(dir).map_or(&[], |siblings| siblings) + } + + /// The entry at normalized path `path`. + #[must_use] + pub fn get(&self, path: &str) -> Option { + if path.is_empty() { + Some(self.root()) + } else { + self.entries.get(path).copied() + } + } +} + +impl ScanSource for ScanTree { + type Error = Infallible; + + fn list(&mut self, dir: &str) -> Result, Infallible> { + let listing = normalize_relative(dir) + .filter(|dir| self.get(dir).is_some_and(|info| info.is_dir)) + .map(|dir| self.children.get(dir.as_ref()).cloned().unwrap_or_default()); + Ok(listing) + } + + fn lookup(&mut self, path: &str) -> Result, Infallible> { + Ok(normalize_relative(path).and_then(|path| self.get(&path))) + } + + /// Unbounded: a reply already received, whose reader applies its own limits. + fn visit(&mut self) -> Result<(), Infallible> { + Ok(()) + } + + /// Free, as [`Self::visit`] is. + fn charge(&mut self, _bytes: usize) -> Result<(), Infallible> { + Ok(()) + } +} + +// ============================================================================= +// The glob selector — a port of CPython's `glob._GlobberBase`. +// ============================================================================= + +/// Splits off the leading parts CPython resolves by string concatenation +/// rather than listing: `..`, and literals unless `case_sensitive` was given. +/// +/// Returns the joined prefix and the rest. A prefix ending in `/` means the +/// pattern had a trailing slash, so the prefix must name a directory. Hoisting +/// the prefix into the scan root means the host lists nothing above it. +#[must_use] +pub fn split_literal_prefix(parts: &[String], case_sensitive: Option) -> (String, &[String]) { + let mut prefix = String::new(); + let mut rest = parts; + while let Some((part, tail)) = rest.split_first() + && part != "**" + && (is_special(part) || (case_sensitive.is_none() && !has_magic(part))) + { + if !prefix.is_empty() || part.is_empty() { + prefix.push('/'); + } + prefix.push_str(part); + rest = tail; + } + (prefix, rest) +} + +/// Selects the paths a `Path.glob` pattern matches, relative to the scan root. +/// +/// Mirrors CPython 3.14's selectors part for part — literal parts are looked up +/// rather than listed, `**` descends only real directories unless +/// `recurse_symlinks`, other wildcards descend symlinked ones — so running it +/// over a host's reply gives what CPython gives over the real tree. Unlike +/// CPython it works through an explicit stack over normalized paths and visits +/// each pattern state once, so the work is bounded by pattern parts × entries +/// × depth however the pattern is shaped (see [`Self::select`] for the cost). +#[derive(Debug)] +pub struct GlobSelector<'p> { + /// Parsed pattern parts. + parts: &'p [String], + /// What each part index does, compiled once; `None` where no step leads. + steps: Vec>, + /// Whether `**` descends into symlinked directories. + recurse_symlinks: bool, +} + +/// What the selector does at one pattern part (see [`GlobSelector`]). +#[derive(Debug)] +enum Step { + /// No parts left: yield the path if it exists. + Exists, + /// `''` or `..`: append it to the path without touching the filesystem. + Special, + /// Consecutive literal parts, joined with `/`, then continue at `next`. + Literal { joined: String, next: usize }, + /// List the directory and keep children whose name matches. + Wildcard { + matcher: Option, + next: usize, + }, + /// `**`: the path itself, then every descendant; `matcher` filters by the + /// parts merged after it when symlinks are followed. + Recursive { matcher: Option, next: usize }, +} + +impl<'p> GlobSelector<'p> { + /// Compiles `parts` (see [`ScanArgs::pattern`] and [`ScanArgs::case_sensitive`]). + /// + /// Only the steps reachable from the first part are compiled. Each consumes + /// the parts it covers, so compilation is linear in the pattern: compiling + /// every index would copy a literal tail once per part it has. + #[must_use] + pub fn new(parts: &'p [String], case_sensitive: Option, recurse_symlinks: bool) -> Self { + let mut steps: Vec> = (0..=parts.len()).map(|_| None).collect(); + let mut index = 0; + loop { + let step = compile_step(parts, index, case_sensitive, recurse_symlinks); + let next = match &step { + Step::Exists => None, + Step::Special => Some(index + 1), + Step::Literal { next, .. } | Step::Wildcard { next, .. } | Step::Recursive { next, .. } => Some(*next), + }; + steps[index] = Some(step); + match next { + Some(next) => index = next, + None => break, + } + } + Self { + parts, + steps, + recurse_symlinks, + } + } + + /// Selects every match, as normalized paths relative to the scan root. + /// + /// A `..` after a wildcard is collapsed and its target matched once, where + /// CPython spells out every route (`a/../b/../x`): keyed by spelling, the + /// states would multiply by the fan-out per `..`. A directory matched with + /// more parts to come keeps a trailing `/`, which the caller strips as + /// `pathlib` does. + /// + /// `None` when the matches outgrew [`ScanSource::match_capacity`]: the run + /// then stops collecting them but still reads everything it would have, so + /// a host can reply with what it read instead. + pub fn select(&self, source: &mut impl ScanSource) -> Result>, E> { + let mut run = Run { + stack: Vec::new(), + seen: HashSet::new(), + out: Some(Vec::new()), + }; + self.run(source, &mut run)?; + Ok(run.out) + } + + /// The selection loop behind [`Self::select`]. + fn run(&self, source: &mut impl ScanSource, run: &mut Run) -> Result<(), E> { + run.push(0, "", false, source)?; + while let Some((index, path, exists)) = run.stack.pop() { + let step = self.steps[index] + .as_ref() + .expect("states are only pushed by the step chain compiled from part 0"); + match step { + Step::Exists => { + if exists || lexists(&path, source)? { + run.emit(path.to_string(), source); + } + } + Step::Special => { + let mut path = format!("{path}{}", self.parts[index]); + if index + 1 < self.parts.len() { + path.push('/'); + } + run.push(index + 1, &path, exists, source)?; + } + Step::Literal { joined, next } => run.push(*next, &format!("{path}{joined}"), false, source)?, + Step::Wildcard { matcher, next } => { + let dir_only = *next < self.parts.len(); + for (name, info) in source.list(path.trim_end_matches('/'))?.unwrap_or_default().iter() { + source.visit()?; + if matcher.as_ref().is_none_or(|matcher| matcher.matches(name)) { + let entry = join(&path, name); + if !dir_only { + run.emit(entry, source); + } else if info.is_dir { + run.push(*next, &(entry + "/"), true, source)?; + } + } + } + } + Step::Recursive { matcher, next } => { + self.select_recursive(matcher.as_ref(), *next, &path, exists, source, run)?; + } + } + } + Ok(()) + } + + /// Runs a `**` step: the path itself, then each descendant, depth first. + fn select_recursive( + &self, + matcher: Option<&MultiPattern>, + next: usize, + path: &str, + exists: bool, + source: &mut impl ScanSource, + run: &mut Run, + ) -> Result<(), E> { + let dir_only = next < self.parts.len(); + let match_pos = path.len(); + if matcher.is_none_or(|matcher| matcher.matches("")) { + run.push(next, path, exists, source)?; + } + let mut dirs = vec![path.to_owned()]; + while let Some(dir) = dirs.pop() { + for (name, info) in source.list(dir.trim_end_matches('/'))?.unwrap_or_default().iter() { + source.visit()?; + let is_dir = info.is_dir && (self.recurse_symlinks || !info.is_symlink); + if is_dir || !dir_only { + let entry = join(&dir, name); + let matched = matcher.is_none_or(|matcher| matcher.matches(&entry[match_pos..])); + let entry = if dir_only { entry + "/" } else { entry }; + if is_dir { + if matched { + if dir_only { + run.push(next, &entry, true, source)?; + } else { + run.emit(entry.clone(), source); + } + } + dirs.push(entry); + } else if matched { + // Only a file match gets here (`dir_only` is false), so it takes the path. + run.emit(entry, source); + } + } + } + } + Ok(()) + } +} + +/// A glob state: part index, normalized path so far, known to exist. The path +/// is shared between the stack and the seen set. +type State = (usize, Rc, bool); + +/// Bytes a glob state holds beside its path: a slot on the stack and one in +/// the seen set, plus the path's reference counts. +const STATE_OVERHEAD: usize = 2 * size_of::() + 2 * size_of::(); + +/// The pending states and results of one [`GlobSelector`] run. +struct Run { + /// States still to process. + stack: Vec, + /// Every state ever queued, so each is processed once. + seen: HashSet, + /// Matches, until they outgrow the source's [`ScanSource::match_capacity`]. + out: Option>, +} + +impl Run { + /// Queues a state with its path normalized (keeping a trailing `/`) unless + /// it was queued before; one climbing above the root is dropped. + /// + /// Each new state is charged to `source`: it stays held in the seen set + /// until the run ends, and a pattern like `*/../*/../*` holds one per + /// entry for every wildcard part. + fn push( + &mut self, + index: usize, + path: &str, + exists: bool, + source: &mut impl ScanSource, + ) -> Result<(), E> { + let trimmed_len = path.trim_end_matches('/').len(); + let dir = trimmed_len > 0 && trimmed_len < path.len(); + let normalized: Rc = match normalize_relative(&path[..trimmed_len]) { + None => return Ok(()), + Some(Cow::Owned(mut normalized)) => { + if dir && !normalized.is_empty() { + normalized.push('/'); + } + normalized.into() + } + Some(Cow::Borrowed(_)) => path[..trimmed_len + usize::from(dir)].into(), + }; + let state = (index, normalized, exists); + if !self.seen.contains(&state) { + source.charge(STATE_OVERHEAD + state.1.len())?; + self.seen.insert(state.clone()); + self.stack.push(state); + } + Ok(()) + } + + /// Records a match, or stops collecting once `source` would hold one too many. + fn emit(&mut self, path: String, source: &impl ScanSource) { + if let Some(out) = &mut self.out { + if out.len() < source.match_capacity() { + out.push(path); + } else { + self.out = None; + } + } + } +} + +/// Decides what part `index` does, as CPython's `_GlobberBase.selector` does. +fn compile_step(parts: &[String], index: usize, case_sensitive: Option, recurse_symlinks: bool) -> Step { + let Some(part) = parts.get(index) else { + return Step::Exists; + }; + // An explicit `case_sensitive` makes CPython list even literal parts + // ("case pedantic"), since it cannot know the filesystem's own rule. + let pedantic = case_sensitive.is_some(); + let case_sensitive = case_sensitive.unwrap_or(true); + if part == "**" { + // Consecutive `**` parts behave as one. + let mut next = index + 1; + while parts.get(next).is_some_and(|part| part == "**") { + next += 1; + } + // Following symlinks, CPython folds the next non-special parts into one + // regex matched against each descendant's path instead of listing again. + let mut merged = vec![MultiPart::Recursive]; + if recurse_symlinks { + while let Some(part) = parts.get(next).filter(|part| !is_special(part)) { + merged.push(MultiPart::compile(part, case_sensitive)); + next += 1; + } + } + let matcher = (merged.len() > 1).then_some(MultiPattern(merged)); + Step::Recursive { matcher, next } + } else if is_special(part) { + Step::Special + } else if !pedantic && !has_magic(part) { + let mut joined = part.clone(); + let mut next = index + 1; + while let Some(part) = parts.get(next).filter(|part| !has_magic(part)) { + joined.push('/'); + joined.push_str(part); + next += 1; + } + if next < parts.len() { + joined.push('/'); + } + Step::Literal { joined, next } + } else { + let matcher = (part != "*").then(|| SegmentPattern::new(part, case_sensitive)); + Step::Wildcard { + matcher, + next: index + 1, + } + } +} + +/// `os.path.lexists` on a selector path: a trailing `/` (or the root, which is +/// always reached as `root/`) requires a directory, following a symlink. +fn lexists(path: &str, source: &mut impl ScanSource) -> Result { + let info = source.lookup(path.trim_end_matches('/'))?; + Ok(if path.is_empty() || path.ends_with('/') { + info.is_some_and(|info| info.is_dir) + } else { + info.is_some() + }) +} + +/// The parts CPython never matches against names: a trailing slash's `''`, `.` and `..`. +fn is_special(part: &str) -> bool { + matches!(part, "" | "." | "..") +} + +/// Whether a part contains a wildcard character, as `glob.magic_check`. +fn has_magic(part: &str) -> bool { + part.contains(['*', '?', '[']) +} + +/// Joins a child name onto a relative directory path (`""` is the root). +fn join(dir: &str, name: &str) -> String { + if dir.is_empty() || dir.ends_with('/') { + format!("{dir}{name}") + } else { + format!("{dir}/{name}") + } +} + +/// Lexically normalizes a `/`-separated relative path, dropping `.` and empty +/// components and resolving `..`; `None` if `..` climbs above the root. +/// +/// [`ScanTree`] stores and looks paths up in this form, so a caller spelling +/// one differently (`./sub`, `sub/../other`) normalizes it first. +#[must_use] +pub fn normalize_relative(path: &str) -> Option> { + if path.is_empty() || path.split('/').all(|part| !is_special(part)) { + Some(Cow::Borrowed(path)) + } else { + let mut parts: Vec<&str> = Vec::new(); + for part in path.split('/') { + match part { + "" | "." => {} + ".." => { + parts.pop()?; + } + part => parts.push(part), + } + } + Some(Cow::Owned(parts.join("/"))) + } +} + +// ============================================================================= +// fnmatch-style matching. +// ============================================================================= + +/// One path segment's pattern with `fnmatch` semantics: `*`, `?`, `[...]`, +/// `[!...]`; a leading dot is matched like any other character. +/// +/// Matching backtracks over `*` only, so it costs at most pattern length × +/// name length (the regex CPython compiles the pattern to backtracks the same +/// way), never exponential. Mounts bound both lengths by their name limit. +#[derive(Debug, Clone)] +pub struct SegmentPattern { + tokens: Vec, + case_sensitive: bool, +} + +/// A compiled `fnmatch` element. +#[derive(Debug, Clone, PartialEq)] +enum Token { + /// A literal character. + Char(char), + /// `?`: any one character. + Any, + /// `*`: any run of characters (consecutive stars collapse). + Star, + /// `[...]`: one character in (or, negated, not in) the items. + Class { negated: bool, items: Vec<(char, char)> }, +} + +impl SegmentPattern { + /// Compiles a segment pattern the way `fnmatch._translate` reads it. + #[must_use] + pub fn new(pattern: &str, case_sensitive: bool) -> Self { + let chars: Vec = pattern.chars().collect(); + let mut tokens = Vec::new(); + let mut i = 0; + // Once a `[` finds no `]` ahead, no later `[` can either; skipping their + // scans keeps a run of unterminated brackets linear. + let mut unterminated = false; + while let Some(&c) = chars.get(i) { + i += 1; + match c { + '*' => { + if tokens.last() != Some(&Token::Star) { + tokens.push(Token::Star); + } + } + '?' => tokens.push(Token::Any), + '[' if !unterminated => { + if let Some((token, end)) = parse_class(&chars, i) { + tokens.push(token); + i = end; + } else { + unterminated = true; + tokens.push(Token::Char('[')); + } + } + c => tokens.push(Token::Char(c)), + } + } + Self { tokens, case_sensitive } + } + + /// Whether `name` matches the whole pattern. + #[must_use] + pub fn matches(&self, name: &str) -> bool { + // `t` is a byte offset into `name`, always on a character boundary. + let (mut p, mut t) = (0, 0); + // The last `*` seen and the text position it is currently absorbing up to. + let mut star: Option<(usize, usize)> = None; + while let Some(c) = name[t..].chars().next() { + match self.tokens.get(p) { + Some(Token::Star) => { + star = Some((p, t)); + p += 1; + } + Some(token) if self.token_matches(token, c) => { + p += 1; + t += c.len_utf8(); + } + _ => match star { + Some((star_p, star_t)) => { + // The star was recorded before a character at `star_t`, so one is there. + let absorbed = name[star_t..].chars().next().map_or(1, char::len_utf8); + p = star_p + 1; + t = star_t + absorbed; + star = Some((star_p, t)); + } + None => return false, + }, + } + } + self.tokens[p..].iter().all(|token| *token == Token::Star) + } + + /// Whether a single-character token accepts `c`. + /// + /// Case-insensitively, `re.IGNORECASE` compares lowercased characters and + /// folds a class's ranges both ways, so the variants tried are `c`, its + /// lowercase, that lowercase's uppercase (`K` → `k` → `K`, for `[A-Z]`) and + /// its uppercase's lowercase (`ſ` → `S` → `s`, for `[a-z]`). + fn token_matches(&self, token: &Token, c: char) -> bool { + let variants = if self.case_sensitive { + [c, c, c, c] + } else { + let lower = simple_lower(c); + [c, lower, simple_upper(lower), simple_lower(simple_upper(c))] + }; + match token { + Token::Char(expected) => variants + .iter() + .any(|v| *v == *expected || (!self.case_sensitive && simple_lower(*expected) == simple_lower(*v))), + Token::Any => true, + Token::Star => false, + Token::Class { negated, items } => { + let hit = variants + .iter() + .any(|v| items.iter().any(|(low, high)| (*low..=*high).contains(v))); + hit != *negated + } + } + } +} + +/// Parses a `[...]` class whose body starts at `start`, returning the token and +/// the index after `]`, or `None` when unterminated (then `[` is literal). +/// +/// A leading `!` negates and a `]` straight after `[` or `[!` is literal. Each +/// `a-b` is a range — reversed ranges match nothing — and a `-` that cannot +/// start one is literal, which reproduces `fnmatch`'s chunking. +fn parse_class(chars: &[char], start: usize) -> Option<(Token, usize)> { + let mut end = start; + if chars.get(end) == Some(&'!') { + end += 1; + } + if chars.get(end) == Some(&']') { + end += 1; + } + while chars.get(end).is_some_and(|c| *c != ']') { + end += 1; + } + if end >= chars.len() { + return None; + } + let (negated, body) = match &chars[start..end] { + ['!', body @ ..] => (true, body), + body => (false, body), + }; + let mut items = Vec::new(); + let mut k = 0; + while let Some(&c) = body.get(k) { + if let (Some('-'), Some(&high)) = (body.get(k + 1), body.get(k + 2)) { + items.push((c, high)); + k += 3; + } else { + items.push((c, c)); + k += 1; + } + } + Some((Token::Class { negated, items }, end + 1)) +} + +/// Single-character lowercase, as `re.IGNORECASE` compares. Unicode's one +/// multi-character lowercase, `İ` → `i̇`, has the simple mapping `i`, its first +/// character, which is what CPython uses. +fn simple_lower(c: char) -> char { + c.to_lowercase().next().unwrap_or(c) +} + +/// Single-character uppercase counterpart of [`simple_lower`]. +fn simple_upper(c: char) -> char { + let mut upper = c.to_uppercase(); + match (upper.next(), upper.next()) { + (Some(upper), None) => upper, + _ => c, + } +} + +/// Several parts matched against a `/`-separated path, as `glob.translate` +/// compiles the parts following `**` when symlinks are followed. +#[derive(Debug)] +struct MultiPattern(Vec); + +/// One part of a [`MultiPattern`]. +#[derive(Debug)] +enum MultiPart { + /// `**`: any number of segments — at least one when last, since the + /// regex's trailing `.*` sits after a separator. + Recursive, + /// Exactly one segment matching the pattern. + Segment(SegmentPattern), +} + +impl MultiPart { + /// Compiles one merged part. + fn compile(part: &str, case_sensitive: bool) -> Self { + if part == "**" { + Self::Recursive + } else { + Self::Segment(SegmentPattern::new(part, case_sensitive)) + } + } +} + +impl MultiPattern { + /// Whether `path` (relative, no trailing `/`) matches; dynamic programming + /// over (part, segment), so linear in each. + fn matches(&self, path: &str) -> bool { + let segments: Vec<&str> = if path.is_empty() { + Vec::new() + } else { + path.split('/').collect() + }; + let mut reachable = vec![false; segments.len() + 1]; + reachable[0] = true; + for (index, part) in self.0.iter().enumerate() { + let mut next = vec![false; segments.len() + 1]; + match part { + MultiPart::Recursive => { + let at_least_one = index + 1 == self.0.len(); + let mut any = false; + for (position, slot) in next.iter_mut().enumerate() { + if !at_least_one { + any |= reachable[position]; + } + *slot = any; + if at_least_one { + any |= reachable[position]; + } + } + } + MultiPart::Segment(pattern) => { + for (position, segment) in segments.iter().enumerate() { + if reachable[position] && pattern.matches(segment) { + next[position + 1] = true; + } + } + } + } + reachable = next; + } + reachable[segments.len()] + } +} diff --git a/crates/bashkit-monty-types/src/type_checking.rs b/crates/bashkit-monty-types/src/type_checking.rs new file mode 100644 index 000000000..0582d58ad --- /dev/null +++ b/crates/bashkit-monty-types/src/type_checking.rs @@ -0,0 +1,238 @@ +use std::{ + error::Error, + fmt::{self, Display}, + str::FromStr, +}; + +pub use ruff_python_stdlib::identifiers::is_identifier; +use serde::{Deserialize, Serialize}; +use strum::VariantNames; + +/// How type-check diagnostics are rendered into text. +/// +/// Mirrors ty's `DiagnosticFormat`. Rendering happens wherever the type checker +/// runs (inside the worker for pool sessions), because ty's structured +/// diagnostics borrow the salsa database and cannot cross a process boundary — +/// so the format has to be chosen before the check, not after it. +/// +/// Serialized into session dumps by variant name, so a rename needs +/// `#[serde(alias)]` to keep older dumps loading (see `DUMP_VERSION` in `monty`). +#[derive( + Debug, + Clone, + Copy, + Default, + PartialEq, + Eq, + Serialize, + Deserialize, + strum::Display, + strum::EnumString, + strum::VariantNames, +)] +#[strum(serialize_all = "lowercase", ascii_case_insensitive)] +pub enum TypeCheckingFormat { + /// Human-readable diagnostics with a source snippet and carets. + #[default] + Full, + /// One `path:line:col: severity[rule] message` line per diagnostic. + Concise, + /// Azure Pipelines logging commands. + Azure, + /// A JSON array of diagnostic objects. + Json, + /// One JSON diagnostic object per line. + #[strum(to_string = "jsonlines", serialize = "json-lines")] + JsonLines, + /// Reviewdog diagnostic JSON. + Rdjson, + /// Pylint-compatible output. + Pylint, + /// GitLab Code Quality report JSON. + Gitlab, + /// GitHub Actions workflow commands. + Github, +} + +impl TypeCheckingFormat { + /// Parses a format name, reporting the valid names on failure. + /// + /// Bindings take the format as a string, so the error has to be good + /// enough to show a user who guessed wrong. + pub fn from_name(name: &str) -> Result { + Self::from_str(name) + .map_err(|_| format!("unknown type check format '{name}', expected one of: {}", Self::names())) + } + + /// Comma-separated list of the accepted format names. + #[must_use] + pub fn names() -> String { + Self::VARIANTS.join(", ") + } +} + +/// How a type check renders whatever diagnostics it finds. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TypeCheckingConfig { + /// Output format. + pub format: TypeCheckingFormat, + /// Whether to include ANSI colour escapes. Only `Full` and `Concise` + /// render any colour; the machine-readable formats ignore it. + pub color: bool, +} + +/// Per-session type-check state: successfully committed snippets accumulate as +/// stubs so later snippets can reference names defined by earlier ones. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TypeCheckState { + /// User-provided stubs plus every snippet that has completed successfully. + pub committed_stubs: String, + /// The in-flight snippet; committed on success, discarded on error. + pub pending_snippet: Option, + /// How diagnostics are rendered by whoever runs the type checker. + pub config: TypeCheckingConfig, + /// Committed imports, injected before the stubs' star import to preserve bindings `.pyi` files omit. + #[serde(default)] + pub committed_imports: String, + /// Imports from `pending_snippet`, appended to `committed_imports` on commit. + #[serde(default)] + pub pending_imports: String, + /// Modules already requested from the host, including modules without stubs, to avoid asking twice. + #[serde(default)] + pub asked_modules: Vec, +} + +/// A host module's `.pyi`, written as a module or package tree for the type checker. +/// Construction validates each path component and rejects top-level names reserved by the +/// sandbox or checker, preventing stubs from shadowing their modules. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ModuleStub { + module: String, + source: String, +} + +impl ModuleStub { + /// Validates each dotted component as an identifier and rejects top-level names reserved + /// by [`validate_module_name`] or [`CHECKER_MODULE_NAMES`]. + pub fn new(module: impl Into, source: impl Into) -> Result { + let module = module.into(); + let mut parts = module.split('.'); + let top = parts.next().unwrap_or_default(); + validate_module_name(top).map_err(|_| invalid_path(&module, top))?; + if CHECKER_MODULE_NAMES.contains(&top) { + return Err(ModuleStubError::ReservedName(top.to_owned())); + } + if let Some(part) = parts.find(|part| !is_identifier(part)) { + return Err(invalid_path(&module, part)); + } + Ok(Self { + module, + source: source.into(), + }) + } + + /// The dotted module path. + #[must_use] + pub fn module(&self) -> &str { + &self.module + } + + /// The `.pyi` source. + #[must_use] + pub fn source(&self) -> &str { + &self.source + } +} + +/// Rejects non-identifiers and [`SANDBOX_MODULE_NAMES`], whose imports never reach the host. +/// [`CHECKER_MODULE_NAMES`] are valid runtime module names; only [`ModuleStub::new`] rejects them. +pub fn validate_module_name(name: &str) -> Result<(), ModuleStubError> { + if !is_identifier(name) { + Err(ModuleStubError::InvalidName(name.to_owned())) + } else if SANDBOX_MODULE_NAMES.contains(&name) { + Err(ModuleStubError::ReservedName(name.to_owned())) + } else { + Ok(()) + } +} + +/// Preserves reserved-name errors; other invalid components report the full dotted path. +fn invalid_path(path: &str, part: &str) -> ModuleStubError { + if SANDBOX_MODULE_NAMES.contains(&part) { + ModuleStubError::ReservedName(part.to_owned()) + } else { + ModuleStubError::InvalidName(path.to_owned()) + } +} + +/// An invalid or reserved host module name; see [`validate_module_name`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ModuleStubError { + /// Not a Python identifier, or a keyword. + InvalidName(String), + /// A module the sandbox provides itself, or one its type stubs rely on. + ReservedName(String), +} + +impl Display for ModuleStubError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidName(name) => write!(f, "module name {name:?} is not a valid identifier"), + Self::ReservedName(name) => write!( + f, + "module {name:?} is provided by the sandbox or its type checker and cannot be replaced" + ), + } + } +} + +impl Error for ModuleStubError {} + +/// Sandbox module names, excluding the dotted name `os.path`. +/// Imports of these modules never reach the host, so host modules cannot use these names. +/// Keep in sync with the runtime's `StandardLib`. +pub const SANDBOX_MODULE_NAMES: &[&str] = &[ + "asyncio", + "base64", + "binascii", + "bisect", + "collections", + "copy", + "csv", + "dataclasses", + "datetime", + "decimal", + "functools", + "gc", + "hashlib", + "itertools", + "json", + "math", + "os", + "pathlib", + "posixpath", + "random", + "re", + "sys", + "time", + "tomllib", + "typing", + "unicodedata", +]; + +/// Vendored typeshed modules outside [`SANDBOX_MODULE_NAMES`], including private dependencies, +/// plus ty's `ty_extensions`. Hosts may provide these modules at runtime, but +/// [`ModuleStub::new`] rejects their stubs to prevent shadowing the checker's definitions. +pub const CHECKER_MODULE_NAMES: &[&str] = &[ + "__future__", + "__main__", + "_collections_abc", + "_typeshed", + "abc", + "builtins", + "enum", + "genericpath", + "ty_extensions", + "types", + "typing_extensions", +]; diff --git a/crates/bashkit-monty-types/src/uuid.rs b/crates/bashkit-monty-types/src/uuid.rs new file mode 100644 index 000000000..981a808f0 --- /dev/null +++ b/crates/bashkit-monty-types/src/uuid.rs @@ -0,0 +1,101 @@ +//! The 16-byte UUID carried on the wire for class and instance identity. +//! +//! `MontyUuid` only stores, formats and parses ids — it never generates them. +//! Hosts generate uuid4 values (Python via the `uuid` crate, JS via `crypto`); +//! the worker generates ids for sandbox-defined classes/instances from raw entropy +//! via [`MontyUuid::from_random_bytes`]. Keeping generation out of this crate +//! leaves `monty-types` free of RNG dependencies on every target. + +use std::fmt; + +/// A 16-byte UUID identifying a host or sandbox class/instance across the +/// sandbox boundary. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +pub struct MontyUuid(#[serde(with = "serde_bytes")] [u8; 16]); + +impl MontyUuid { + /// Wraps raw bytes as-is; used when the bytes are already a valid uuid. + #[must_use] + pub const fn from_bytes(bytes: [u8; 16]) -> Self { + Self(bytes) + } + + /// Builds a deterministic id from an integer — for tests and fixtures + /// that must be reproducible; never use for real identity. + #[must_use] + pub const fn from_u128(v: u128) -> Self { + Self(v.to_be_bytes()) + } + + /// Stamps the uuid4 version and RFC 4122 variant bits over caller-supplied + /// random bytes, so any entropy source yields a well-formed uuid4. + #[must_use] + pub const fn from_random_bytes(mut bytes: [u8; 16]) -> Self { + bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4 + bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC 4122 variant + Self(bytes) + } + + /// Returns the raw bytes (big-endian field order, per RFC 4122). + #[must_use] + pub const fn as_bytes(&self) -> &[u8; 16] { + &self.0 + } + + /// Parses exactly 16 bytes; `None` for any other length. This is the + /// wire-decode entry point, so it must never panic. + #[must_use] + pub fn try_from_slice(bytes: &[u8]) -> Option { + <[u8; 16]>::try_from(bytes).ok().map(Self) + } + + /// Parses the canonical hyphenated form (`8-4-4-4-12` hex digits), any + /// case; `None` on any deviation. Used by the JS surfaces, which carry + /// uuids as strings. + #[must_use] + pub fn parse(s: &str) -> Option { + let raw = s.as_bytes(); + if raw.len() != 36 || raw[8] != b'-' || raw[13] != b'-' || raw[18] != b'-' || raw[23] != b'-' { + return None; + } + let mut bytes = [0u8; 16]; + let mut out = 0; + let mut i = 0; + while i < 36 { + if matches!(i, 8 | 13 | 18 | 23) { + i += 1; + continue; + } + let hi = hex_value(raw[i])?; + let lo = hex_value(raw[i + 1])?; + bytes[out] = (hi << 4) | lo; + out += 1; + i += 2; + } + Some(Self(bytes)) + } +} + +/// Renders the canonical hyphenated lowercase form, e.g. +/// `"0d1f3c9a-5b7e-4c21-9f8a-2e6b4d0c7a13"`. +impl fmt::Display for MontyUuid { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for (i, byte) in self.0.iter().enumerate() { + if matches!(i, 4 | 6 | 8 | 10) { + f.write_str("-")?; + } + write!(f, "{byte:02x}")?; + } + Ok(()) + } +} + +/// Decodes one ASCII hex digit; `None` for anything else. +const fn hex_value(c: u8) -> Option { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'a'..=b'f' => Some(c - b'a' + 10), + b'A'..=b'F' => Some(c - b'A' + 10), + _ => None, + } +} diff --git a/crates/bashkit-monty-types/src/virtual_path.rs b/crates/bashkit-monty-types/src/virtual_path.rs new file mode 100644 index 000000000..92745ed08 --- /dev/null +++ b/crates/bashkit-monty-types/src/virtual_path.rs @@ -0,0 +1,69 @@ +//! Lexical POSIX normalization shared by the interpreter and filesystem hosts. + +use std::borrow::Cow; + +/// Returns an absolute POSIX path with `.` removed and `..` resolved, stopping at `/`. +/// Relative inputs are rooted at `/`; this never reads the host cwd or follows symlinks. +/// Already normalized paths are borrowed. Validate NUL bytes and length limits first: +/// normalization can remove invalid components and does not provide filesystem confinement. +#[must_use] +pub fn normalize_virtual_path(path: &str) -> Cow<'_, str> { + if is_normalized(path) { + Cow::Borrowed(path) + } else { + let mut out = String::with_capacity(path.len()); + for segment in path.split('/') { + match segment { + "" | "." => {} + ".." => out.truncate(out.rfind('/').unwrap_or(0)), + segment => { + out.push('/'); + out.push_str(segment); + } + } + } + if out.is_empty() { + out.push('/'); + } + Cow::Owned(out) + } +} + +/// Checks a host-supplied working directory: absolute, POSIX, no NUL bytes. +/// +/// Trailing slashes are dropped so `os.getcwd()` never reports `/data/`; the +/// root itself stays `/`. `.` and `..` are left for the interpreter, which +/// normalizes the directory when it adopts it. The error is the message of +/// the `ValueError` hosts raise for it. +/// +/// ``` +/// use monty_types::validate_cwd; +/// +/// assert_eq!(validate_cwd("/data/").unwrap(), "/data"); +/// assert_eq!(validate_cwd("data").unwrap_err(), "cwd must be an absolute POSIX path: \"data\""); +/// ``` +pub fn validate_cwd(cwd: &str) -> Result { + if cwd.contains('\0') { + Err(format!("cwd must not contain NUL bytes: {cwd:?}")) + } else if !cwd.starts_with('/') { + Err(format!("cwd must be an absolute POSIX path: {cwd:?}")) + } else { + let trimmed = cwd.trim_end_matches('/'); + Ok(if trimmed.is_empty() { + "/".to_owned() + } else { + trimmed.to_owned() + }) + } +} + +/// Recognizes paths that can be returned without allocating or rewriting them. +fn is_normalized(path: &str) -> bool { + path == "/" + || (path.starts_with('/') + && !path.ends_with('/') + && path + .split('/') + .skip(1) + .all(|segment| !matches!(segment, "" | "." | ".."))) +} diff --git a/crates/bashkit-monty/Cargo.toml b/crates/bashkit-monty/Cargo.toml new file mode 100644 index 000000000..9eff48d5b --- /dev/null +++ b/crates/bashkit-monty/Cargo.toml @@ -0,0 +1,83 @@ +# Fork of pydantic/monty monty-1.4.0 (MIT) for bashkit's in-process Python. +# +# Important decision (security): bashkit runs many tenants' Python in one +# process. Upstream Monty enforces `max_memory` through a process-wide +# allocator counter and has no in-VM host checkpoint, so bashkit carries a +# small patch in `bashkit-monty-types` (`set_memory_probe`, pydantic/monty#740, +# and `set_checkpoint_hook`) and republishes `monty` against it. Source is +# upstream monty-1.4.0 unchanged except marked edits; the library names stay `monty` / +# `monty_types` so code reads as upstream. Drop both crates once upstream ships +# the hooks. See knowledge/runtimes/python-builtin.md. +# +# Not formatted or linted as bashkit code: kept byte-identical to upstream +# (rustfmt.toml disables formatting; a crate-level `#![allow]` in lib.rs and +# [lints] allow upstream warnings; upstream tests are not vendored). Every +# local edit is marked with a `bashkit fork:` comment. + +[package] +name = "bashkit-monty" +version.workspace = true +edition = "2024" +rust-version = "1.96" +authors = ["Samuel Colvin ", "Everruns"] +license = "MIT" +repository.workspace = true +description = "Fork of pydantic/monty 1.4.0 (secure, snapshotable Python sandbox) built against bashkit-monty-types, for bashkit's python3" +keywords = ["python", "interpreter", "sandbox", "bashkit"] +categories = ["compilers", "emulators"] +readme = "README.md" +include = ["src/**", "README.md", "LICENSE"] + +[lib] +name = "monty" +path = "src/lib.rs" +# Upstream tests are not vendored (they need the upstream tests/ tree). +test = false +doctest = false + +[dependencies] +monty-types = { package = "bashkit-monty-types", path = "../bashkit-monty-types", version = "0.20.3" } +ahash = { version = "0.8.0", features = ["serde"] } +chrono = { version = "0.4", features = ["serde"] } +fancy-regex = { version = "0.17.0" } +getrandom = { version = "0.3" } +hashbrown = { version = "0.16" } +indexmap = { version = "2" } +itertools = { version = "0.14.0" } +itoa = { version = "1" } +jiter = { version = "0.17.0", features = ["num-bigint"] } +libm = { version = "0.2" } +memchr = { version = "2.7" } +minicbor-serde = { version = "0.7", features = ["alloc"], default-features = false } +monty-macros = { version = "1.4.0" } +num-bigint = { version = "0.4", features = ["serde"] } +num-integer = { version = "0.1" } +num-traits = { version = "0.2" } +postcard = { version = "1.1", features = ["alloc"] } +ruff_python_ast = { version = "0.0.14" } +ruff_python_codegen = { version = "0.0.14" } +ruff_python_parser = { version = "0.0.14" } +ruff_python_stdlib = { version = "0.0.14" } +ruff_source_file = { version = "0.0.14" } +ruff_text_size = { version = "0.0.14" } +serde = { version = "1.0", features = ["derive", "rc"] } +serde_bytes = { version = "0.11" } +sha1 = { version = "0.11", default-features = false } +sha2 = { version = "0.11", default-features = false } +smallvec = { version = "1.13", features = ["serde", "union"] } +speedate = { version = "0.17.0" } +strum = { version = "0.27", features = ["derive", "phf"] } +unicode-general-category = { version = "1" } +unicode-normalization = { version = "0.1" } +unicode_names2 = { version = "1" } + +[features] +memory-model-checks = [] +ref-count-return = ["test-hooks"] +test-hooks = ["monty-types/test-hooks"] + +[lints.rust] +warnings = "allow" + +[lints.clippy] +all = "allow" diff --git a/crates/bashkit-monty/LICENSE b/crates/bashkit-monty/LICENSE new file mode 100644 index 000000000..d30ac52dc --- /dev/null +++ b/crates/bashkit-monty/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Pydantic Services Inc. 2026 to present + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/bashkit-monty/README.md b/crates/bashkit-monty/README.md new file mode 100644 index 000000000..7c4069a55 --- /dev/null +++ b/crates/bashkit-monty/README.md @@ -0,0 +1,167 @@ +# monty + +[![CI](https://github.com/pydantic/monty/actions/workflows/ci.yml/badge.svg)](https://github.com/pydantic/monty/actions/workflows/ci.yml?query=branch%3Amain) +[![crates.io](https://img.shields.io/crates/v/monty.svg)](https://crates.io/crates/monty) +[![license](https://img.shields.io/github/license/pydantic/monty.svg?v=2)](https://github.com/pydantic/monty/blob/main/LICENSE) + +The core interpreter crate of [Monty](https://github.com/pydantic/monty) — a secure Python sandbox written in Rust for code written by AI. + +Monty runs Python code written by an LLM without the cost, latency and complexity of a container based sandbox. It parses Python with [Ruff](https://github.com/astral-sh/ruff)'s parser and executes it on its own bytecode VM — no CPython, no FFI, no C dependencies. Startup takes microseconds, not hundreds of milliseconds. + +This crate runs the interpreter in your own process, so an abort inside it (a stack overflow, an allocator failure) takes your process with it. For untrusted code use [`monty-pool`](https://crates.io/crates/monty-pool), which runs the interpreter in worker subprocesses and replaces one that crashes. + +The sandbox has no ambient access to the host: filesystem, environment and network are only reachable through external function calls and mounts that you explicitly provide. + +This crate is the pure-Rust core. Most users want one of the bindings built on top of it: + +- **Python**: [`pydantic-monty`](https://pypi.org/project/pydantic-monty/) +- **JavaScript/TypeScript**: [`@pydantic/monty`](https://www.npmjs.com/package/@pydantic/monty) +- **CLI**: the `monty` binary from the [`monty-runtime`](https://crates.io/crates/monty-runtime) crate + +See the [documentation](https://pydantic.dev/docs/monty/) for the motivation, latency measurements, comparison to alternatives and the supported Python subset. + +## Basic usage + +`MontyRun` parses and compiles code once; `run` executes it with input values and returns the value of the final expression as a `MontyObject`: + +```rust +use monty::MontyRun; +use monty_types::{CompileOptions, ResourceTracker, MontyObject, PrintWriter, ResourceLimits}; + +let code = r#" +def fib(n): + if n <= 1: + return n + return fib(n - 1) + fib(n - 2) + +fib(x) +"#; + +let mut runner = MontyRun::new(code.to_owned(), "fib.py", vec!["x".to_owned()], CompileOptions::default()).unwrap(); +let result = runner.run(vec![MontyObject::int(10)], ResourceTracker::default(), PrintWriter::Stdout).unwrap(); +assert_eq!(result, MontyObject::int(55)); +``` + +`CompileOptions` also carries `source_scan_threshold`, the source length in bytes above which a pre-parse nesting scan runs (4 KiB by default); the docs' language limitations page describes the scan. + +Errors are returned as `MontyException`, with a traceback matching what CPython would produce. `PrintWriter` controls where `print()` output goes: `Stdout`, `Disabled`, or collected for the host to inspect — into a `String`, or into a `CollectedStreams` buffer whose `entries()` label each run `stdout` or `stderr`. + +## Resource limits + +Untrusted code shouldn't be able to hog the host. `ResourceTracker` enforces execution-time and recursion limits and configures GC scheduling. Memory limits additionally require `monty-alloc` as the executable's global allocator. + +Hosts enforce `max_suspensions`: count answered suspensions, then call `abort` on `FunctionCall`, `OsCall`, `NameLookup`, or `ResolveFutures` at the first excess. The supplied exception bypasses sandbox exception handlers: + +```rust +use std::time::Duration; +use monty::MontyRun; +use monty_types::{CompileOptions, ResourceTracker, PrintWriter, ResourceLimits}; + +let limits = ResourceLimits { + max_feed_duration: Some(Duration::from_millis(20)), + ..ResourceLimits::default() +}; + +let mut runner = MontyRun::new("while True: pass".to_owned(), "spin.py", vec![], CompileOptions::default()).unwrap(); +let err = runner.run(vec![], ResourceTracker::new(limits), PrintWriter::Stdout).unwrap_err(); +assert!(err.to_string().contains("feed time limit exceeded")); +``` + +## External functions and snapshotting + +The defining feature of the crate: instead of running to completion, `MontyRun::start` returns a `RunProgress` that pauses execution whenever the sandboxed code calls a function provided by the host. The host runs the real function (an API call, a database query, an LLM tool) and resumes with the result: + +```rust +use monty::{MontyRun, RunProgress}; +use monty_types::{CompileOptions, ResourceTracker, MontyObject, PrintWriter, ResourceLimits}; + +let code = "data = get_data(3)\ndata * 2"; +let runner = MontyRun::new(code.to_owned(), "main.py", vec!["get_data".to_owned()], CompileOptions::default()).unwrap(); + +// pass the external function in as an input +let get_data = MontyObject::function("get_data".to_owned(), None); +let progress = runner.start(vec![get_data], ResourceTracker::default(), PrintWriter::Stdout).unwrap(); + +// execution pauses at the `get_data(3)` call +let RunProgress::FunctionCall(call) = progress else { panic!("expected a function call") }; +assert_eq!(call.function_name, "get_data"); +assert_eq!(call.args.arg(0).unwrap(), MontyObject::int(3)); + +// the host computes the result and resumes +let progress = call.resume(MontyObject::int(21), PrintWriter::Stdout).unwrap(); +let RunProgress::Complete(result) = progress else { panic!("expected completion") }; +assert_eq!(result, MontyObject::int(42)); +``` + +Serialize a REPL session with `dump()` and restore it with `Dump::load()` to continue in another process or machine. +The dump includes the interpreter state and the supplied script name, type-check state and module stubs. +Loading checks the dump version: + +```rust +use monty::{Dump, MontyRepl, Session, SessionRef, dump}; +use monty_types::{CompileOptions, MontyObject, PrintWriter, ResourceTracker}; + +let mut repl = MontyRepl::new("main.py", ResourceTracker::default(), CompileOptions::default()); +repl.feed_run("x = 41", vec![], PrintWriter::Stdout).unwrap(); +let bytes = dump("main.py", None, &[], SessionRef::Idle(&repl)).unwrap(); + +// later, restore and carry on feeding +let Session::Idle(mut restored) = Dump::load(&bytes).unwrap().state else { + panic!("expected an idle session") +}; +let result = restored.feed_run("x + 1", vec![], PrintWriter::Stdout).unwrap(); +assert_eq!(result, MontyObject::int(42)); +``` + +`MontyRun` and `RunProgress` have no dump format of their own, but both implement `serde::Serialize`/`Deserialize`, so a host that wants to cache compiled code or a paused run can serialize them with whatever format it already uses. + +For both `Dump::load` and direct serde deserialization, the caller must establish that the bytes are unmodified output from a trusted, compatible Monty producer. +Monty does not authenticate snapshots or fully validate their contents. +Invalid snapshots have no correctness or availability guarantees: loading or using them may panic, abort, hang, or produce incorrect results. +Successful decoding is not evidence of authenticity or validity. + +Async host functions are supported too: `FunctionCall::resume_pending` continues execution with a pending future the sandboxed code can `await`; when all tasks are blocked, execution yields `RunProgress::ResolveFutures` for the host to supply results. When `FunctionCall::allow_eager_await` is true the call is awaited immediately and no other task can run, so a host that already has the result can pass it to `FunctionCall::resume_eager` and skip the `ResolveFutures` round trip. `OsCall::allow_eager_await` says the same of an `asyncio.sleep` the host has already waited out. + +Imports of unknown modules suspend with `OsFunctionCall::Import` and the top-level module name. +The host's answer becomes the module; dotted imports read subsequent components as attributes of that value. +Hosts usually return a host-backed class instance containing the module's attributes. +`ExtFunctionResult::NotFound`, or running without a host, raises `ModuleNotFoundError`. +The worker requests module type stubs through `OsFunctionCall::ImportStubs`; the interpreter never raises it. + +## Other pieces + +- `MontyRepl` — a REPL-style interface: feed code snippet by snippet with state persisting between snippets. +- `monty-fs` crate — mount real host directories into the sandbox at virtual paths (read-write, read-only, or copy-on-write in-memory overlay), with path resolution hardened against escapes. +- `RunProgress::OsCall` — filesystem and other `os`-level operations the host can intercept or delegate. +- `FunctionCall::object_id` and `NameLookup::object_id` identify the host receiver for routed calls and lookups, + including class construction via `__call__`. + Plain calls and lookups carry `None`. +- Every suspension carries a `SourceRange` (`FunctionCall::position`, `OsCall::position`, `NameLookup::position`, + `ResolveFutures::position()`) locating the suspending expression: the call, the name, or the `await` the main task is + blocked on. +- `MontyRun::with_os_policy` / `MontyRepl::with_os_policy` configure clocks, sleeps and initial random state on every + execution path. + `DateTimeSource` selects the system clock, a fixed instant or the host; `SandboxTimeZone` independently selects UTC, a + fixed offset and name, or an IANA zone (`SandboxTimeZone::named`, resolved from the tz database that `monty-types`' + `tzdb` or `tzdb-bundled` feature provides). + `SleepMode` selects capped system sleeps, a host handler or no wait; `RandomStart` selects OS entropy, a seed with + `random.seed()` semantics or host entropy. + Defaults use the system clock, UTC and OS entropy, with sleeps capped at ten seconds. + System sleeps suspend for the host to wait without its `os` handler; standard execution waits inline. + `CallHost` delegates to the host through `RunProgress::OsCall`. + +## Monty crates + +- [`monty`](https://crates.io/crates/monty) — the core interpreter: Python parser, bytecode VM, and sandbox. **this crate** +- [`monty-types`](https://crates.io/crates/monty-types) — the shared boundary data types (values, exceptions, OS calls, resource limits) hosts use without linking the interpreter. +- [`monty-fs`](https://crates.io/crates/monty-fs) — host-side filesystem mounts: maps virtual sandbox paths to real host directories. +- [`monty-runtime`](https://crates.io/crates/monty-runtime) — the `monty` binary: REPL, file runner, and subprocess worker mode. +- [`monty-pool`](https://crates.io/crates/monty-pool) — an elastic pool of crash-isolated `monty` worker subprocesses. +- [`monty-proto`](https://crates.io/crates/monty-proto) — the protobuf wire protocol spoken between pool parents and workers. +- [`monty-type-checking`](https://crates.io/crates/monty-type-checking) — type checking of sandboxed code, powered by [ty](https://docs.astral.sh/ty/). +- [`monty-typeshed`](https://crates.io/crates/monty-typeshed) — the trimmed typeshed stubs describing the stdlib subset Monty implements. +- [`monty-macros`](https://crates.io/crates/monty-macros) — the proc macros behind `monty`'s argument parsing. + +## License + +MIT diff --git a/crates/bashkit-monty/rustfmt.toml b/crates/bashkit-monty/rustfmt.toml new file mode 100644 index 000000000..582ae19f4 --- /dev/null +++ b/crates/bashkit-monty/rustfmt.toml @@ -0,0 +1,2 @@ +# Upstream source, kept byte-identical: never reformat. +disable_all_formatting = true diff --git a/crates/bashkit-monty/src/args/bind_native.rs b/crates/bashkit-monty/src/args/bind_native.rs new file mode 100644 index 000000000..6857a66c5 --- /dev/null +++ b/crates/bashkit-monty/src/args/bind_native.rs @@ -0,0 +1,722 @@ +//! Runtime argument binder for *native* (Rust-implemented) callables, +//! driving `#[derive(FromArgs)]`. +//! +//! The derive macro emits a `static` [`ParamSpec`] describing the signature +//! and calls [`bind`], which does *all* of the dispatch work — arity +//! pre-checks, positional slot filling, kwarg matching, duplicate/conflict +//! detection, unknown-kwarg handling, `*args` / `**kwargs` collection, and +//! refcount cleanup on every error path — as ordinary, debuggable Rust. +//! Generated code is left with only the parts that must be compile-time: +//! per-field [`FromValue`](super::FromValue) conversions, default +//! expressions, and the final struct build. +//! +//! User-defined Python functions are bound by the sibling +//! [`bind_python`](super::bind_python) module instead. The two binders are +//! deliberately separate (different param representations, outputs, and +//! error families), but [`ErrorFamily::Def`] here MUST stay behaviourally +//! identical to `Signature::bind` — same kwargs-before-overflow ordering, +//! same wording, same `(and N keyword-only argument(s))` counting. When +//! changing `def` semantics in either file, change both; coverage lives in +//! `test_cases/args__macro_errors.py` and +//! `test_cases/function__arity_defaults.py`. +//! +//! No type conversion happens here: `bind` fills raw [`Value`] slots +//! ([`Bound`], in place) and the generated code drains them in declaration order via +//! [`Bound::require`] / [`Bound::take`], finishing with [`Bound::finish`]. +//! That split is deliberate — it reproduces CPython's error orderings, which +//! differ per parser family (see [`ErrorFamily`]): the `def`/clinic/unpack +//! families detect *all* binding errors before any converter runs, while the +//! `PyArg_ParseTupleAndKeywords` families interleave missing errors with +//! conversion parameter-by-parameter and report leftover kwargs (conflicts, +//! unknowns) last — hence the deferred state on [`Bound`] raised by +//! [`Bound::finish`]. + +use std::{mem, ptr}; + +use crate::{ + args::{ArgPosIter, ArgValues, KwargsValues, KwargsValuesIter}, + bytecode::VM, + defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{ContainsHeap, DropWithContext}, + intern::{Interns, StaticStrings}, + value::{EitherStr, Value}, +}; + +/// Bind positional and keyword arguments into `bound`'s raw [`Value`] slots +/// per its spec, enforcing the spec's family arity/conflict/unknown-kwarg +/// ordering. +/// +/// Fills in place rather than returning a `Bound` so the (potentially large) +/// slot struct is never moved by value: the generated code allocates it once +/// inside its `DropGuard`-protected slots struct, and that caller guard also +/// owns cleanup of everything bound so far — on error, `bind` guarantees each +/// argument was either stored in `bound` or dropped with the heap, never +/// leaked in between. +/// +/// The purely-positional 0/1/2-argument shapes — the overwhelming majority of +/// real calls — take a fast path that fills the slots directly: with no kwargs +/// and the count inside `n_required_positional..=n_positional`, *no* check in +/// the slow path can fire (every pre-check needs kwargs or an out-of-range +/// count, the derive guarantees required positional params precede defaulted +/// ones — so the first `n` slots are exactly the ones a valid call fills — +/// and the derive rejects required `kw_only` fields, so skipping the +/// aggregated missing-keyword check is safe). Keeping this function +/// `#[inline]` lets the shape dispatch fold into each derive's call site +/// while `bind_slow` stays outlined. +#[inline] +pub(crate) fn bind( + spec: &'static ParamSpec, + bound: &mut Bound, + args: ArgValues, + vm: &mut VM<'_>, +) -> RunResult<()> { + // `spec` is passed explicitly (despite living in `bound` too) so the + // inlined fast-path conditions constant-fold against the caller's + // `static` instead of loading through the guard-wrapped `bound`. + debug_assert!(ptr::eq(spec, bound.spec), "spec must match the bound's spec"); + let args = match args { + ArgValues::Empty if spec.n_required_positional == 0 => { + return Ok(()); + } + ArgValues::One(v) if spec.n_required_positional <= 1 && spec.n_positional >= 1 => { + bound.slots[0] = Some(v); + return Ok(()); + } + ArgValues::Two(v1, v2) if spec.n_required_positional <= 2 && spec.n_positional >= 2 => { + bound.slots[0] = Some(v1); + bound.slots[1] = Some(v2); + return Ok(()); + } + other => other, + }; + bind_slow(spec, bound, args, vm) +} + +/// The general binding path: iterators, a cleanup guard, kwarg dispatch, and +/// every family pre-check. See [`bind`] for the contract. +fn bind_slow( + spec: &'static ParamSpec, + bound: &mut Bound, + args: ArgValues, + vm: &mut VM<'_>, +) -> RunResult<()> { + let (pos, kwargs) = args.into_parts(); + let state = IterState { + pos, + kwargs: kwargs.into_iter(), + }; + // The guard drains both argument iterators on any `return Err(...)`; + // values already moved into `bound` are covered by the *caller's* guard + // around the slots struct, so no error arm needs manual drops beyond + // values it has already pulled out of an iterator. + defer_drop_mut!(state, vm); + + if spec.kwargs_not_supported_yet && state.kwargs.len() > 0 { + return Err(ExcType::kwargs_not_implemented(spec.func_name)); + } + + let n_pos = state.pos.len(); + let n_kw = state.kwargs.len(); + + // Family pre-checks. Order matches CPython: `PyArg_UnpackTuple` callers + // reject keywords wholesale (`_PyArg_NoKeywords` / the `METH_FASTCALL` + // dispatch) before any arity check, then check the positional range; + // `at_most_total` reproduces the `PyArg_ParseTupleAndKeywords` total + // pre-count; the "at least M positional" check reproduces + // `_PyArg_UnpackKeywords` for C methods whose required positional-only + // params cannot be filled by keyword. + if matches!(spec.family, ErrorFamily::Unpack | ErrorFamily::ParseTuple) { + if n_kw > 0 { + let name = spec.kwarg_error_name.unwrap_or(spec.func_name); + return Err(ExcType::type_error_no_kwargs(name)); + } + if let Some(err) = unpack_arity_error(spec, n_pos) { + return Err(err); + } + } + // `tp_vectorcall` fast paths (`int`, `str`) check positional arity with + // `_PyArg_CheckPositional` before reaching the clinic parser, so kwarg-free + // overflow gets the un-parenthesised wording; with kwargs present the + // `at_most_total` check below fires with the clinic wording instead. + if spec.vectorcall && n_kw == 0 && n_pos > spec.n_positional { + return Err(ExcType::type_error_at_most(spec.func_name, spec.n_positional, n_pos)); + } + if spec.at_most_total && n_pos + n_kw > spec.params.len() { + return Err(total_overflow_error(spec, n_pos, n_kw)); + } + if spec.uses_c_method_arity() && n_pos < spec.n_required_pos_only { + // The exact form outranks "at least" when every positional slot is + // required, even though these are positional-only — CPython counts + // the slots, not how they may be passed. + return Err(if spec.uses_exact_positional_arity() { + ExcType::type_error_named_positional(spec.func_name, spec.n_positional, n_pos, true) + } else { + ExcType::type_error_at_least_positional(spec.func_name, spec.n_required_pos_only, n_pos) + }); + } + + // Positional overflow: every C parser checks arity before touching kwargs, + // but pure-Python `def` binding processes keyword arguments first — its + // unexpected-kwarg and multiple-values errors beat too-many-positional — + // so for `Def` the check is deferred to after the kwarg loop below. + let positional_overflow = n_pos > spec.n_positional && !spec.varargs; + if positional_overflow && !matches!(spec.family, ErrorFamily::Def) { + return Err(positional_overflow_error(spec, n_pos, n_kw)); + } + for slot in bound.slots.iter_mut().take(n_pos.min(spec.n_positional)) { + *slot = state.pos.next(); + } + // On (deferred) overflow without `*args` the excess stays in the iterator; + // the guard drains it when the overflow error returns below. + if spec.varargs { + bound.varargs.extend(state.pos.by_ref()); + } + + for (key, value) in state.kwargs.by_ref() { + let Some(key_str) = key.as_either_str(vm.heap) else { + (key, value).drop_with(vm); + return Err(ExcType::type_error_kwargs_nonstring_key()); + }; + match find_param(spec, &key_str, vm.interns) { + Some((_, param)) if matches!(param.kind, ParamKind::PosOnly) => { + (key, value).drop_with(vm); + return Err(ExcType::type_error_positional_only(spec.func_name, param.name)); + } + Some((idx, param)) => { + key.drop_with(vm); + if bound.slots[idx].is_some() { + value.drop_with(vm); + match duplicate_error(spec, idx, param) { + DuplicateOutcome::Raise(err) => return Err(err), + // C families treat a kwarg naming an already-positional + // param as a *leftover*, reported by the final sweep + // (`finish`) — every missing/conversion error beats it, + // and among several conflicts CPython reports the + // earliest parameter (verified against 3.14). + DuplicateOutcome::Defer(err) => { + let deferred = bound.deferred_mut(); + if deferred.conflict.as_ref().is_none_or(|(ci, _)| idx < *ci) { + deferred.conflict = Some((idx, err)); + } + } + } + } else { + bound.slots[idx] = Some(value); + } + } + None if spec.varkwargs => { + // The key is already known to be a string (`as_either_str` + // succeeded above) — keep it as a `Value` so runtime-built + // heap strings (e.g. `dict(**{k: 1})`) work, not just + // interned ids. + bound.varkwargs.push((key, value)); + } + None if spec.family.defers_unknown_kwarg() => { + // C families raise unknown-kwarg *last* (after every missing, + // conversion, and conflict error); stash the first for `finish`. + value.drop_with(vm); + if bound.deferred.as_ref().is_none_or(|d| d.unknown.is_none()) { + let err = match spec.family { + ErrorFamily::C { .. } => ExcType::type_error_c_unexpected_keyword(key_str.as_str(vm.interns)), + _ => ExcType::type_error_unexpected_keyword(spec.func_name, key_str.as_str(vm.interns)), + }; + bound.deferred_mut().unknown = Some(err); + } + key.drop_with(vm); + } + None => { + value.drop_with(vm); + let name = key_str.as_str(vm.interns).to_owned(); + key.drop_with(vm); + let err_name = spec.kwarg_error_name.unwrap_or(spec.func_name); + return Err(ExcType::type_error_unexpected_keyword(err_name, &name)); + } + } + } + + // The deferred `def` overflow: every kwarg bound cleanly, so report + // too-many-positional with CPython's `(and N keyword-only argument(s))` + // suffix, N = keyword-only slots *filled by the call* (CPython's + // `too_many_positional` scans localsplus before defaults are applied). + if positional_overflow { + let kwonly_given = bound.slots[spec.n_positional..].iter().filter(|s| s.is_some()).count(); + return Err(ExcType::type_error_too_many_positional_range( + spec.func_name, + spec.n_required_positional, + spec.n_positional, + n_pos, + kwonly_given, + )); + } + + // `def`/clinic/unpack report every missing required name in one aggregated + // error, positional names first — before any conversion runs, exactly like + // CPython's `def` binding and `_PyArg_UnpackKeywords`. The C families skip + // this: their missing errors surface per-parameter from `Bound::require`, + // interleaved with conversion, matching `vgetargskeywords`. + if spec.family.aggregates_missing() { + let missing = missing_names(spec, &bound.slots, 0, spec.n_positional); + if !missing.is_empty() { + return Err(ExcType::type_error_missing_positional_with_names( + spec.func_name, + &missing, + )); + } + let missing = missing_names(spec, &bound.slots, spec.n_positional, N); + if !missing.is_empty() { + return Err(ExcType::type_error_missing_kwonly_with_names(spec.func_name, &missing)); + } + } + + // Both iterators are exhausted; the guard has nothing left to drain. + Ok(()) +} + +/// Compile-time description of one `FromArgs` signature, generated as a +/// `static` by the derive and interpreted by [`bind`]. +#[expect(clippy::struct_excessive_bools, reason = "mirrors independent signature axes")] +pub(crate) struct ParamSpec { + /// Function name embedded in error messages (the `{name}()` prefix). + pub func_name: &'static str, + pub family: ErrorFamily, + /// Named params in declaration order — `[pos_only..][pos_or_kw..][kw_only..]`. + /// The index into this slice is also the slot index in [`Bound`]. + pub params: &'static [Param], + /// Count of `PosOnly` + `PosOrKeyword` params (the positional slot prefix). + pub n_positional: usize, + /// Count of positional params without defaults. + pub n_required_positional: usize, + /// Count of required `PosOnly` params — non-zero switches the non-`def` + /// families onto CPython's C-method `_PyArg_UnpackKeywords` arity wording + /// (required positional-only args cannot be filled by keyword). + pub n_required_pos_only: usize, + /// `*args` — excess positionals are collected instead of erroring. + pub varargs: bool, + /// `**kwargs` — unmatched kwargs are collected instead of erroring. + pub varkwargs: bool, + /// Pre-count `positional + kwarg` against all named slots before dispatch, + /// reproducing `PyArg_ParseTupleAndKeywords`' total pre-check. Set per + /// function from CPython's observed behaviour — not derivable from the + /// field shapes (identical signatures differ by parser generation). + pub at_most_total: bool, + /// Kwarg-free positional overflow uses `_PyArg_CheckPositional` wording + /// (`{name} expected at most N arguments, got M`) — models `tp_vectorcall` + /// fast paths (`int`, `str`) that bypass the clinic parser when no + /// keywords are passed. Requires `at_most_total` (enforced by the derive). + pub vectorcall: bool, + /// Reject any kwarg up front with `NotImplementedError` — a Monty TODO + /// marker for functions whose CPython kwargs aren't plumbed through yet. + pub kwargs_not_supported_yet: bool, + /// Override for the function name in the unknown-kwarg error only + /// (`json.dumps` reports `JSONEncoder.__init__`). + pub kwarg_error_name: Option<&'static str>, +} + +impl ParamSpec { + /// True when required positional-only params switch the arity wording to + /// CPython's C-method form (`{name}() takes at least/most N positional + /// arguments (M given)`). `def` keeps pure-Python wording even for + /// required pos-only params (e.g. `json.loads(s, /)`); `unpack` has its + /// own range pre-check. + fn uses_c_method_arity(&self) -> bool { + self.n_required_pos_only > 0 && !matches!(self.family, ErrorFamily::Def | ErrorFamily::Unpack) + } + + /// True when `_PyArg_UnpackKeywords` words arity as `takes exactly N + /// positional argument(s)`: a named C parser whose positional slots are + /// every one required and followed by keyword-only params + /// (`binascii.b2a_base64`, `os.stat`). + fn uses_exact_positional_arity(&self) -> bool { + matches!(self.family, ErrorFamily::CNamed { positional_pivot: true }) + && self.n_required_positional == self.n_positional + } +} + +/// One named parameter slot of a [`ParamSpec`]. +pub(crate) struct Param { + pub name: &'static str, + /// Executor-independent identity used for keyword matching. + pub keyword_name: Option, + pub kind: ParamKind, + /// True when the param has no default. + pub required: bool, +} + +/// Role of a named parameter. `*args` / `**kwargs` are spec-level flags, not +/// params — they own no slot. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum ParamKind { + PosOnly, + PosOrKeyword, + KwOnly, +} + +/// CPython argument-parser family. Selects both the error *wording* and the +/// error *ordering* [`bind`] and [`Bound`] enforce; the derive's `style` +/// attribute maps onto this 1:1 (with `C`'s pivot computed from the fields). +#[derive(Clone, Copy)] +pub(crate) enum ErrorFamily { + /// Pure-Python `def` binding (`style = def`). Too-many-positional counts + /// positionals only and appends CPython's `(and N keyword-only + /// argument(s))` suffix; all binding errors fire before the function body + /// (i.e. before any conversion) — unknown kwargs immediately, missing + /// names aggregated. + Def, + /// Argument Clinic `_PyArg_UnpackKeywords` (the default style). Binding + /// errors fire before converters run: unknown kwargs and positional/keyword + /// conflicts (`argument for {name}() given by name and position`) + /// immediately, missing names aggregated; required positional-only params + /// add the C-method "at least/at most N positional" wording. + Clinic, + /// `PyArg_ParseTupleAndKeywords` with no name in the format string — + /// errors say `function takes …` / `this function got …`. Per-parameter + /// ordering: missing → convert for each param in order; kwargs that name + /// an already-positional param (conflicts) and unknown kwargs are both + /// *leftovers*, raised last by [`Bound::finish`] — conflicts (earliest + /// param) before unknowns, matching `vgetargskeywords`' final sweep. + /// `positional_pivot` is computed by the derive (any `kw_only` field + /// present) and switches the overflow wording to `… positional arguments …` + /// with CPython's pivot back to the total count once the overflow exceeds + /// all slots. + C { positional_pivot: bool }, + /// Like [`ErrorFamily::C`] but the C source embeds the function name + /// (`:name` in the format string) — errors say `{name}() …`, and the + /// unknown-kwarg error uses the named Python wording. + /// + /// `positional_pivot` mirrors [`ErrorFamily::C`]'s: computed by the derive + /// (any `kw_only` field present) and switches the overflow wording to + /// `… exactly/at most N positional argument(s) …`, pivoting back to the + /// total count once the overflow exceeds all slots (e.g. `os.stat`). + CNamed { positional_pivot: bool }, + /// `PyArg_ParseTuple` with a `:name` and no keyword support (`style = parse_tuple`). + /// Same order as [`ErrorFamily::Unpack`] — keywords rejected wholesale, then a + /// fixed positional `min..max` range — but worded `{name}() takes at + /// least/most N argument(s) (M given)` (`time.gmtime`, `time.strftime`). + ParseTuple, + /// `PyArg_UnpackTuple` (`style = unpack`): any keyword argument is + /// rejected first with `{name}() takes no keyword arguments` (CPython's + /// `_PyArg_NoKeywords` / `METH_FASTCALL` dispatch), then a fixed + /// positional `min..max` range is checked, `{name} expected …` wording + /// with no parentheses. When `min == max` CPython collapses to + /// `expected N argument(s)` — [`bind`] does the same. + Unpack, +} + +impl ErrorFamily { + /// C families raise unknown-kwarg after every missing/conversion error. + fn defers_unknown_kwarg(self) -> bool { + matches!(self, Self::C { .. } | Self::CNamed { .. }) + } + + /// Non-C families aggregate all missing required names into one error at + /// the end of [`bind`]; C families report per-param via [`Bound::require`]. + fn aggregates_missing(self) -> bool { + !matches!(self, Self::C { .. } | Self::CNamed { .. }) + } +} + +/// Raw bound arguments: the output of [`bind`], consumed by generated code. +/// +/// Holds heap references — every slot must be drained (via +/// [`require`](Self::require) / [`take`](Self::take) / +/// [`take_varargs`](Self::take_varargs) / [`take_varkwargs`](Self::take_varkwargs)) +/// or the whole value dropped with the heap. Generated code embeds it in the +/// guarded slots struct so both happen automatically. +pub(crate) struct Bound { + spec: &'static ParamSpec, + slots: [Option; N], + varargs: Vec, + varkwargs: Vec<(Value, Value)>, + /// C families only: leftover-kwarg errors raised by [`finish`](Self::finish). + /// Boxed because `RunError` is large and `Bound` is moved by value through + /// the generated code — the common no-leftover call pays one niche'd word. + deferred: Option>, +} + +/// C-family leftover kwargs recorded during [`bind`], reported by +/// [`Bound::finish`] only after every missing/conversion error has had its +/// chance — matching `vgetargskeywords`' final sweep, where a conflict +/// (earliest parameter) beats an unknown kwarg. +#[derive(Default)] +struct DeferredLeftovers { + /// Earliest-param positional/keyword conflict. + conflict: Option<(usize, RunError)>, + /// First unknown kwarg (in call order). + unknown: Option, +} + +impl Bound { + /// Empty slots for `spec`, ready for [`bind`]. Called by generated code + /// when building its guarded slots struct; `N` must equal + /// `spec.params.len()` (the derive guarantees this). + pub(crate) fn new(spec: &'static ParamSpec) -> Self { + debug_assert_eq!(N, spec.params.len(), "slot count must match spec params"); + Self { + spec, + slots: [const { None }; N], + varargs: Vec::new(), + varkwargs: Vec::new(), + deferred: None, + } + } + + /// The deferred-leftovers slot, allocated on first use (C families only). + fn deferred_mut(&mut self) -> &mut DeferredLeftovers { + self.deferred.get_or_insert_default() + } + + /// Take required param `i`, raising the family's missing-required error if + /// absent. For the aggregating families the missing case is unreachable — + /// [`bind`] already checked — so this only genuinely errors for `C`/`CNamed`. + pub(crate) fn require(&mut self, i: usize) -> RunResult { + match self.slots[i].take() { + Some(v) => Ok(v), + None => Err(self.missing_error(i)), + } + } + + /// Take optional param `i` (`None` = absent, caller applies the default). + pub(crate) fn take(&mut self, i: usize) -> Option { + self.slots[i].take() + } + + /// Take the collected `*args` values. + pub(crate) fn take_varargs(&mut self) -> Vec { + mem::take(&mut self.varargs) + } + + /// Take the collected `**kwargs`, collapsing empty to `KwargsValues::Empty` + /// so callers get cheap emptiness checks. + pub(crate) fn take_varkwargs(&mut self) -> KwargsValues { + if self.varkwargs.is_empty() { + KwargsValues::Empty + } else { + KwargsValues::Pairs(mem::take(&mut self.varkwargs)) + } + } + + /// Raise the deferred C-family leftover-kwarg error, if any: the earliest- + /// param conflict first, then the first unknown kwarg. Generated code + /// calls this after every param has been required/taken, matching + /// `vgetargskeywords`' final leftover sweep (every missing and conversion + /// error beats a leftover). No-op for the other families, which raised + /// immediately during [`bind`]. + pub(crate) fn finish(&mut self) -> RunResult<()> { + match self.deferred.take() { + None => Ok(()), + Some(deferred) => match *deferred { + DeferredLeftovers { + conflict: Some((_, err)), + .. + } => Err(err), + DeferredLeftovers { unknown: Some(err), .. } => Err(err), + DeferredLeftovers { + conflict: None, + unknown: None, + } => Ok(()), + }, + } + } + + /// Family-worded missing-required error for param `i`. + #[cold] + fn missing_error(&self, i: usize) -> RunError { + let param = &self.spec.params[i]; + match self.spec.family { + ErrorFamily::C { .. } if i < self.spec.n_positional => { + ExcType::type_error_c_missing_required(param.name, i + 1) + } + ErrorFamily::CNamed { .. } if i < self.spec.n_positional => { + ExcType::type_error_c_missing_required_named(self.spec.func_name, param.name, i + 1) + } + ErrorFamily::C { .. } | ErrorFamily::CNamed { .. } => { + ExcType::type_error_missing_kwonly_with_names(self.spec.func_name, &[param.name]) + } + // Aggregating families: bind() already raised; a required slot the + // macro asks for is guaranteed filled. Emit the matching wording + // anyway rather than panicking. + _ => ExcType::type_error_missing_positional_with_names(self.spec.func_name, &[param.name]), + } + } +} + +impl DropWithContext for Bound { + fn drop_with(self, heap: &mut C) { + for slot in self.slots { + slot.drop_with(heap); + } + self.varargs.drop_with(heap); + for (k, v) in self.varkwargs { + k.drop_with(heap); + v.drop_with(heap); + } + } +} + +/// The partially-consumed argument iterators [`bind_slow`] owns mid-flight, +/// guarded so both are drained on every error path (already-bound values are +/// covered by the caller's guard around the slots struct). +struct IterState { + pos: ArgPosIter, + kwargs: KwargsValuesIter, +} + +impl DropWithContext for IterState { + fn drop_with(self, heap: &mut C) { + self.pos.drop_with(heap); + self.kwargs.drop_with(heap); + } +} + +/// Finds the parameter named by a keyword in declaration order. +/// +/// Plain positional-only parameters have no keyword identity and do not match. +fn find_param<'s>(spec: &'s ParamSpec, key: &EitherStr, interns: &Interns) -> Option<(usize, &'s Param)> { + let name = key.static_string(interns)?; + spec.params + .iter() + .enumerate() + .find(|(_, param)| param.keyword_name == Some(name)) +} + +/// How a duplicate (slot already filled) kwarg should be reported. +enum DuplicateOutcome { + /// Raise immediately during bind (`def`/clinic/unpack, and all keyword-only + /// duplicates — those can only arise from pathological `**` merges). + Raise(RunError), + /// C families: record as a leftover, raised by [`Bound::finish`]. + Defer(RunError), +} + +/// Build the family-worded duplicate/conflict error for param `idx`. +/// `def` uses pure-Python binding's `got multiple values for argument`; +/// clinic uses `_PyArg_UnpackKeywords`' immediate `argument for {name}() +/// given by name and position` (verified against CPython 3.14 — +/// `'a'.encode(42, encoding='x')` reports the conflict, not the bad type); +/// the C families defer the same wording to the leftover sweep. +#[cold] +fn duplicate_error(spec: &ParamSpec, idx: usize, param: &Param) -> DuplicateOutcome { + if matches!(param.kind, ParamKind::KwOnly) { + return DuplicateOutcome::Raise(ExcType::type_error_multiple_values(spec.func_name, param.name)); + } + let named_conflict = + || ExcType::type_error_positional_keyword_conflict(&format!("{}()", spec.func_name), param.name, idx + 1); + match spec.family { + ErrorFamily::C { .. } => DuplicateOutcome::Defer(ExcType::type_error_positional_keyword_conflict( + "function", + param.name, + idx + 1, + )), + ErrorFamily::CNamed { .. } => DuplicateOutcome::Defer(named_conflict()), + ErrorFamily::Clinic => DuplicateOutcome::Raise(named_conflict()), + // `Unpack`/`ParseTuple` accept no keywords, so they never get here. + ErrorFamily::Def | ErrorFamily::Unpack | ErrorFamily::ParseTuple => { + DuplicateOutcome::Raise(ExcType::type_error_duplicate_arg(spec.func_name, param.name)) + } + } +} + +/// `PyArg_UnpackTuple` range check: too few / too many positionals, with the +/// `expected N` collapse when `min == max` (exactly CPython's behaviour). +#[cold] +fn unpack_arity_error(spec: &ParamSpec, n_pos: usize) -> Option { + let (min, max) = (spec.n_required_positional, spec.n_positional); + let parse_tuple = matches!(spec.family, ErrorFamily::ParseTuple); + // Both parsers collapse a fixed arity to "exactly"; they differ only in wording. + if n_pos < min { + Some(match (parse_tuple, min == max) { + (true, true) => ExcType::type_error_method_exact(spec.func_name, min, n_pos), + (true, false) => ExcType::type_error_method_at_least(spec.func_name, min, n_pos), + (false, true) => ExcType::type_error_expected_exact(spec.func_name, min, n_pos), + (false, false) => ExcType::type_error_at_least(spec.func_name, min, n_pos), + }) + } else if n_pos > max { + Some(match (parse_tuple, min == max) { + (true, true) => ExcType::type_error_method_exact(spec.func_name, max, n_pos), + (true, false) => ExcType::type_error_method_at_most(spec.func_name, max, n_pos, false), + (false, true) => ExcType::type_error_expected_exact(spec.func_name, max, n_pos), + (false, false) => ExcType::type_error_at_most(spec.func_name, max, n_pos), + }) + } else { + None + } +} + +/// `at_most_total` pre-count error: `PyArg_ParseTupleAndKeywords`' total-count +/// wording for the C families, the parenthesised method form otherwise. +/// +/// The named families pivot to `keyword argument` when the call passed no +/// positionals — the only overflow site that can see `n_pos == 0`. +#[cold] +fn total_overflow_error(spec: &ParamSpec, n_pos: usize, n_kw: usize) -> RunError { + let total = n_pos + n_kw; + match spec.family { + ErrorFamily::C { .. } => ExcType::type_error_c_at_most(spec.params.len(), total), + // Clinic / CNamed (`def`/`unpack` reject the flag at derive time). + _ => ExcType::type_error_method_at_most(spec.func_name, spec.params.len(), total, n_pos == 0), + } +} + +/// Too-many-positional error for the non-`def` families without `*args`, +/// folding the kwarg count into the reported total (matching the C parsers' +/// "(M given)" figure). `def` never reaches here — its overflow is deferred +/// past the kwarg loop and worded inline in [`bind_slow`]. +#[cold] +fn positional_overflow_error(spec: &ParamSpec, n_pos: usize, n_kw: usize) -> RunError { + let max = spec.n_positional; + match spec.family { + // Unreachable: `def` defers, and the positional-only pre-check already + // covered both directions. Match their wording anyway rather than panicking. + ErrorFamily::ParseTuple => ExcType::type_error_method_at_most(spec.func_name, max, n_pos, false), + ErrorFamily::Def | ErrorFamily::Unpack => ExcType::type_error_at_most(spec.func_name, max, n_pos), + // The exact form again outranks the generic C-method wording for + // required positional-only slots; the total-count fallback below still + // applies once the overflow exceeds every slot. + ErrorFamily::CNamed { positional_pivot: true } + if spec.uses_exact_positional_arity() && n_pos + n_kw <= spec.params.len() => + { + ExcType::type_error_named_positional(spec.func_name, max, n_pos, true) + } + _ if spec.uses_c_method_arity() => ExcType::type_error_method_at_most(spec.func_name, max, n_pos + n_kw, false), + ErrorFamily::C { + positional_pivot: false, + } => ExcType::type_error_c_at_most(max, n_pos + n_kw), + // CPython pivots from "M positional arguments" back to "M_total + // arguments" once the overflow exceeds positional + kw-only slots. + ErrorFamily::C { positional_pivot: true } => { + ExcType::type_error_c_at_most_positional_or_total(max, spec.params.len(), n_pos + n_kw) + } + ErrorFamily::CNamed { + positional_pivot: false, + } => ExcType::type_error_method_at_most(spec.func_name, max, n_pos + n_kw, false), + // Same pivot as `C`, but named: `_PyArg_UnpackKeywords` says "exactly" + // when every positional param is required (`os.stat`), "at most" when + // some have defaults (`os.mkdir`), and falls back to the total-count + // wording once the overflow exceeds positional + kw-only slots. The + // positional wordings count only positionals in "(M given)" + // (`stat('.', 1, dir_fd=None)` reports 2, not 3); the total-count + // fallback counts everything — both verified against CPython 3.14. + ErrorFamily::CNamed { positional_pivot: true } => { + let total = n_pos + n_kw; + if total > spec.params.len() { + ExcType::type_error_method_at_most(spec.func_name, spec.params.len(), total, false) + } else { + let exact = spec.n_required_positional == spec.n_positional; + ExcType::type_error_named_positional(spec.func_name, max, n_pos, exact) + } + } + ErrorFamily::Clinic => ExcType::type_error_at_most(spec.func_name, max, n_pos + n_kw), + } +} + +/// Collect the names of required-but-unfilled params in `start..end` (the +/// positional prefix or the keyword-only tail) for the aggregated missing errors. +fn missing_names(spec: &ParamSpec, slots: &[Option], start: usize, end: usize) -> Vec<&'static str> { + spec.params[start..end] + .iter() + .zip(&slots[start..end]) + .filter(|(p, slot)| p.required && slot.is_none()) + .map(|(p, _)| p.name) + .collect() +} diff --git a/crates/bashkit-monty/src/args/bind_python.rs b/crates/bashkit-monty/src/args/bind_python.rs new file mode 100644 index 000000000..cf7ef45c2 --- /dev/null +++ b/crates/bashkit-monty/src/args/bind_python.rs @@ -0,0 +1,689 @@ +//! Signature representation and argument binding for user-defined *Python* +//! functions (`def` / `lambda`). +//! +//! This module handles Python function signatures including all parameter types: +//! positional-only, positional-or-keyword, *args, keyword-only, and **kwargs. +//! It also handles default values and the argument binding algorithm. +//! +//! Native (Rust-implemented) callables are bound by the sibling +//! [`bind_native`](super::bind_native) module instead. The two binders are +//! deliberately separate (different param representations, outputs, and +//! error families), but [`Signature::bind`] MUST stay behaviourally +//! identical to `bind_native`'s `ErrorFamily::Def` path — same +//! kwargs-before-overflow ordering, same wording, same `(and N keyword-only +//! argument(s))` counting. When changing `def` semantics in either file, +//! change both; coverage lives in `test_cases/function__arity_defaults.py` +//! and `test_cases/args__macro_errors.py`. + +use std::cell::OnceCell; + +use crate::{ + args::{ArgPosIter, ArgValues}, + bytecode::VM, + defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunResult, SimpleException}, + expressions::Identifier, + heap::{DropGuard, DropWithContext, HeapData}, + intern::{Interns, StringId}, + resource_checks::check_estimated_size, + types::{Dict, allocate_tuple}, + value::{VALUE_SIZE, Value}, +}; + +/// Represents a Python function signature with all parameter types. +/// +/// A complete Python signature can include: +/// - Positional-only parameters (before `/`) +/// - Positional-or-keyword parameters (regular parameters) +/// - Variable positional parameter (`*args`) +/// - Keyword-only parameters (after `*` or `*args`) +/// - Variable keyword parameter (`**kwargs`) +/// +/// # Default Values +/// +/// Default values are tracked by count per parameter group. The `*_defaults_count` fields +/// indicate how many parameters (from the end of each group) have defaults. For example, +/// if `args = [a, b, c]` and `arg_defaults_count = 2`, then `b` and `c` have defaults. +/// +/// Note: The actual default Values are evaluated at function definition time and stored +/// separately (in the heap as part of the function/closure object). This struct only +/// tracks the structure, not the values themselves. +/// +/// # Namespace Layout +/// +/// Parameters are laid out in the namespace in this order: +/// ```text +/// [pos_args][args][*args_slot?][kwargs][**kwargs_slot?] +/// ``` +/// The `*args` slot is only present if `var_args` is Some. +/// The `**kwargs` slot is only present if `var_kwargs` is Some. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub(crate) struct Signature { + /// Positional-only parameters, e.g. `a, b` in `def f(a, b, /): ...` + /// + /// These can only be passed by position, not by keyword. + #[serde(rename = "P")] + pos_args: Option>, + + /// Number of positional-only parameters with defaults (from the end). + #[serde(rename = "Q")] + pos_defaults_count: usize, + + /// Positional-or-keyword parameters, e.g. `a, b` in `def f(a, b): ...` + /// + /// These can be passed either by position or by keyword. + #[serde(rename = "A")] + args: Option>, + + /// Number of positional-or-keyword parameters with defaults (from the end). + #[serde(rename = "B")] + arg_defaults_count: usize, + + /// Variable positional parameter name, e.g. `args` in `def f(*args): ...` + /// + /// Collects excess positional arguments into a tuple. + #[serde(rename = "V")] + var_args: Option, + + /// Keyword-only parameters, e.g. `c` in `def f(*, c): ...` or `def f(*args, c): ...` + /// + /// These can only be passed by keyword, not by position. + #[serde(rename = "K")] + kwargs: Option>, + + /// Mapping from each keyword-only parameter to its default index (if any). + /// + /// Each entry corresponds to the same index in `kwargs`. A value of `Some(i)` + /// points into the kwarg section of the defaults array, while `None` means + /// the parameter is required. + #[serde(rename = "M")] + kwarg_default_map: Option>>, + + /// Variable keyword parameter name, e.g. `kwargs` in `def f(**kwargs): ...` + /// + /// Collects excess keyword arguments into a dict. + #[serde(rename = "W")] + var_kwargs: Option, + + /// How simple the signature is, used for the fast path when binding. + /// + /// Derived from the other fields and cached lazily via [`Self::bind_mode`] + /// rather than serialized: never storing a computed value on the wire + /// means a signature loaded from an older REPL dump can't ever carry a + /// `BindMode` stale with respect to the derivation logic in the binary + /// that loads it. + #[serde(skip)] + bind_mode: OnceCell, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BindMode { + /// If this is a simple signature (no defaults, no *args/**kwargs). + /// + /// Simple signatures can use a fast path for argument binding that avoids + /// the full binding algorithm overhead. A simple signature has: + /// - No positional-only parameters + /// - No defaults for any parameters + /// - No *args or **kwargs + /// - No keyword-only parameters + Simple, + /// If this signature has only positional-or-keyword params with defaults. + /// + /// This identifies the common pattern `def f(a, b=1, c=2)` where: + /// - No positional-only parameters + /// - No *args or **kwargs + /// - No keyword-only parameters + /// - Has some default values + /// + /// These signatures can use a simplified binding that just fills positional + /// args and applies defaults without the full algorithm overhead. + SimpleWithDefaults, + Complex, +} + +impl Signature { + /// Returns the parameter count when positional arguments need no binding. + /// + /// With no defaults, variadic slots, or keyword-only parameters, positional + /// arguments already have the namespace layout produced by [`Self::bind`]. + pub(crate) fn exact_positional_count(&self) -> Option { + (self.pos_defaults_count == 0 + && self.arg_defaults_count == 0 + && self.var_args.is_none() + && self.kwargs.is_none() + && self.var_kwargs.is_none()) + .then(|| self.param_count()) + } + + /// Creates a full signature with all parameter types. + /// + /// # Arguments + /// * `pos_args` - Positional-only parameter names + /// * `pos_defaults_count` - Number of pos_args with defaults (from end) + /// * `args` - Positional-or-keyword parameter names + /// * `arg_defaults_count` - Number of args with defaults (from end) + /// * `var_args` - Variable positional parameter name (*args) + /// * `kwargs` - Keyword-only parameter names + /// * `kwarg_default_map` - Mapping of kw-only parameters to default indices + /// * `var_kwargs` - Variable keyword parameter name (**kwargs) + #[expect(clippy::too_many_arguments)] + pub fn new( + pos_args: Vec, + pos_defaults_count: usize, + args: Vec, + arg_defaults_count: usize, + var_args: Option, + kwargs: Vec, + kwarg_default_map: Vec>, + var_kwargs: Option, + ) -> Self { + let pos_args = if pos_args.is_empty() { None } else { Some(pos_args) }; + let has_kwonly = !kwargs.is_empty(); + let kwargs = if has_kwonly { Some(kwargs) } else { None }; + + Self { + pos_args, + pos_defaults_count, + args: if args.is_empty() { None } else { Some(args) }, + arg_defaults_count, + var_args, + kwargs, + kwarg_default_map: if has_kwonly { Some(kwarg_default_map) } else { None }, + var_kwargs, + bind_mode: OnceCell::new(), + } + } + + /// Returns the signature's [`BindMode`], deriving and caching it on first use. + fn bind_mode(&self) -> BindMode { + *self.bind_mode.get_or_init(|| self.derive_bind_mode()) + } + + /// Derives [`BindMode`] from the signature's parameter fields. + fn derive_bind_mode(&self) -> BindMode { + if self.pos_args.is_none() + && self.pos_defaults_count == 0 + && self.arg_defaults_count == 0 + && self.var_args.is_none() + && self.kwargs.is_none() + && self.var_kwargs.is_none() + { + BindMode::Simple + } else if self.pos_args.is_none() + && self.var_args.is_none() + && self.kwargs.is_none() + && self.var_kwargs.is_none() + && self.arg_defaults_count > 0 + { + BindMode::SimpleWithDefaults + } else { + BindMode::Complex + } + } + + /// Binds arguments to parameters according to Python's calling conventions. + /// + /// This implements the full argument binding algorithm: + /// 1. Bind positional args to pos_args, then args (in order) + /// 2. Bind keyword args to args and kwargs (NOT pos_args - positional-only) + /// 3. Collect excess positional args into *args tuple + /// 4. Collect excess keyword args into **kwargs dict + /// 5. Apply defaults for missing parameters + /// + /// Returns a Vec ready to be injected into the namespace, laid out as: + /// `[pos_args][args][*args_slot?][kwargs][**kwargs_slot?]` + /// + /// # Arguments + /// * `args` - The arguments from the call site + /// * `defaults` - Evaluated default values (layout: pos_defaults, arg_defaults, kwarg_defaults) + /// * `heap` - The heap for allocating *args tuple and **kwargs dict + /// * `interns` - For looking up parameter names in error messages + /// * `func_name` - Function name for error messages + /// * `namespace` - The namespace to populate with bound arguments. This is mutated in place and will need to be cleaned up on error. + /// + /// # Errors + /// Returns an error if: + /// - Too few or too many positional arguments + /// - Missing required keyword-only arguments + /// - Unexpected keyword argument + /// - Positional-only parameter passed as keyword + /// - Same argument passed both positionally and by keyword + pub fn bind( + &self, + args: ArgValues, + defaults: &[Value], + vm: &mut VM<'_>, + func_name: Identifier, + namespace: &mut Vec, + ) -> RunResult<()> { + let (pos_iter, keyword_args) = args.into_parts(); + let n_kwargs = keyword_args.len(); + let namespace_base = namespace.len(); + + // Fast path for simple signatures (no special params) and signatures + // with only positional-or-keyword params and defaults, when no keyword + // arguments are passed. Handled before building the kwargs iterator + + // guard below, which are pure overhead in this common positional case. + if n_kwargs == 0 && matches!(self.bind_mode(), BindMode::Simple | BindMode::SimpleWithDefaults) { + // No keyword arguments to bind; the empty container holds no refs. + keyword_args.drop_with(vm); + match pos_iter { + ArgPosIter::Empty => {} + ArgPosIter::One(a) => { + namespace.push(a); + } + ArgPosIter::Two([a1, a2]) => { + namespace.push(a1); + namespace.push(a2); + } + ArgPosIter::Vec(args) => { + namespace.extend(args); + } + } + + let actual_count = namespace.len() - namespace_base; + let param_count = self.param_count(); + + if actual_count == param_count { + // Exact match - no defaults needed + return Ok(()); + } else if self.bind_mode() == BindMode::SimpleWithDefaults { + let required = self.required_positional_count(); + if actual_count >= required && actual_count < param_count { + // Apply defaults for remaining parameters + // Defaults are stored at the end of the defaults array for pos-or-kw params + let defaults_needed = param_count - actual_count; + let defaults_start = self.arg_defaults_count - defaults_needed; + for i in 0..defaults_needed { + namespace.push(defaults[defaults_start + i].clone_with_heap(vm)); + } + return Ok(()); + } + } + + return self.wrong_arg_count_error(actual_count, vm.interns, func_name); + } + + // Full binding algorithm for complex signatures or kwargs. Convert + // kwargs to an iterator and guard it so remaining items are cleaned up + // on any error path. + let keyword_args = keyword_args.into_iter(); + defer_drop_mut!(keyword_args, vm); + + // Keep unconsumed positional values guarded throughout binding. + defer_drop_mut!(pos_iter, vm); + + // Calculate how many positional params we have + let pos_param_count = self.pos_arg_count(); + let arg_param_count = self.arg_count(); + let total_positional_params = pos_param_count + arg_param_count; + + // Too many positionals? Noted here but raised only *after* the keyword + // loop: CPython binds keyword arguments first, so unexpected-kwarg and + // multiple-values errors beat too-many-positional. + let positional_count = pos_iter.len(); + let positional_overflow = self.max_positional_count().is_some_and(|max| positional_count > max); + + // `Undefined` is internal-only, so each namespace slot also records whether + // its parameter was bound. Layout: [pos_args][args][*args?][kwargs][**kwargs?] + let var_args_offset = usize::from(self.var_args.is_some()); + namespace.resize_with(namespace.len() + self.total_slots(), || Value::Undefined); + + // 1. Bind positional args to pos_args, then args + + // Bind to pos_args + for slot in namespace[namespace_base..].iter_mut().take(pos_param_count) { + if let Some(val) = pos_iter.next() { + *slot = val; + } + } + + // Bind to args + for slot in namespace[namespace_base..] + .iter_mut() + .take(total_positional_params) + .skip(pos_param_count) + { + if let Some(val) = pos_iter.next() { + *slot = val; + } + } + + // 2. Collect excess positional args into *args tuple. Without `*args` + // any excess (the deferred overflow) stays in `pos_iter`, drained by + // its guard when the overflow error returns below. + if self.var_args.is_some() { + // Preflight the rounded-up reservation, not the length: `TupleVec` is a + // `SmallVec` whose `extend` rounds up to the next power of two. Unchecked, + // `f(*t)` on a big tuple clears the hard-limit headroom in one allocation. + let slots = pos_iter.len().checked_next_power_of_two().unwrap_or(usize::MAX); + check_estimated_size(slots.saturating_mul(VALUE_SIZE), &vm.heap.tracker)?; + namespace[namespace_base + total_positional_params] = allocate_tuple(pos_iter.collect(), vm.heap); + } + + // 3. Bind keyword args + // Bind keywords to args and kwargs (not pos_args - those are positional-only) + let mut excess_kwargs_guard = DropGuard::new(self.var_kwargs.is_some().then(Dict::new), vm); + let (excess_kwargs, vm) = excess_kwargs_guard.as_parts_mut(); + + 'kwargs: for (key, value) in keyword_args { + // Guard key: dropped on most paths, consumed into **kwargs via into_parts(). + let mut key_guard = DropGuard::new(key, vm); + let (key, vm) = key_guard.as_parts_mut(); + + // Guard value: consumed into namespace/excess_kwargs via into_inner(), + // or dropped automatically on error paths. + let mut value_guard = DropGuard::new(value, vm); + let vm = value_guard.ctx(); + + let Some(keyword_name) = key.as_either_str(vm.heap) else { + return Err(ExcType::type_error("keywords must be strings")); + }; + + // Check if this keyword matches a positional-only param (error) + if let Some(pos_args) = &self.pos_args + && let Some(¶m_id) = pos_args + .iter() + .find(|&¶m_id| keyword_name.matches(param_id, vm.interns)) + { + let func = vm.interns.get_str(func_name.name_id); + let param = vm.interns.get_str(param_id); + return Err(ExcType::type_error_positional_only(func, param)); + } + + // Try positional-or-keyword params + if let Some(args) = &self.args { + for (i, ¶m_id) in args.iter().enumerate() { + if keyword_name.matches(param_id, vm.interns) { + let ns_idx = pos_param_count + i; + if !matches!(namespace[namespace_base + ns_idx], Value::Undefined) { + let func = vm.interns.get_str(func_name.name_id); + let param = vm.interns.get_str(param_id); + return Err(ExcType::type_error_duplicate_arg(func, param)); + } + let (value, _) = value_guard.into_parts(); + namespace[namespace_base + ns_idx] = value; + continue 'kwargs; + } + } + } + + // Try keyword-only params + if let Some(kwargs) = &self.kwargs { + for (i, ¶m_id) in kwargs.iter().enumerate() { + if keyword_name.matches(param_id, vm.interns) { + let ns_idx = total_positional_params + var_args_offset + i; + if !matches!(namespace[namespace_base + ns_idx], Value::Undefined) { + let func = vm.interns.get_str(func_name.name_id); + let param = vm.interns.get_str(param_id); + return Err(ExcType::type_error_duplicate_arg(func, param)); + } + let (value, _) = value_guard.into_parts(); + namespace[namespace_base + ns_idx] = value; + continue 'kwargs; + } + } + } + + if let Some(excess_kwargs) = excess_kwargs { + // Consume both value and key into **kwargs dict + let (value, _) = value_guard.into_parts(); + let (key, vm) = key_guard.into_parts(); + excess_kwargs.set(key, value, vm)?; + continue 'kwargs; + } + + let func = vm.interns.get_str(func_name.name_id); + let key_str = keyword_name.as_str(vm.interns); + return Err(ExcType::type_error_unexpected_keyword(func, key_str)); + } + + // 3.4. Raise the deferred too-many-positional error now that every + // kwarg has bound (or errored). CPython reports the range form when + // some positional params have defaults, plus an `(and N keyword-only + // argument(s))` suffix counting only the kw-only params *bound by the + // call* — defaults have not been applied yet, exactly as in CPython's + // `too_many_positional`. + if positional_overflow { + let kwonly_given = (0..self.kwarg_count()) + .filter(|&i| { + !matches!( + namespace[namespace_base + total_positional_params + var_args_offset + i], + Value::Undefined + ) + }) + .count(); + let func = vm.interns.get_str(func_name.name_id); + return Err(ExcType::type_error_too_many_positional_range( + func, + self.required_positional_count(), + total_positional_params, + positional_count, + kwonly_given, + )); + } + + // 3.5. Apply default values to unbound optional parameters + // Defaults layout: [pos_defaults...][arg_defaults...][kwarg_defaults...] + // Each section only contains defaults for params that have them. + let mut default_idx = 0; + + // Apply pos_args defaults (optional params at the end of pos_args) + if self.pos_defaults_count > 0 { + let first_optional = pos_param_count - self.pos_defaults_count; + for i in first_optional..pos_param_count { + if matches!(namespace[namespace_base + i], Value::Undefined) { + namespace[namespace_base + i] = defaults[default_idx + (i - first_optional)].clone_with_heap(vm); + } + } + } + default_idx += self.pos_defaults_count; + + // Apply args defaults (optional params at the end of args) + if self.arg_defaults_count > 0 { + let first_optional = arg_param_count - self.arg_defaults_count; + for i in first_optional..arg_param_count { + let ns_idx = pos_param_count + i; + if matches!(namespace[namespace_base + ns_idx], Value::Undefined) { + namespace[namespace_base + ns_idx] = + defaults[default_idx + (i - first_optional)].clone_with_heap(vm); + } + } + } + default_idx += self.arg_defaults_count; + + // Apply kwargs defaults using the explicit default map + if let Some(ref default_map) = self.kwarg_default_map { + for (i, default_slot) in default_map.iter().enumerate() { + if let Some(slot_idx) = default_slot { + // Skip past *args slot if present + let ns_idx = total_positional_params + var_args_offset + i; + if matches!(namespace[namespace_base + ns_idx], Value::Undefined) { + namespace[namespace_base + ns_idx] = defaults[default_idx + slot_idx].clone_with_heap(vm); + } + } + } + } + + // 4. Check that all required params are bound BEFORE building final namespace. + // This ensures we can clean up properly on error without leaking heap values. + + // Check required positional params (pos_args + required args) + let mut missing_positional: Vec<&str> = Vec::new(); + + // Check pos_args + if let Some(ref pos_args) = self.pos_args { + let required_pos_only = pos_args.len().saturating_sub(self.pos_defaults_count); + for (i, ¶m_id) in pos_args.iter().enumerate() { + if i < required_pos_only && matches!(namespace[namespace_base + i], Value::Undefined) { + missing_positional.push(vm.interns.get_str(param_id)); + } + } + } + + // Check args (positional-or-keyword) + if let Some(ref args_params) = self.args { + let required_args = args_params.len().saturating_sub(self.arg_defaults_count); + for (i, ¶m_id) in args_params.iter().enumerate() { + if i < required_args && matches!(namespace[namespace_base + pos_param_count + i], Value::Undefined) { + missing_positional.push(vm.interns.get_str(param_id)); + } + } + } + + if !missing_positional.is_empty() { + // Clean up bound values before returning error + let func = vm.interns.get_str(func_name.name_id); + return Err(ExcType::type_error_missing_positional_with_names( + func, + &missing_positional, + )); + } + + // Check required keyword-only args + let mut missing_kwonly: Vec<&str> = Vec::new(); + if let Some(ref kwargs_params) = self.kwargs { + let default_map = self.kwarg_default_map.as_ref(); + for (i, ¶m_id) in kwargs_params.iter().enumerate() { + let has_default = default_map.and_then(|map| map.get(i)).is_some_and(Option::is_some); + let ns_idx = total_positional_params + var_args_offset + i; + if !has_default && matches!(namespace[namespace_base + ns_idx], Value::Undefined) { + missing_kwonly.push(vm.interns.get_str(param_id)); + } + } + } + + if !missing_kwonly.is_empty() { + let func = vm.interns.get_str(func_name.name_id); + return Err(ExcType::type_error_missing_kwonly_with_names(func, &missing_kwonly)); + } + + // 5. Insert **kwargs dict if present (at the last slot) + // Namespace layout: [pos_args][args][*args?][kwargs][**kwargs?] + let (excess_kwargs, vm) = excess_kwargs_guard.into_parts(); + if let Some(excess_kwargs) = excess_kwargs { + let dict_id = vm.heap.allocate(HeapData::Dict(excess_kwargs)); + let last_slot = namespace.len() - 1; + namespace[last_slot] = Value::Ref(dict_id); + } + + Ok(()) + } + + /// Returns the total number of named parameters (excluding *args/**kwargs slots). + /// + /// This is `pos_args.len() + args.len() + kwargs.len()`. + pub fn param_count(&self) -> usize { + self.pos_arg_count() + self.arg_count() + self.kwarg_count() + } + + /// Returns the total number of namespace slots needed for parameters. + /// + /// This includes slots for: + /// - All named parameters (pos_args + args + kwargs) + /// - The *args tuple (if var_args is Some) + /// - The **kwargs dict (if var_kwargs is Some) + pub fn total_slots(&self) -> usize { + let mut slots = self.param_count(); + if self.var_args.is_some() { + slots += 1; + } + if self.var_kwargs.is_some() { + slots += 1; + } + slots + } + + /// Returns the total number of default values across all parameter groups. + pub fn total_defaults_count(&self) -> usize { + self.pos_defaults_count + self.arg_defaults_count + self.kwarg_defaults_count() + } + + /// Returns the minimum number of positional arguments required. + /// + /// This is the total positional param count minus the number of defaults. + /// For a signature like `def f(a, b, c=1)`, this returns 2 (a and b are required). + #[inline] + fn required_positional_count(&self) -> usize { + self.pos_arg_count() + self.arg_count() - self.pos_defaults_count - self.arg_defaults_count + } + + fn kwarg_defaults_count(&self) -> usize { + self.kwarg_default_map + .as_deref() + .map(|v| v.iter().filter(|&x| x.is_some()).count()) + .unwrap_or_default() + } + + /// Returns the number of positional-only parameters. + fn pos_arg_count(&self) -> usize { + self.pos_args.as_ref().map_or(0, Vec::len) + } + + /// Returns the number of positional-or-keyword parameters. + fn arg_count(&self) -> usize { + self.args.as_ref().map_or(0, Vec::len) + } + + /// Returns the number of keyword-only parameters. + fn kwarg_count(&self) -> usize { + self.kwargs.as_ref().map_or(0, Vec::len) + } + + /// Returns parameter names in the slot order filled by `bind`: + /// positional-only, positional-or-keyword, `*args`, keyword-only, `**kwargs`. + pub(crate) fn param_names(&self) -> impl Iterator + '_ { + let pos_args = self.pos_args.iter().flat_map(|v| v.iter().copied()); + let args = self.args.iter().flat_map(|v| v.iter().copied()); + let var_args = self.var_args.iter().copied(); + let kwargs = self.kwargs.iter().flat_map(|v| v.iter().copied()); + let var_kwargs = self.var_kwargs.iter().copied(); + + pos_args.chain(args).chain(var_args).chain(kwargs).chain(var_kwargs) + } + + /// Returns the maximum number of positional arguments accepted. + /// + /// Returns None if *args is present (unlimited positional args). + fn max_positional_count(&self) -> Option { + if self.var_args.is_some() { + None + } else { + Some(self.pos_arg_count() + self.arg_count()) + } + } + + /// Creates an error for wrong number of arguments. + /// + /// Handles both "missing required positional arguments" and "too many arguments" cases, + /// formatting the error message to match CPython's style. + /// + /// # Arguments + /// * `actual_count` - Number of arguments actually provided + /// * `interns` - String storage for looking up interned names + fn wrong_arg_count_error(&self, actual_count: usize, interns: &Interns, func_name: Identifier) -> RunResult { + let name_str = interns.get_str(func_name.name_id); + let param_count = self.param_count(); + // Only reached from the Simple/SimpleWithDefaults fast paths, so there + // are no pos-only, kw-only, or `*args` params: every param is + // positional-or-keyword and `param_count` is the positional maximum. + let required = self.required_positional_count(); + let msg = if actual_count < required { + // Missing arguments — CPython lists only the *required* params not + // yet provided (params with defaults are never "missing"). + let missing_names: Vec = self + .param_names() + .take(required) + .skip(actual_count) + .map(|string_id| interns.get_str(string_id).to_string()) + .collect(); + let missing_refs: Vec<&str> = missing_names.iter().map(String::as_str).collect(); + ExcType::missing_positional_msg(name_str, &missing_refs) + } else { + ExcType::too_many_positional_range_msg(name_str, required, param_count, actual_count, 0) + }; + Err(SimpleException::new_msg(ExcType::TypeError, msg) + .with_position(func_name.position) + .into()) + } +} diff --git a/crates/bashkit-monty/src/args/from_value.rs b/crates/bashkit-monty/src/args/from_value.rs new file mode 100644 index 000000000..e0359df34 --- /dev/null +++ b/crates/bashkit-monty/src/args/from_value.rs @@ -0,0 +1,447 @@ +//! Trait + impls for coercing a Python `Value` into a Rust type during +//! argument extraction. +//! +//! Companion to the `#[derive(FromArgs)]` macro in `monty-macros`. The derive +//! generates code that calls [`FromValue::extract_into`] for every positional +//! or keyword argument. The trait owns the cleanup of the input `Value` — +//! constrained impls drop the input, the identity impl for `Value` and the +//! owning [`StrArg`] keep it. Generated callers also need to drop +//! already-extracted owning fields on later error paths; for that they call +//! [`FromValue::drop_extracted`], which knows whether the extracted form holds +//! a heap reference. +//! +//! Failures are structured ([`FromValueFail`]) so the *kind* of failure is +//! reported by the impl rather than re-derived from error messages: +//! `WrongType` lets the extraction site pick CPython's wording, `Raise` +//! surfaces a fully-formed error unchanged. + +use std::borrow::Cow; + +use num_bigint::{BigInt, Sign}; +use num_traits::ToPrimitive; + +use crate::{ + bytecode::VM, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{ContainsHeap, DropWithContext, HeapData}, + types::PyTrait, + value::Value, +}; + +/// Error-wording selection for [`FromValue::extract_into`]. Built as a literal +/// by `#[derive(FromArgs)]` at each extraction site to pick how a +/// [`FromValueFail::WrongType`] failure is reported, mirroring CPython's +/// `_PyArg_BadArgument` variants. +pub(crate) enum ArgErrCtx { + /// No per-site wording: use the impl's [`FromValue::type_error`]. + Plain, + /// Positional form: `{func_name}() argument {pos} must be {expected}, not {got}`. + BadArgPos { func_name: &'static str, pos: usize }, + /// Named form: `{func_name}() argument '{arg_name}' must be {expected}, not {got}`. + BadArgNamed { + func_name: &'static str, + arg_name: &'static str, + }, +} + +/// A failed [`FromValue`] coercion, split by *why* it failed so extraction +/// sites never have to reverse-engineer the reason from an error message. +pub(crate) enum FromValueFail { + /// The input value's type is unacceptable. Deliberately carries no + /// [`Type`]: the input has already been dropped by the time the failure + /// is reported, so a `Type::Instance` derived from it could dangle. + /// [`extract_into`](FromValue::extract_into) names the offending type + /// from a snapshot taken *before* the coercion ran; the extraction site + /// owns the wording — the per-site `_PyArg_BadArgument` forms + /// ([`ArgErrCtx`]) or the impl's [`FromValue::type_error`]. + WrongType, + /// The type was acceptable but the value was not (`ValueError`, + /// `OverflowError`, resource errors, …). Surfaces unchanged — never + /// rewritten into a type error. + Raise(RunError), +} + +/// Coerces a `Value` into `Self` during `#[derive(FromArgs)]` argument +/// extraction, consuming the value and handling refcount cleanup on both +/// success and failure paths. +/// +/// **Only use `FromValue`-typed fields for functions that are implemented in +/// C in CPython** (builtins and extension modules, where CPython's argument +/// clinic type-checks each argument *while binding* it). Functions that are +/// pure-Python `def`s in CPython (`style = def` structs — the `re` module, +/// `json.dumps`/`loads`, …) must declare fields as raw `Value` and coerce in +/// the function body instead: CPython `def` binding never type-checks, so a +/// coercion failure at extraction time would wrongly preempt later binding +/// errors such as missing arguments or unexpected kwargs. +/// +/// Implementations *must* consume the input on every path: either drop it +/// (`drop_with`) once any needed data has been read out, or transfer +/// ownership into `Self` (the identity `Value` impl, [`StrArg`]) — in which +/// case [`drop_extracted`](Self::drop_extracted) must release it. +pub(crate) trait FromValue: Sized { + /// CPython "must be X" type label used by `_PyArg_BadArgument`-style + /// error messages ("argument N must be {EXPECTED_TYPE_NAME}, not {Y}"). + /// + /// `Some("str")`, `Some("int")`, etc. for impls that constrain their input; + /// `None` for the identity `Value` impl (which accepts any value). Read by + /// [`extract_into`](Self::extract_into) when the struct sets + /// [`bad_arg`](../../monty_macros/struct.FromArgs.html) — see + /// `crates/monty-macros/README.md`. + /// + /// Impls that wrap another `FromValue` (e.g. `Option`) forward this + /// from the inner type by default; override if you need different wording + /// (e.g. `"str or None"`). + const EXPECTED_TYPE_NAME: Option<&'static str> = None; + + /// Convert a `Value` into `Self`. On error, the input value must have + /// been dropped before returning. + /// + /// Takes `&mut VM` so impls can both inspect the heap (for type coercion) + /// and call `drop_with` on the input; this also lets `LaxBool` route + /// through `PyTrait::py_bool`. + fn from_value(value: Value, vm: &mut VM<'_>) -> Result; + + /// The error for a [`FromValueFail::WrongType`] failure at a site with no + /// `_PyArg_BadArgument` wording ([`ArgErrCtx::Plain`], `*args` elements). + /// `got` is the offending type's CPython arg-error name (e.g. `'Foo'` for + /// a user-class instance), snapshotted before the value was consumed. + /// + /// The default is a generic `expected {EXPECTED_TYPE_NAME}, not {got}`; + /// impls whose wrong-type error can actually surface through a `Plain` + /// site should override it with the exact CPython message their callers + /// produce (e.g. the int impls' `'{got}' object cannot be interpreted as + /// an integer`). + fn type_error(got: &str) -> RunError { + let expected = Self::EXPECTED_TYPE_NAME.unwrap_or("a different type"); + ExcType::type_error(format!("expected {expected}, not {got}")) + } + + /// Drop the *extracted* value (i.e. `Self`) so refcounts stay balanced + /// when generated `from_args` code aborts after extracting one field but + /// before completing the struct. + /// + /// For primitives this is a no-op; for `Value` / [`StrArg`] it decrements + /// the held reference. + fn drop_extracted(self, heap: &mut impl ContainsHeap) { + // Default: no heap references held. Specialise in impls that hold them. + let _ = heap; + drop(self); + } + + /// Coerce `value` into `Self` and store it in `slot`, applying `ctx`'s + /// CPython `_PyArg_BadArgument` wording to `WrongType` failures. + /// + /// This is what `#[derive(FromArgs)]` calls for every positional/keyword + /// argument. Centralising it here — rather than inlining the equivalent + /// tokens at each derive's call sites — keeps the generated code small: the + /// body is monomorphised once per field type and shared across all derives. + /// On error the input `value` has already been dropped by `from_value`; the + /// caller remains responsible for draining the argument iterators. + /// + /// [`FromValueFail::Raise`] errors surface unchanged, so an impl can + /// report a failure that is not a type mismatch — e.g. the int impls + /// raise `OverflowError` for out-of-range ints — without that error being + /// clobbered into a bogus "must be int, not int". Use `Raise` only for + /// checks CPython performs *during* argument conversion; validation + /// CPython does in the function body belongs in the body (see + /// `NormForm::parse` in `unicodedata.rs`). + fn extract_into(value: Value, slot: &mut Option, vm: &mut VM<'_>, ctx: ArgErrCtx) -> RunResult<()> { + // Capture both names before conversion can free the instance's class; + // they borrow only the interner, never the heap. `_PyArg_BadArgument` + // names `None` by value, the plain `type_error` fallback by type. + let got = Self::EXPECTED_TYPE_NAME.map(|_| { + let got_type = value.py_type_heap(vm.heap); + ( + got_type.cpython_arg_name(vm.heap, vm.interns), + got_type.name(vm.heap, vm.interns), + ) + }); + match Self::from_value(value, vm) { + Ok(extracted) => { + *slot = Some(extracted); + Ok(()) + } + Err(FromValueFail::Raise(err)) => Err(err), + Err(FromValueFail::WrongType) => { + // `WrongType` is only reported by impls with an + // `EXPECTED_TYPE_NAME`, so the snapshot is always present; + // "object" keeps that unreachable arm honest without a panic. + let (arg_name, got) = got.unwrap_or((Cow::Borrowed("object"), Cow::Borrowed("object"))); + Err(match (ctx, Self::EXPECTED_TYPE_NAME) { + (ArgErrCtx::BadArgPos { func_name, pos }, Some(expected)) => { + ExcType::type_error_bad_arg_pos(func_name, pos, expected, arg_name) + } + ( + ArgErrCtx::BadArgNamed { + func_name, + arg_name: name, + }, + Some(expected), + ) => ExcType::type_error_bad_arg_named(func_name, name, expected, arg_name), + _ => Self::type_error(&got), + }) + } + } + } +} + +impl FromValue for Value { + fn from_value(value: Self, _vm: &mut VM<'_>) -> Result { + Ok(value) + } + + fn drop_extracted(self, heap: &mut impl ContainsHeap) { + self.drop_with(heap); + } +} + +impl FromValue for i32 { + const EXPECTED_TYPE_NAME: Option<&'static str> = Some("int"); + + fn from_value(value: Value, vm: &mut VM<'_>) -> Result { + let value = resolve_index_dunder(value, vm)?; + let result = match value { + Value::Bool(b) => Ok(Self::from(b)), + // Overflow is a *value* failure: the argument is a genuine int, + // so a bad-arg rewrite ("must be int, not int") would be wrong. + // CPython's `i` format range-checks with sign-aware wording. + Value::Int(i) => Self::try_from(i).map_err(|_| { + let msg = if i < 0 { + "signed integer is less than minimum" + } else { + "signed integer is greater than maximum" + }; + FromValueFail::Raise(SimpleException::new_msg(ExcType::OverflowError, msg).into()) + }), + _ if is_long_int(&value, vm) => Err(FromValueFail::Raise(ExcType::overflow_c_long())), + _ => Err(FromValueFail::WrongType), + }; + value.drop_with(vm); + result + } + + fn type_error(got: &str) -> RunError { + ExcType::type_error_not_integer(got) + } +} + +impl FromValue for i64 { + const EXPECTED_TYPE_NAME: Option<&'static str> = Some("int"); + + fn from_value(value: Value, vm: &mut VM<'_>) -> Result { + let value = resolve_index_dunder(value, vm)?; + let result = match value { + Value::Bool(b) => Ok(Self::from(b)), + Value::Int(i) => Ok(i), + _ if is_long_int(&value, vm) => Err(FromValueFail::Raise(ExcType::overflow_c_long())), + _ => Err(FromValueFail::WrongType), + }; + value.drop_with(vm); + result + } + + fn type_error(got: &str) -> RunError { + ExcType::type_error_not_integer(got) + } +} + +/// Replaces a value with the `int` the `__index__` protocol produces, leaving +/// anything not `__index__`-able untouched. +/// +/// Runs before the fixed-width int impls match, so they only ever see real ints +/// — the `PyNumber_Index` step CPython's `i`/`n` argument converters perform. An +/// int answers with an equal int, and a class without `__index__` is returned +/// unchanged, so the caller still reports its own `WrongType`. +fn resolve_index_dunder(value: Value, vm: &mut VM<'_>) -> Result { + match value.py_index_impl(vm) { + Ok(Some(index)) => { + value.drop_with(vm); + Ok(index) + } + Ok(None) => Ok(value), + Err(err) => { + value.drop_with(vm); + Err(FromValueFail::Raise(err)) + } + } +} + +/// True when `value` is a Python int wider than i64 (heap or interned +/// `LongInt`). Such values are genuine ints, so fixed-width int impls +/// must raise `OverflowError` rather than report `WrongType` — a bad-arg +/// rewrite would produce the absurd "must be int, not int". Also used by +/// consumer-specific int impls (e.g. `timedelta`'s component extraction). +pub(crate) fn is_long_int(value: &Value, vm: &VM<'_>) -> bool { + long_int(value, vm).is_some() +} + +/// The big integer behind an `int` too wide for `Value::Int`, if that is +/// what `value` is; the one lookup for every C-width converter. +pub(crate) fn long_int<'a>(value: &'a Value, vm: &'a VM<'_>) -> Option<&'a BigInt> { + match value { + Value::InternLongInt(id) => Some(vm.interns.get_long_int(*id)), + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::LongInt(big) => Some(big.inner()), + _ => None, + }, + _ => None, + } +} + +impl FromValue for u64 { + const EXPECTED_TYPE_NAME: Option<&'static str> = Some("int"); + + /// Argument Clinic's `unsigned_long` converter with a 64-bit `long`: a + /// negative int is a `ValueError` before the width is checked. + fn from_value(value: Value, vm: &mut VM<'_>) -> Result { + let value = resolve_index_dunder(value, vm)?; + let result = match value { + Value::Bool(b) => Ok(Self::from(b)), + Value::Int(i) => Self::try_from(i).map_err(|_| FromValueFail::Raise(ExcType::value_error_negative_int())), + _ => match long_int(&value, vm) { + Some(big) if big.sign() == Sign::Minus => { + Err(FromValueFail::Raise(ExcType::value_error_negative_int())) + } + Some(big) => big + .to_u64() + .ok_or_else(|| FromValueFail::Raise(ExcType::overflow_c_unsigned_long())), + None => Err(FromValueFail::WrongType), + }, + }; + value.drop_with(vm); + result + } + + fn type_error(got: &str) -> RunError { + ExcType::type_error_not_integer(got) + } +} + +impl FromValue for bool { + const EXPECTED_TYPE_NAME: Option<&'static str> = Some("bool"); + + fn from_value(value: Value, vm: &mut VM<'_>) -> Result { + let result = match value { + Value::Bool(b) => Ok(b), + _ => Err(FromValueFail::WrongType), + }; + value.drop_with(vm); + result + } + + fn type_error(_got: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, "a bool is required").into() + } +} + +/// A `str` argument extracted without copying: validates the value is a +/// string, then keeps the original `Value` (ownership and refcount +/// transferred in) and lends the text on demand via [`StrArg::as_str`]. +/// +/// Always prefer this over an owned `String` field — copying the text onto +/// the Rust heap is pure overhead for arguments the function only reads. If +/// ownership is genuinely needed, call `.as_str(vm).to_owned()` at the point +/// of storage. +/// +/// Holds a heap reference for heap strings, so extracted fields must be +/// released on every path: bind them with `defer_drop!` in the function body +/// (the macro's error paths use [`FromValue::drop_extracted`]). +pub(crate) struct StrArg(Value); + +impl FromValue for StrArg { + const EXPECTED_TYPE_NAME: Option<&'static str> = Some("str"); + + fn from_value(value: Value, vm: &mut VM<'_>) -> Result { + if value.is_str(vm.heap) { + Ok(Self(value)) + } else { + value.drop_with(vm); + Err(FromValueFail::WrongType) + } + } + + fn drop_extracted(self, heap: &mut impl ContainsHeap) { + self.0.drop_with(heap); + } +} + +impl StrArg { + /// Borrows the text. Infallible: the constructor validated str-ness and a + /// live value's type cannot change. + pub fn as_str<'a>(&'a self, vm: &'a VM<'_>) -> &'a str { + match self.0.to_str(vm) { + Ok(s) => s, + Err(_) => unreachable!("StrArg always holds a str"), + } + } +} + +impl DropWithContext for StrArg { + fn drop_with(self, ctx: &mut C) { + self.0.drop_with(ctx); + } +} + +/// `Option` is the natural way to spell "absent or present" arguments +/// (e.g. `date.replace(year=…)` where the kwarg's default comes from the +/// receiver, not from a static constant). Paired with `#[from_args(default)]` +/// on the field, an absent argument resolves to `None` and a present one is +/// delegated to `T::from_value` and wrapped in `Some`. +/// +/// Note: an explicit `Value::None` passed by the caller is **not** treated as +/// absent — it is forwarded to `T::from_value`, which will normally reject it. +/// This matches CPython: `date.replace(year=None)` is a `TypeError`, not a +/// no-op. +impl FromValue for Option { + // Forward the inner type's label — `Option` reports "str" in + // bad-arg errors, matching CPython for fields where absence is signalled + // by `Option::None` rather than by passing `None`. Functions that accept + // a literal `None` value (e.g. open()'s `encoding=None`) need + // `"str or None"` wording and should override at the field level. + const EXPECTED_TYPE_NAME: Option<&'static str> = T::EXPECTED_TYPE_NAME; + + fn from_value(value: Value, vm: &mut VM<'_>) -> Result { + T::from_value(value, vm).map(Some) + } + + fn type_error(got: &str) -> RunError { + T::type_error(got) + } + + fn drop_extracted(self, heap: &mut impl ContainsHeap) { + if let Some(inner) = self { + inner.drop_extracted(heap); + } + } +} + +/// Newtype around `bool` for kwargs that perform Python's *truth test* on the +/// incoming value rather than demanding a strict `bool`. CPython spells this +/// pattern via `if flag:` — empty strings/bytes/collections are falsy, every +/// other heap object is truthy. +/// +/// Use this for flags like `Path.mkdir(parents=…, exist_ok=…)` where the +/// CPython signature documents a `bool` but the implementation feeds the raw +/// value through `bool()`. Using plain `bool` would reject `mkdir(parents=[])` +/// with a `TypeError`; that does not match CPython, which silently treats the +/// empty list as `False`. +#[derive(Debug, Clone, Copy)] +pub(crate) struct LaxBool(bool); + +impl FromValue for LaxBool { + fn from_value(value: Value, vm: &mut VM<'_>) -> Result { + let result = value.py_bool(vm); + value.drop_with(vm); + result.map(Self).map_err(FromValueFail::Raise) + } +} + +impl LaxBool { + pub fn new(b: bool) -> Self { + Self(b) + } + + pub fn bool(self) -> bool { + self.0 + } +} diff --git a/crates/bashkit-monty/src/args/mod.rs b/crates/bashkit-monty/src/args/mod.rs new file mode 100644 index 000000000..40f2cd68c --- /dev/null +++ b/crates/bashkit-monty/src/args/mod.rs @@ -0,0 +1,761 @@ +mod bind_native; +mod bind_python; +mod from_value; + +use std::{mem, slice, vec::IntoIter}; + +pub(crate) use bind_native::{Bound, ErrorFamily, Param, ParamKind, ParamSpec, bind}; +pub(crate) use bind_python::Signature; +pub(crate) use from_value::{ArgErrCtx, FromValue, FromValueFail, LaxBool, StrArg, is_long_int, long_int}; +pub(crate) use monty_macros::FromArgs; +use monty_types::{ + CallArgs, + unstable::{self, MontyNode}, +}; + +use crate::{ + bytecode::VM, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + expressions::{ExprLoc, Identifier}, + heap::{ContainsHeap, DropWithContext, Heap}, + intern::{Interns, StringId}, + object_bridge::{CallArgsExt, GraphExporter}, + parse::ParseError, + types::{Dict, dict::DictIntoIter}, + value::Value, +}; + +/// Type for method call arguments. +/// +/// Uses specific variants for common cases (0-2 arguments). +/// Most Python method calls have at most 2 arguments, so this optimization +/// eliminates the Vec heap allocation overhead for the vast majority of calls. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum ArgValues { + Empty, + One(Value), + Two(Value, Value), + Kwargs(KwargsValues), + ArgsKargs { args: Vec, kwargs: KwargsValues }, +} + +impl ArgValues { + /// Checks that zero arguments were passed. + /// + /// On error, properly drops all contained values to maintain reference counts. + pub fn check_zero_args(self, name: &str, heap: &mut Heap) -> RunResult<()> { + match self { + Self::Empty => Ok(()), + other => { + // CPython checks keywords first and reports them separately, so a + // stray kwarg is never described as `(0 given)`. + let has_kwargs = other.has_kwargs(); + let count = other.count(); + other.drop_with(heap); + if has_kwargs { + Err(ExcType::type_error_no_kwargs(name)) + } else { + Err(ExcType::type_error_no_args(name, count)) + } + } + } + } + + /// Whether any keyword argument was passed. + #[must_use] + fn has_kwargs(&self) -> bool { + match self { + Self::Empty | Self::One(_) | Self::Two(_, _) => false, + Self::Kwargs(kwargs) | Self::ArgsKargs { kwargs, .. } => !kwargs.is_empty(), + } + } + + /// Rejects keywords before a positional-only function's arity or conversion checks. + pub(crate) fn reject_kwargs(self, name: &str, heap: &mut Heap) -> RunResult { + if self.has_kwargs() { + self.drop_with(heap); + Err(ExcType::type_error_no_kwargs(name)) + } else { + Ok(self) + } + } + + /// Checks that exactly one positional argument was passed, returning it. + /// + /// On error, properly drops all contained values to maintain reference counts. + pub fn get_one_arg(self, name: &str, heap: &mut Heap) -> RunResult { + match self { + Self::One(a) => Ok(a), + other => { + let count = other.count(); + other.drop_with(heap); + Err(ExcType::type_error_arg_count(name, 1, count)) + } + } + } + + /// Checks that exactly two positional arguments were passed, returning them as a tuple. + /// + /// On error, properly drops all contained values to maintain reference counts. + pub fn get_two_args(self, name: &str, heap: &mut Heap) -> RunResult<(Value, Value)> { + match self { + Self::Two(a1, a2) => Ok((a1, a2)), + other => { + let count = other.count(); + other.drop_with(heap); + Err(ExcType::type_error_arg_count(name, 2, count)) + } + } + } + + /// Checks that one or two arguments were passed, returning them as a tuple. + /// + /// On error, properly drops all contained values to maintain reference counts. + pub fn get_one_two_args(self, name: &str, heap: &mut Heap) -> RunResult<(Value, Option)> { + match self { + Self::One(a) => Ok((a, None)), + Self::Two(a1, a2) => Ok((a1, Some(a2))), + other => { + let count = other.count(); + other.drop_with(heap); + if count == 0 { + Err(ExcType::type_error_at_least(name, 1, count)) + } else { + Err(ExcType::type_error_at_most(name, 2, count)) + } + } + } + } + + /// Checks that zero or one argument was passed, returning the optional value. + /// + /// On error, properly drops all contained values to maintain reference counts. + pub fn get_zero_one_arg(self, name: &str, heap: &mut Heap) -> RunResult> { + match self { + Self::Empty => Ok(None), + Self::One(a) => Ok(Some(a)), + other => { + let count = other.count(); + other.drop_with(heap); + Err(ExcType::type_error_at_most(name, 1, count)) + } + } + } + + /// Builds an `ArgValues` from split parts, collapsing to the small-arity + /// variants the way [`VM::pop_n_args`](crate::bytecode::VM) does. + /// + /// Anything assembling arguments itself rather than popping them off the + /// stack must go through this. `get_one_arg` and its siblings match only + /// `Empty`/`One`/`Two`, so a hand-built `ArgsKargs` carrying empty kwargs + /// makes every builtin using them report a bogus arity error. + pub(crate) fn from_parts(mut args: Vec, kwargs: KwargsValues) -> Self { + match args.len() { + _ if !kwargs.is_empty() => Self::ArgsKargs { args, kwargs }, + 0 => Self::Empty, + 1 => Self::One(args.pop().expect("length checked")), + 2 => { + let b = args.pop().expect("length checked"); + let a = args.pop().expect("length checked"); + Self::Two(a, b) + } + _ => Self::ArgsKargs { args, kwargs }, + } + } + + /// Prepends a value as the first positional argument. + /// + /// Used to insert `self` when dispatching dataclass method calls to the host. + /// The dataclass instance becomes the first arg so the host can reconstruct + /// the original object and call the method on it. + pub fn prepend(self, value: Value) -> Self { + match self { + Self::Empty => Self::One(value), + Self::One(a) => Self::Two(value, a), + Self::Two(a, b) => Self::ArgsKargs { + args: vec![value, a, b], + kwargs: KwargsValues::Empty, + }, + Self::Kwargs(kw) => Self::from_parts(vec![value], kw), + Self::ArgsKargs { mut args, kwargs } => { + args.insert(0, value); + Self::from_parts(args, kwargs) + } + } + } + + /// Splits into positional iterator and keyword values without allocating + /// for the common One/Two cases. + pub fn into_parts(self) -> (ArgPosIter, KwargsValues) { + match self { + Self::Empty => (ArgPosIter::Empty, KwargsValues::Empty), + Self::One(v) => (ArgPosIter::One(v), KwargsValues::Empty), + Self::Two(v1, v2) => (ArgPosIter::Two([v1, v2]), KwargsValues::Empty), + Self::Kwargs(kwargs) => (ArgPosIter::Empty, kwargs), + Self::ArgsKargs { args, kwargs } => (ArgPosIter::Vec(args.into_iter()), kwargs), + } + } + + /// Variant of [`into_parts()`](Self::into_parts) that accepts no kwargs, returning an error if any are present. + pub fn into_pos_only(self, method_name: &str, heap: &mut Heap) -> RunResult { + match self { + Self::Empty => Ok(ArgPosIter::Empty), + Self::One(v) => Ok(ArgPosIter::One(v)), + Self::Two(v1, v2) => Ok(ArgPosIter::Two([v1, v2])), + Self::Kwargs(kwargs) => { + if kwargs.is_empty() { + Ok(ArgPosIter::Empty) + } else { + Err(Self::unexpected_kwargs_error(kwargs, method_name, heap)) + } + } + Self::ArgsKargs { args, kwargs } => { + if kwargs.is_empty() { + Ok(ArgPosIter::Vec(args.into_iter())) + } else { + args.drop_with(heap); + Err(Self::unexpected_kwargs_error(kwargs, method_name, heap)) + } + } + } + } + + #[cold] + fn unexpected_kwargs_error(kwargs: KwargsValues, method_name: &str, heap: &mut Heap) -> RunError { + kwargs.drop_with(heap); + ExcType::type_error_no_kwargs(method_name) + } + + /// Exports the arguments into one arena for delivery to an external + /// function, so an object passed twice crosses once. + pub fn into_call_args(self, vm: &mut VM<'_>) -> CallArgs { + let mut exporter = GraphExporter::new(); + let mut call = CallArgs::new(); + match self { + Self::Empty => {} + Self::One(a) => call.export_arg(&mut exporter, a, vm), + Self::Two(a1, a2) => { + call.export_arg(&mut exporter, a1, vm); + call.export_arg(&mut exporter, a2, vm); + } + Self::Kwargs(kwargs) => kwargs.export_into(&mut call, &mut exporter, vm), + Self::ArgsKargs { args, kwargs } => { + for arg in args { + call.export_arg(&mut exporter, arg, vm); + } + kwargs.export_into(&mut call, &mut exporter, vm); + } + } + *unstable::call_args_parts_mut(&mut call).0 = exporter.finish(vm); + call + } + + /// The first positional argument, if any, without consuming the arguments. + pub(crate) fn first_positional(&self) -> Option<&Value> { + match self { + Self::Empty | Self::Kwargs(_) => None, + Self::One(v) | Self::Two(v, _) => Some(v), + Self::ArgsKargs { args, .. } => args.first(), + } + } + + /// The keyword argument called `name`, if any, without consuming the arguments. + pub(crate) fn keyword(&self, name: &str, heap: &Heap, interns: &Interns) -> Option<&Value> { + match self { + Self::Empty | Self::One(_) | Self::Two(_, _) => None, + Self::Kwargs(kwargs) | Self::ArgsKargs { kwargs, .. } => kwargs.get(name, heap, interns), + } + } + + /// Returns the number of positional arguments. + /// + /// For `Kwargs` returns 0, for `ArgsKargs` returns only the positional args count. + pub(crate) fn count(&self) -> usize { + match self { + Self::Empty => 0, + Self::One(_) => 1, + Self::Two(_, _) => 2, + Self::Kwargs(_) => 0, + Self::ArgsKargs { args, .. } => args.len(), + } + } +} + +impl DropWithContext for ArgValues { + fn drop_with(self, heap: &mut C) { + match self { + Self::Empty => {} + Self::One(v) => v.drop_with(heap), + Self::Two(v1, v2) => { + v1.drop_with(heap); + v2.drop_with(heap); + } + Self::Kwargs(kwargs) => { + kwargs.drop_with(heap); + } + Self::ArgsKargs { args, kwargs } => { + args.drop_with(heap); + kwargs.drop_with(heap); + } + } + } +} + +/// Iterator over positional arguments without allocation. +/// +/// Supports iterating over `ArgValues::One/Two` without converting to Vec. +/// This iterator must be fully consumed OR explicitly dropped with +/// `drop_with()` to maintain correct reference counts. +/// +/// The iterator yields values by ownership transfer. Once a value is yielded, +/// the caller is responsible for either using it or calling `drop_with()` on it. +pub(crate) enum ArgPosIter { + Empty, + One(Value), + Two([Value; 2]), + Vec(IntoIter), +} + +impl ArgPosIter { + /// Returns a slice of the remaining positional arguments without consuming them. + pub fn as_slice(&self) -> &[Value] { + match self { + Self::Empty => &[], + Self::One(v) => slice::from_ref(v), + Self::Two(array) => array.as_slice(), + Self::Vec(iter) => iter.as_slice(), + } + } +} + +impl Iterator for ArgPosIter { + type Item = Value; + + #[inline] + fn next(&mut self) -> Option { + match self { + Self::Empty => None, + Self::One(_) => { + let Self::One(v) = mem::replace(self, Self::Empty) else { + unreachable!() + }; + Some(v) + } + Self::Two(_) => { + let Self::Two([v1, v2]) = mem::replace(self, Self::Empty) else { + unreachable!() + }; + *self = Self::One(v2); + Some(v1) + } + Self::Vec(iter) => iter.next(), + } + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + match self { + Self::Empty => (0, Some(0)), + Self::One(_) => (1, Some(1)), + Self::Two(_) => (2, Some(2)), + Self::Vec(iter) => iter.size_hint(), + } + } +} + +impl ExactSizeIterator for ArgPosIter {} + +impl DropWithContext for ArgPosIter { + fn drop_with(self, heap: &mut C) { + match self { + Self::Empty => {} + Self::One(v1) => v1.drop_with(heap), + Self::Two(v12) => v12.drop_with(heap), + Self::Vec(iter) => iter.drop_with(heap), + } + } +} + +/// Type for keyword arguments. +/// +/// Used to capture both the case of inline keyword arguments `foo(foo=1, bar=2)` +/// and the case of a dictionary passed as a single argument `foo(**kwargs)`. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum KwargsValues { + Empty, + Inline(Vec<(StringId, Value)>), + /// Kwargs whose keys are runtime string `Value`s — produced by the binder's + /// `varkwargs` collection, where `**{...}` unpacking can supply str keys + /// that have no interned id (`Inline` can only carry `StringId` keys). + Pairs(Vec<(Value, Value)>), + Dict(Dict), +} + +impl KwargsValues { + /// Returns the number of keyword arguments. + #[must_use] + pub fn len(&self) -> usize { + match self { + Self::Empty => 0, + Self::Inline(kvs) => kvs.len(), + Self::Pairs(kvs) => kvs.len(), + Self::Dict(dict) => dict.len(), + } + } + + /// Returns true if there are no keyword arguments. + #[must_use] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// The value passed under `name`, if any; a non-string key (only possible via `**` + /// unpacking) never matches. + pub(crate) fn get(&self, name: &str, heap: &Heap, interns: &Interns) -> Option<&Value> { + let is_name = |key: &Value| key.as_either_str(heap).is_some_and(|key| key.as_str(interns) == name); + match self { + Self::Empty => None, + Self::Inline(kvs) => kvs + .iter() + .find(|(id, _)| interns.get_str(*id) == name) + .map(|(_, value)| value), + Self::Pairs(kvs) => kvs.iter().find(|(key, _)| is_name(key)).map(|(_, value)| value), + Self::Dict(dict) => dict.iter().find(|(key, _)| is_name(key)).map(|(_, value)| value), + } + } + + /// The first keyword's name, for callables that accept none and report + /// CPython's `got an unexpected keyword argument`. A non-string key (only + /// possible via `**` unpacking) is CPython's `keywords must be strings`. + pub fn first_key(&self, heap: &Heap, interns: &Interns) -> RunResult> { + let key = match self { + Self::Empty => return Ok(None), + Self::Inline(kvs) => return Ok(kvs.first().map(|(id, _)| interns.get_str(*id).to_owned())), + Self::Pairs(kvs) => kvs.first().map(|(key, _)| key), + Self::Dict(dict) => dict.iter().next().map(|(key, _)| key), + }; + match key { + None => Ok(None), + Some(key) => key + .as_either_str(heap) + .map(|key| Some(key.as_str(interns).to_owned())) + .ok_or_else(ExcType::type_error_kwargs_nonstring_key), + } + } + + /// Exports the keyword arguments into `call`'s arena, for external functions. + fn export_into(self, call: &mut CallArgs, exporter: &mut GraphExporter, vm: &mut VM<'_>) { + match self { + Self::Empty => {} + Self::Inline(kvs) => { + for (k, v) in kvs { + let key = exporter.push_node(MontyNode::String(vm.interns.get_str(k).to_owned())); + let value = exporter.push_owned(v, vm); + unstable::call_args_parts_mut(call).2.push((key, value)); + } + } + Self::Pairs(kvs) => { + for (k, v) in kvs { + call.export_kwarg(exporter, k, v, vm); + } + } + Self::Dict(dict) => { + for (k, v) in dict { + call.export_kwarg(exporter, k, v, vm); + } + } + } + } +} + +impl DropWithContext for KwargsValues { + /// Properly drops all values in the arguments, decrementing reference counts. + fn drop_with(self, heap: &mut C) { + match self { + Self::Empty => {} + Self::Inline(kvs) => { + for (_, v) in kvs { + v.drop_with(heap); + } + } + Self::Pairs(kvs) => { + for (k, v) in kvs { + k.drop_with(heap); + v.drop_with(heap); + } + } + Self::Dict(dict) => { + for (k, v) in dict { + k.drop_with(heap); + v.drop_with(heap); + } + } + } + } +} + +impl IntoIterator for KwargsValues { + type Item = (Value, Value); + type IntoIter = KwargsValuesIter; + + fn into_iter(self) -> Self::IntoIter { + match self { + Self::Empty => KwargsValuesIter::Empty, + Self::Inline(kvs) => KwargsValuesIter::Inline(kvs.into_iter()), + Self::Pairs(kvs) => KwargsValuesIter::Pairs(kvs.into_iter()), + Self::Dict(dict) => KwargsValuesIter::Dict(dict.into_iter()), + } + } +} + +/// Iterator over keyword argument (key, value) pairs. +/// +/// For `Inline` kwargs, converts `StringId` keys to `Value::InternString`. +/// For `Pairs` and `Dict` kwargs, iterates directly over the owned entries +/// without intermediate allocation. +pub(crate) enum KwargsValuesIter { + Empty, + Inline(IntoIter<(StringId, Value)>), + Pairs(IntoIter<(Value, Value)>), + Dict(DictIntoIter), +} + +impl Iterator for KwargsValuesIter { + type Item = (Value, Value); + + fn next(&mut self) -> Option { + match self { + Self::Empty => None, + Self::Inline(iter) => iter.next().map(|(k, v)| (Value::InternString(k), v)), + Self::Pairs(iter) => iter.next(), + Self::Dict(iter) => iter.next(), + } + } + + fn size_hint(&self) -> (usize, Option) { + match self { + Self::Empty => (0, Some(0)), + Self::Inline(iter) => iter.size_hint(), + Self::Pairs(iter) => iter.size_hint(), + Self::Dict(iter) => iter.size_hint(), + } + } +} + +impl ExactSizeIterator for KwargsValuesIter {} + +impl DropWithContext for KwargsValuesIter { + fn drop_with(self, heap: &mut C) { + match self { + Self::Empty => {} + Self::Inline(iter) => { + for (_, v) in iter { + v.drop_with(heap); + } + } + Self::Pairs(iter) => { + for (k, v) in iter { + k.drop_with(heap); + v.drop_with(heap); + } + } + Self::Dict(iter) => { + for (k, v) in iter { + k.drop_with(heap); + v.drop_with(heap); + } + } + } + } +} + +/// A keyword argument in a function call expression. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Kwarg { + pub key: Identifier, + pub value: ExprLoc, +} + +/// A positional argument item in a generalized function call (PEP 448). +/// +/// Used in `ArgExprs::GeneralizedCall` when a call has multiple `*unpacks` +/// or positional arguments after a `*unpack`. Each item is either a plain +/// value or a `*expr` iterable to be unpacked into the argument tuple. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) enum CallArg { + /// A plain positional argument. + Value(ExprLoc), + /// A `*expr` unpack — the iterable is spread into consecutive arguments. + Unpack(ExprLoc), +} + +/// A keyword argument item in a generalized function call (PEP 448). +/// +/// Used in `ArgExprs::GeneralizedCall` when a call has multiple `**unpacks` +/// or named kwargs interspersed with `**unpacks`. Duplicate keys from any +/// combination raise `TypeError` (both `f(**a, **b)` with shared keys and +/// `f(x=1, **{'x': 2})` are errors). This is enforced by `DictMerge` in +/// the compiler. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) enum CallKwarg { + /// A named keyword argument: `key=value`. + Named(Kwarg), + /// A `**expr` unpack — the mapping's entries are merged into kwargs. + Unpack(ExprLoc), +} + +/// Expressions that make up a function call's arguments. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum ArgExprs { + Empty, + One(ExprLoc), + Two(ExprLoc, ExprLoc), + Args(Vec), + Kwargs(Vec), + ArgsKargs { + args: Option>, + var_args: Option, + kwargs: Option>, + var_kwargs: Option, + }, + /// Generalized call with PEP 448 unpacking. + /// + /// Used when a call has multiple `*args` unpacks, positional arguments + /// after a `*unpack`, or multiple `**kwargs` unpacks. The compiler + /// builds the args tuple incrementally using `BuildList(0)` + + /// `ListAppend`/`ListExtend` + `ListToTuple`, and the kwargs dict + /// using `BuildDict(0)` + `DictMerge` (which raises `TypeError` on + /// duplicate keys). + GeneralizedCall { + args: Vec, + kwargs: Vec, + }, +} + +impl ArgExprs { + /// Creates a `GeneralizedCall` for PEP 448 calls with multiple unpacks. + /// + /// Use this when a function call has multiple `*args` unpacks, positional + /// arguments after a `*unpack`, or multiple `**kwargs` unpacks. The compiler + /// will emit `BuildList(0)` + `ListAppend`/`ListExtend` + `ListToTuple` for + /// the args tuple, and `BuildDict(0)` + `DictMerge` for the kwargs dict. + pub(crate) fn new_generalized(args: Vec, kwargs: Vec) -> Self { + Self::GeneralizedCall { args, kwargs } + } + + /// Creates a new `ArgExprs` with optional `*args` and `**kwargs` unpacking expressions. + /// + /// This is used when parsing function calls that may include `*expr` / `**expr` + /// syntax for unpacking iterables or mappings into arguments. + pub fn new_with_var_kwargs( + args: Vec, + var_args: Option, + kwargs: Vec, + var_kwargs: Option, + ) -> Self { + // Full generality requires ArgsKargs when we have unpacking or mixed arg/kwarg usage + if var_args.is_some() || var_kwargs.is_some() || (!kwargs.is_empty() && !args.is_empty()) { + Self::ArgsKargs { + args: if args.is_empty() { None } else { Some(args) }, + var_args, + kwargs: if kwargs.is_empty() { None } else { Some(kwargs) }, + var_kwargs, + } + } else if !kwargs.is_empty() { + Self::Kwargs(kwargs) + } else if args.len() > 2 { + Self::Args(args) + } else { + let mut iter = args.into_iter(); + if let Some(first) = iter.next() { + if let Some(second) = iter.next() { + Self::Two(first, second) + } else { + Self::One(first) + } + } else { + Self::Empty + } + } + } + + /// Applies a transformation function to all `ExprLoc` elements in the args. + /// + /// This is used during the preparation phase to recursively prepare all + /// argument expressions before execution. + pub fn prepare_args( + &mut self, + mut f: impl FnMut(ExprLoc) -> Result, + ) -> Result<(), ParseError> { + // Swap self with Empty to take ownership, then rebuild + let taken = mem::replace(self, Self::Empty); + *self = match taken { + Self::Empty => Self::Empty, + Self::One(arg) => Self::One(f(arg)?), + Self::Two(arg1, arg2) => Self::Two(f(arg1)?, f(arg2)?), + Self::Args(args) => Self::Args(args.into_iter().map(&mut f).collect::, _>>()?), + Self::Kwargs(kwargs) => Self::Kwargs( + kwargs + .into_iter() + .map(|kwarg| { + Ok(Kwarg { + key: kwarg.key, + value: f(kwarg.value)?, + }) + }) + .collect::, ParseError>>()?, + ), + Self::ArgsKargs { + args, + var_args, + kwargs, + var_kwargs, + } => { + let args = args + .map(|a| a.into_iter().map(&mut f).collect::, ParseError>>()) + .transpose()?; + let var_args = var_args.map(&mut f).transpose()?; + let kwargs = kwargs + .map(|k| { + k.into_iter() + .map(|kwarg| { + Ok(Kwarg { + key: kwarg.key, + value: f(kwarg.value)?, + }) + }) + .collect::, ParseError>>() + }) + .transpose()?; + let var_kwargs = var_kwargs.map(&mut f).transpose()?; + Self::ArgsKargs { + args, + var_args, + kwargs, + var_kwargs, + } + } + Self::GeneralizedCall { args, kwargs } => { + let args = args + .into_iter() + .map(|arg| match arg { + CallArg::Value(e) => Ok(CallArg::Value(f(e)?)), + CallArg::Unpack(e) => Ok(CallArg::Unpack(f(e)?)), + }) + .collect::, ParseError>>()?; + let kwargs = kwargs + .into_iter() + .map(|kwarg| match kwarg { + CallKwarg::Named(kw) => Ok(CallKwarg::Named(Kwarg { + key: kw.key, + value: f(kw.value)?, + })), + CallKwarg::Unpack(e) => Ok(CallKwarg::Unpack(f(e)?)), + }) + .collect::, ParseError>>()?; + Self::GeneralizedCall { args, kwargs } + } + }; + Ok(()) + } +} diff --git a/crates/bashkit-monty/src/asyncio.rs b/crates/bashkit-monty/src/asyncio.rs new file mode 100644 index 000000000..c2870aa5b --- /dev/null +++ b/crates/bashkit-monty/src/asyncio.rs @@ -0,0 +1,353 @@ +//! Async/await support types for Monty. +//! +//! This module contains all async-related types including coroutines, futures, +//! and task identifiers. The host acts as the event loop - external function +//! calls return `ExternalFuture` objects that can be awaited. + +use ahash::AHashMap; +use smallvec::SmallVec; + +use crate::{ + exception_private::RunError, + heap::{ContainsHeap, DropWithContext, HeapId}, + intern::FunctionId, + value::Value, +}; + +/// Unique identifier for external function calls. +/// +/// Sequential integers allocated by the scheduler. Used to correlate +/// external function calls with their results when the host resolves them. +/// The counter always increments, even for sync resolution, to keep IDs unique. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) struct CallId(u32); + +impl CallId { + /// Creates a new CallId from a raw value. + #[inline] + pub fn new(id: u32) -> Self { + Self(id) + } + + /// Returns the raw u32 value. + #[inline] + pub fn raw(self) -> u32 { + self.0 + } +} + +/// Unique identifier for an async task. +/// +/// Sequential integers allocated by the scheduler. Task 0 is always the main task +/// which uses the VM's stack/frames directly. Spawned tasks (1+) store their own context, +/// hence `TaskId::default()` is the main task. +#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) struct TaskId(u32); + +impl TaskId { + /// Creates a new TaskId from a raw value. + #[inline] + pub fn new(id: u32) -> Self { + Self(id) + } + + /// Returns true if this is the main task (task 0). + #[inline] + pub fn is_main(self) -> bool { + self.0 == 0 + } +} + +/// Coroutine execution state (single-shot semantics). +/// +/// Coroutines in Monty follow single-shot semantics - they can only be awaited once. +/// This differs from Python generators which can be resumed multiple times. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub(crate) enum CoroutineState { + /// Coroutine has been created but not yet awaited. + New, + /// Coroutine is currently executing (has been awaited). + Running, + /// Coroutine has finished execution. + Completed, +} + +/// A coroutine object representing an async function call result. +/// +/// Created when an `async def` function is called. Argument binding happens at call time; +/// awaiting the coroutine starts execution. Coroutines use single-shot semantics - +/// they can only be awaited once. +/// +/// # Namespace Layout +/// +/// The `namespace` vector is pre-sized to match the function's namespace size and contains: +/// ```text +/// [params...][cell_vars...][free_vars...][locals...] +/// ``` +/// - Parameter slots are filled with bound argument values at call time +/// - Cell/free var slots contain `Value::Ref` to captured cells +/// - Local slots start as `Value::Undefined` +/// +/// When the coroutine is awaited, these values are pushed onto the VM's stack +/// as inline locals, and a new frame is pushed to execute the async function body. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct Coroutine { + /// The async function to execute. + pub func_id: FunctionId, + /// Pre-bound namespace values (sized to function namespace). + /// Contains bound parameters, captured cells, and uninitialized locals. + pub namespace: Vec, + /// Current execution state. + pub state: CoroutineState, + /// Owned reference to the `exec()` / `eval()` globals dict the async + /// function was defined under; `None` when its globals are module slots. + pub globals: Option, +} +impl Coroutine { + /// Creates a new coroutine for an async function call. + /// + /// # Arguments + /// * `func_id` - The async function to execute + /// * `namespace` - Pre-bound namespace with parameters and captured variables + /// * `globals` - The function's globals dict, already inc_ref'd for this coroutine + pub fn new(func_id: FunctionId, namespace: Vec, globals: Option) -> Self { + Self { + func_id, + namespace, + state: CoroutineState::New, + globals, + } + } +} + +/// An external future driven by the host. +/// +/// Created when the host returns `ExtFunctionResult::Future(call_id)` in +/// response to a function call yield. The future starts in `Pending`, and +/// transitions to `Resolved` (host returned a value) or `Failed` (host +/// returned an error) when [`VM::resolve_future`] / [`VM::fail_future`] +/// fires. +/// +/// # Re-await semantics +/// +/// `Resolved` / `Failed` futures can be awaited any number of times — each +/// await yields a clone of the cached value or replays the cached exception, +/// matching CPython's Future semantics. `Pending` futures still support only +/// a single in-flight awaiter (the `awaiter: Option` slot); +/// multi-awaiter on `Pending` is a planned follow-up that needs the same +/// wake/raise plumbing as multi-waiter gathers. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct ExternalFuture { + /// Host-side identifier. Used by the scheduler's `CallId -> HeapId` + /// index so host resolutions can find the heap entry. + pub call_id: CallId, + /// Current state. + pub state: ExternalFutureState, + /// `asyncio.sleep(delay, result)`: the value to resolve with in place of + /// the host's, which is only the wake-up signal. Owned; taken on + /// resolution and released on failure or when the entry is freed. + pub sleep_result: Option, +} + +/// State machine for [`ExternalFuture`]. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum ExternalFutureState { + /// Awaiting host resolution. `awaiter` is the downstream that should be + /// notified on resolution; `None` until someone awaits, `Some(...)` for + /// the lifetime of the await. + Pending { awaiter: Option }, + /// Resolved with a value. Re-awaits clone this Value. + Resolved(Value), + /// Rejected with an error. Re-awaits replay (clone) this error. + Failed(RunError), +} + +impl ExternalFuture { + /// Creates a new `ExternalFuture` in the `Pending` state with no awaiter. + pub fn new_pending(call_id: CallId, sleep_result: Option) -> Self { + Self { + call_id, + state: ExternalFutureState::Pending { awaiter: None }, + sleep_result, + } + } +} + +/// Where the result/error of a completing awaitable should be routed. +/// +/// Stored as the "downstream" of an awaitable. +/// +/// - `Task` wakes the named task by setting it `Ready` and pushing the value +/// (or routing the error through its frame's exception handler). `TaskId` +/// is just a scheduler-side identifier, not a heap reference, so the +/// variant owns no inc_ref. +/// - `GatherSlot` fans the value into the gather at `gather`, looking up the +/// slot indices it should fill via the awaitable's own `HeapId` (`source`). +/// The wrapper **owns an inc_ref on `gather`**: storing the awaiter on an +/// awaitable keeps the gather alive for the in-flight window, so the +/// awaitable's resolution path can dispatch to it safely without +/// additional cleanup elsewhere. Drop the owned `Awaiter` via +/// [`DropWithContext`] (and clone via [`Self::clone_with_heap`]) so the +/// `gather` ref count stays balanced. +/// +/// An awaitable whose downstream has already settled keeps its `Awaiter` +/// pointing at it; the value is discarded where it is delivered rather than +/// the link being severed here. See [`GatherState`]. +/// +/// Not `Copy` / `Clone` on purpose — the inc_ref discipline requires every +/// duplication to go through `clone_with_heap` and every discard to go +/// through `drop_with`. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum Awaiter { + Task(TaskId), + GatherSlot { gather: HeapId, source: HeapId }, +} + +impl DropWithContext for Awaiter { + fn drop_with(self, heap: &mut C) { + if let Self::GatherSlot { gather, .. } = self { + heap.heap_mut().dec_ref(gather); + } + } +} + +/// A gather() result tracking multiple coroutines/tasks and external futures. +/// +/// Created by `asyncio.gather(*awaitables)`. Does NOT spawn tasks immediately - +/// tasks are spawned when the GatherFuture is awaited in Await. +/// +/// # Lifecycle +/// +/// The lifecycle is encoded in [`GatherState`]: +/// +/// 1. **`Pending`** — created by `gather(coro1, coro2, ...)` but not yet awaited. +/// Only `items` carries data; the per-await bookkeeping does not yet exist. +/// 2. **`Awaited(AwaitedGather)`** — entered by the `Await` opcode. Spawned task +/// ids, the waiter, the per-slot results, and any external futures still +/// being waited on all live inside the [`AwaitedGather`] payload. Tasks and +/// external resolutions write into `results` slots while in this state. +/// 3. **`Completed(list_id)`** — all children completed successfully. The +/// `list_id` is an inc_ref'd `HeapData::List` holding the gathered results; +/// re-awaiting the gather returns this same list, matching CPython's +/// behavior of caching a Future's result. +/// 4. **`Failed(error)`** — a child task or external future raised. The error +/// was propagated to the original waiter on first await, and is cached here +/// so re-awaits re-raise the same exception (again matching CPython). +/// +/// Encoding the phases as a `match`-able enum lets every site that touches a +/// gather state-transition explicitly, instead of inferring "have we been +/// awaited?" / "are we done?" from emptiness checks across several `Vec`s. +/// +/// # Re-await semantics +/// +/// `Completed` and `Failed` gathers can be awaited any number of times — each +/// await yields the same cached result or exception. Re-awaiting a gather that +/// is still in `Awaited` state (in-flight, the original waiter has not finished +/// driving it to completion) is currently rejected; supporting that would +/// require a list of waiters and is left as future work. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct GatherFuture { + /// Heap ids of items to gather. Each id points to an awaitable + /// `HeapData` entry (currently `Coroutine` or `ExternalFuture`); the + /// kind is recovered with `heap.read(id)` at gather-await time. + /// + /// Set once at construction and never mutated. The gather inc_refs each + /// id and is the owner until drop, so GC must always walk this vector + /// regardless of `state`. + pub items: Vec, + /// Phase of the gather lifecycle. See [`GatherState`]. + pub state: GatherState, +} + +/// Lifecycle phase of a [`GatherFuture`]. +/// +/// See the `GatherFuture` docs for the transition rules. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum GatherState { + /// Created but never awaited. No spawned tasks, no results, no waiter. + Pending, + /// Currently being awaited. `AwaitedGather` carries every per-await field. + Awaited(AwaitedGather), + /// All children completed successfully. Re-awaiting the gather inc_refs this + /// value and returns it. + Completed(Value), + /// A child task failed (or an external future was rejected). The error + /// is cached so subsequent awaits re-raise it. `RunError` implements + /// `Clone`; clone the error when transitioning into this state. + Failed(RunError), +} + +/// Children of a gather that are still in flight → the slots each fills in the +/// gather's `results`. +/// +/// Keyed by the child's own `HeapId` (coroutine, external future or nested +/// gather), which is how every resolution site addresses its parent's slots. +/// Duplicates from `gather(c, c)` share one entry with several indices. +pub(crate) type PendingChildren = AHashMap>; + +/// Per-await bookkeeping for a [`GatherFuture`] in the `Awaited` phase. +/// +/// All fields are populated when the gather is first awaited (in +/// `await_gather_future`) and progressively consumed as children resolve. +/// +/// The gather is the single source of truth for "what awaitables I'm waiting +/// on and where their values go". Both maps follow the same lifecycle: each +/// entry is removed as the corresponding child resolves, and the gather is +/// done when both maps are empty. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct AwaitedGather { + /// Downstream the gather should notify on completion. `Awaiter::Task(t)` + /// is the user-level `await gather` case (waker is the task that ran + /// the `await`); `Awaiter::GatherSlot { .. }` is the nested-gather case + /// (this gather is an item of an outer gather, and its result list + /// fans into the outer's slot). Single-waiter for now; the multi-waiter + /// form is a planned follow-up. + pub awaiter: Awaiter, + /// Children → slots they fill in `results`, see [`PendingChildren`]. + /// + /// Entries are removed as the corresponding child resolves. The gather + /// is done when this map is empty. + pub pending_children: PendingChildren, + /// Results from each gather item, in order. Indices align with + /// `GatherFuture::items`. Filled as tasks complete and externals resolve. + pub results: Vec>, +} + +impl GatherFuture { + /// Creates a new GatherFuture with the given item heap ids. + /// + /// # Arguments + /// * `items` - Heap ids of awaitables (coroutines or external futures) + pub fn new(items: Vec) -> Self { + Self { + items, + state: GatherState::Pending, + } + } + + /// Returns the number of items to gather. + #[inline] + pub fn item_count(&self) -> usize { + self.items.len() + } + + /// Returns the per-await bookkeeping if the gather is in the `Awaited` + /// phase. Convenience for read-only inspection sites that don't need to + /// distinguish the other phases from one another. + #[inline] + pub fn as_awaited(&self) -> Option<&AwaitedGather> { + match &self.state { + GatherState::Awaited(awaited) => Some(awaited), + GatherState::Pending | GatherState::Completed(_) | GatherState::Failed(_) => None, + } + } + + /// Mutable counterpart to [`Self::as_awaited`]. + #[inline] + pub fn as_awaited_mut(&mut self) -> Option<&mut AwaitedGather> { + match &mut self.state { + GatherState::Awaited(awaited) => Some(awaited), + GatherState::Pending | GatherState::Completed(_) | GatherState::Failed(_) => None, + } + } +} diff --git a/crates/bashkit-monty/src/boundary_uuid.rs b/crates/bashkit-monty/src/boundary_uuid.rs new file mode 100644 index 000000000..7a1db4882 --- /dev/null +++ b/crates/bashkit-monty/src/boundary_uuid.rs @@ -0,0 +1,20 @@ +//! Worker-side uuid generation for sandbox-defined classes and instances. +//! +//! Sandbox objects need boundary identities generated where they live — in the +//! worker — so ids never encode addresses and stay stable for the life of the +//! heap object (dumps included). A uuid is generated only when a value crosses +//! to the host; sandboxed code has no way to observe these ids, so this is not +//! an entropy side-channel into the sandbox. + +use monty_types::MontyUuid; + +/// Generates a fresh uuid4 from OS entropy. +/// +/// # Panics +/// If the OS entropy source fails — unrecoverable, and a worker panic is +/// treated as a crash by the pool, which replaces the process. +pub(crate) fn create_uuid() -> MontyUuid { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes).expect("OS entropy source unavailable"); + MontyUuid::from_random_bytes(bytes) +} diff --git a/crates/bashkit-monty/src/builtins/abs.rs b/crates/bashkit-monty/src/builtins/abs.rs new file mode 100644 index 000000000..df8fc9750 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/abs.rs @@ -0,0 +1,19 @@ +//! Implementation of the abs() builtin function. + +use crate::{ + args::ArgValues, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + types::PyTrait, + value::Value, +}; + +/// Returns the absolute value through the operand's `__abs__` implementation. +pub fn builtin_abs(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("abs", vm.heap)?; + defer_drop!(value, vm); + value + .py_abs_impl(vm)? + .ok_or_else(|| ExcType::type_error(format!("bad operand type for abs(): '{}'", value.py_type_name(vm)))) +} diff --git a/crates/bashkit-monty/src/builtins/all.rs b/crates/bashkit-monty/src/builtins/all.rs new file mode 100644 index 000000000..f8038208a --- /dev/null +++ b/crates/bashkit-monty/src/builtins/all.rs @@ -0,0 +1,24 @@ +//! Implementation of the all() builtin function. + +use crate::{args::ArgValues, bytecode::VM, defer_drop, exception_private::RunResult, types::PyTrait, value::Value}; + +/// Implementation of the all() builtin function. +/// +/// Returns True if all elements of the iterable are true (or if the iterable is empty). +/// Short-circuits on the first falsy value. +pub fn builtin_all(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let iterable = args.get_one_arg("all", vm.heap)?; + defer_drop!(iterable, vm); + let iter = iterable.py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iter, vm); + let mut iter = iter.read(vm); + + while let Some(item) = iter.py_next(vm)? { + defer_drop!(item, vm); + if !item.py_bool(vm)? { + return Ok(Value::Bool(false)); + } + } + + Ok(Value::Bool(true)) +} diff --git a/crates/bashkit-monty/src/builtins/any.rs b/crates/bashkit-monty/src/builtins/any.rs new file mode 100644 index 000000000..c08a49f4c --- /dev/null +++ b/crates/bashkit-monty/src/builtins/any.rs @@ -0,0 +1,23 @@ +//! Implementation of the any() builtin function. + +use crate::{args::ArgValues, bytecode::VM, defer_drop, exception_private::RunResult, types::PyTrait, value::Value}; + +/// Implementation of the any() builtin function. +/// +/// Returns True if any element of the iterable is true. +/// Returns False for an empty iterable. Short-circuits on the first truthy value. +pub fn builtin_any(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let iterable = args.get_one_arg("any", vm.heap)?; + let iter = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iter, vm); + let mut iter = iter.read(vm); + + while let Some(item) = iter.py_next(vm)? { + defer_drop!(item, vm); + if item.py_bool(vm)? { + return Ok(Value::Bool(true)); + } + } + + Ok(Value::Bool(false)) +} diff --git a/crates/bashkit-monty/src/builtins/bin.rs b/crates/bashkit-monty/src/builtins/bin.rs new file mode 100644 index 000000000..f41f90b7f --- /dev/null +++ b/crates/bashkit-monty/src/builtins/bin.rs @@ -0,0 +1,19 @@ +//! Implementation of the bin() builtin function. + +use crate::{ + args::ArgValues, bytecode::VM, defer_drop, exception_private::RunResult, py_value::PyValue, + types::str::allocate_string_no_interning, value::Value, +}; + +/// Converts an integer or `__index__` result to a binary string prefixed with `0b`. +pub fn builtin_bin(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("bin", vm.heap)?; + defer_drop!(value, vm); + let index = value.py_index(vm)?; + defer_drop!(index, vm); + + let PyValue::Int(integer) = index.py_value(vm) else { + unreachable!("py_index returned an integer"); + }; + Ok(allocate_string_no_interning(integer.radix_repr(2, vm), vm.heap)) +} diff --git a/crates/bashkit-monty/src/builtins/chr.rs b/crates/bashkit-monty/src/builtins/chr.rs new file mode 100644 index 000000000..3c59d0e25 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/chr.rs @@ -0,0 +1,22 @@ +//! Implementation of the chr() builtin function. + +use crate::{ + args::ArgValues, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + types::str::allocate_char, + value::Value, +}; + +/// Returns the character at an `__index__`-compatible Unicode code point. +pub fn builtin_chr(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("chr", vm.heap)?; + defer_drop!(value, vm); + let index = value.saturating_index(vm)?; + if let Some(c) = u32::try_from(index).ok().and_then(char::from_u32) { + Ok(allocate_char(c, vm.heap)) + } else { + Err(ExcType::value_error("chr() arg not in range(0x110000)")) + } +} diff --git a/crates/bashkit-monty/src/builtins/divmod.rs b/crates/bashkit-monty/src/builtins/divmod.rs new file mode 100644 index 000000000..2d809123a --- /dev/null +++ b/crates/bashkit-monty/src/builtins/divmod.rs @@ -0,0 +1,15 @@ +//! Implementation of the divmod() builtin function. + +use crate::{args::ArgValues, bytecode::VM, defer_drop, exception_private::RunResult, value::Value}; + +/// Implementation of the divmod() builtin function. +/// +/// Returns a tuple `(quotient, remainder)` equivalent to `(a // b, a % b)`. +/// The per-type arithmetic lives with the types themselves, reached through +/// `__divmod__` / `__rdivmod__` like every other numeric operation. +pub fn builtin_divmod(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (a, b) = args.get_two_args("divmod", vm.heap)?; + defer_drop!(a, vm); + defer_drop!(b, vm); + a.py_divmod(b, vm) +} diff --git a/crates/bashkit-monty/src/builtins/enumerate.rs b/crates/bashkit-monty/src/builtins/enumerate.rs new file mode 100644 index 000000000..ee4bbd2a0 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/enumerate.rs @@ -0,0 +1,161 @@ +//! Implementation of the enumerate() builtin function. + +use smallvec::smallvec; + +use crate::{ + args::ArgValues, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult, SimpleException}, + heap::{DropGuard, DropWithContext, HeapData}, + types::{List, allocate_tuple}, + value::Value, +}; + +/// Implementation of the enumerate() builtin function. +/// +/// Returns a list of (index, value) tuples. +/// Note: In Python this returns an iterator, but we return a list for simplicity. +pub fn builtin_enumerate(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (iterable, start) = extract_enumerate_args(args, vm)?; + // Guard `start` before building the iterator: a non-iterable `iterable` + // errors out of `py_iter`, and a heap-backed start must not leak. + defer_drop!(start, vm); + let iter = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iter, vm); + let mut iter = iter.read(vm); + + // Get start index (default 0) + let mut index: i64 = match start { + Some(Value::Int(n)) => *n, + Some(Value::Bool(b)) => i64::from(*b), + Some(v) => { + let type_name = v.py_type_name(vm); + return Err(SimpleException::new_msg( + ExcType::TypeError, + format!("'{type_name}' object cannot be interpreted as an integer"), + ) + .into()); + } + None => 0, + }; + + let result: Vec = Vec::new(); + let mut result_guard = DropGuard::new(result, vm); + let (result, vm) = result_guard.as_parts_mut(); + + while let Some(item) = iter.py_next(vm)? { + // Create tuple (index, item) + let tuple_val = allocate_tuple(smallvec![Value::Int(index), item], vm.heap); + result.push(tuple_val); + index += 1; + } + + let (result, vm) = result_guard.into_parts(); + let heap_id = vm.heap.allocate(HeapData::List(List::new(result))); + Ok(Value::Ref(heap_id)) +} + +/// Extracts `enumerate(iterable, start=0)` arguments, faithfully mirroring +/// CPython's hand-written `enumerate_vectorcall` (Objects/enumobject.c) — +/// which `#[derive(FromArgs)]` cannot express. Its quirks are deliberate: +/// keyword names are validated by *position* against the accepted shapes, and +/// zero positionals with an unrecognised keyword shape reports the missing +/// `iterable` even when `iterable=` was actually passed. +fn extract_enumerate_args(args: ArgValues, vm: &mut VM<'_>) -> RunResult<(Value, Option)> { + let (mut pos, kwargs) = args.into_parts(); + let n_pos = pos.len(); + let total = n_pos + kwargs.len(); + let mut kw = kwargs.into_iter(); + // Pull up to two of each stream; each accepted call shape is one pattern + // arm, and the catch-all owns the leftovers on the arity-error path. + match (pos.next(), pos.next(), kw.next(), kw.next()) { + // enumerate(x) / enumerate(x, s) + (Some(iterable), start, None, None) if total <= 2 => Ok((iterable, start)), + // enumerate(x, start=s) + (Some(iterable), None, Some(kv), None) => match take_kwarg(kv, "start", vm) { + Ok(start) => Ok((iterable, Some(start))), + Err(err) => { + iterable.drop_with(vm); + Err(err) + } + }, + // enumerate(iterable=x) + (None, None, Some(kv), None) => Ok((take_kwarg(kv, "iterable", vm)?, None)), + // enumerate(iterable=x, start=s) — either keyword order + (None, None, Some(kv0), Some(kv1)) if total == 2 => two_kwarg_form(kv0, kv1, vm), + // Anything else is an arity error. + (p0, p1, k0, k1) => { + ((p0, p1), (k0, k1)).drop_with(vm); + pos.drop_with(vm); + kw.drop_with(vm); + if n_pos == 0 { + // CPython reports the missing `iterable` for every + // zero-positional shape it doesn't recognise — even + // `enumerate(start=1, x=1, iterable=[1])`. + Err(ExcType::type_error_missing_required_no_pos("enumerate", "iterable")) + } else { + // `n_pos > 0` in this arm, so never the all-keyword wording. + Err(ExcType::type_error_method_at_most("enumerate", 2, total, false)) + } + } + } +} + +/// The `enumerate(iterable=..., start=...)` form: CPython accepts both +/// keyword orders, checking `start` first and reporting the first +/// out-of-place name. +fn two_kwarg_form(kv0: (Value, Value), kv1: (Value, Value), vm: &mut VM<'_>) -> RunResult<(Value, Option)> { + // Decide the shape by reference before any ownership moves. + let swapped = key_check(&kv0.0, "start", vm).is_ok(); + let checked = if swapped { + key_check(&kv1.0, "iterable", vm) + } else { + key_check(&kv0.0, "iterable", vm).and(key_check(&kv1.0, "start", vm)) + }; + match checked { + Ok(()) => { + let ((key0, val0), (key1, val1)) = (kv0, kv1); + (key0, key1).drop_with(vm); + Ok(if swapped { + (val1, Some(val0)) + } else { + (val0, Some(val1)) + }) + } + Err(err) => { + (kv0, kv1).drop_with(vm); + Err(err) + } + } +} + +/// Consumes a kwarg pair, returning its value if the key is `expected`. +fn take_kwarg(kv: (Value, Value), expected: &str, vm: &mut VM<'_>) -> RunResult { + match key_check(&kv.0, expected, vm) { + Ok(()) => { + let (key, value) = kv; + key.drop_with(vm); + Ok(value) + } + Err(err) => { + kv.drop_with(vm); + Err(err) + } + } +} + +/// Errors unless `key` is the string `expected`, mirroring CPython's +/// `check_keyword`: a non-string key raises `keywords must be strings`, any +/// other name the `invalid keyword argument` wording. +fn key_check(key: &Value, expected: &str, vm: &VM<'_>) -> RunResult<()> { + let Some(key) = key.as_either_str(vm.heap) else { + return Err(ExcType::type_error_kwargs_nonstring_key()); + }; + let key = key.as_str(vm.interns); + if key == expected { + Ok(()) + } else { + Err(ExcType::type_error_invalid_keyword_argument("enumerate", key)) + } +} diff --git a/crates/bashkit-monty/src/builtins/eval_exec.rs b/crates/bashkit-monty/src/builtins/eval_exec.rs new file mode 100644 index 000000000..0d19a0df6 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/eval_exec.rs @@ -0,0 +1,276 @@ +//! Implementation of the eval() and exec() builtin functions. +//! +//! Both compile their source at runtime against the session's intern tables +//! and push a frame for it, so the snippet runs like a called function: it +//! can suspend to the host, and its result lands on the caller's stack. + +use std::{str, sync::Arc}; + +use crate::{ + args::{ArgValues, FromArgs, Signature}, + bytecode::{CallResult, Compiler, FrameNamespace, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + expressions::{Identifier, Node}, + function::Function, + heap::{DropGuard, HeapData, HeapId}, + intern::{CompileInterns, FunctionId, StaticStrings}, + name_map::NameMap, + parse::{CodeRange, parse_expression_with_interner, parse_module_with_filename_id}, + prepare::{SnippetNames, prepare_snippet}, + types::{Type, py_trait::PyTrait}, + value::Value, +}; + +/// Arguments of `eval(source, /, globals=None, locals=None)`. +#[derive(FromArgs)] +#[from_args(name = "eval", at_most_total)] +struct EvalArgs { + #[from_args(pos_only)] + source: Value, + #[from_args(default = Value::None)] + globals: Value, + #[from_args(default = Value::None)] + locals: Value, +} + +/// Arguments of `exec(source, /, globals=None, locals=None, *, closure=None)`. +#[derive(FromArgs)] +#[from_args(name = "exec")] +struct ExecArgs { + #[from_args(pos_only)] + source: Value, + #[from_args(default = Value::None)] + globals: Value, + #[from_args(default = Value::None)] + locals: Value, + #[from_args(kw_only, default = Value::None)] + closure: Value, +} + +/// Implementation of the `eval()` builtin function. +/// +/// Parses `source` as one expression and runs it in the given (or the +/// caller's) namespace; the expression's value is the call's result. +pub fn builtin_eval(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let EvalArgs { + source, + globals, + locals, + } = EvalArgs::from_args(args, vm)?; + defer_drop!(source, vm); + defer_drop!(globals, vm); + defer_drop!(locals, vm); + + let text = snippet_source("eval", source, vm)?; + let globals = globals_dict(globals, Builtin::Eval, vm)?; + let locals = locals_dict(locals, Builtin::Eval, vm)?; + run_snippet(Builtin::Eval, &text, globals, locals, vm) +} + +/// Implementation of the `exec()` builtin function. +/// +/// Compiles `source` as a module and runs it in the given (or the caller's) +/// namespace; the call's result is `None`. +pub fn builtin_exec(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ExecArgs { + source, + globals, + locals, + closure, + } = ExecArgs::from_args(args, vm)?; + defer_drop!(source, vm); + defer_drop!(globals, vm); + defer_drop!(locals, vm); + defer_drop!(closure, vm); + + if !matches!(closure, Value::None) { + return Err(ExcType::type_error( + "closure can only be used when source is a code object", + )); + } + let text = snippet_source("exec", source, vm)?; + let globals = globals_dict(globals, Builtin::Exec, vm)?; + let locals = locals_dict(locals, Builtin::Exec, vm)?; + run_snippet(Builtin::Exec, &text, globals, locals, vm) +} + +/// Which builtin is running: the two parse differently and word their +/// argument errors differently. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Builtin { + Eval, + Exec, +} + +/// Compiles `source` in the namespace `globals` / `locals` describe (borrowed +/// dict ids, validated by the caller) and pushes its frame. +fn run_snippet( + builtin: Builtin, + source: &Arc, + globals: Option, + locals: Option, + vm: &mut VM<'_>, +) -> RunResult { + if source.contains('\0') { + return Err( + SimpleException::new_msg(ExcType::SyntaxError, "source code string cannot contain null bytes").into(), + ); + } + for dict in globals.into_iter().chain(locals) { + vm.heap.inc_ref(dict); + } + let (names, namespace) = vm.snippet_namespace(globals, locals)?; + let globals_len = vm.global_names.len(); + let result = compile_and_push(builtin, source, names, namespace, vm); + if result.is_err() { + vm.global_names.truncate(globals_len); + } + result +} + +/// Compiles privately and publishes only after the snippet's frame is admitted. +fn compile_and_push( + builtin: Builtin, + source: &Arc, + names: SnippetNames, + namespace: Box, + vm: &mut VM<'_>, +) -> RunResult { + let mut namespace_guard = DropGuard::new(namespace, vm); + let (_, vm) = namespace_guard.as_parts_mut(); + let mut overlay = CompileInterns::new(vm.interns); + let filename_id = overlay.add_eval_source(Arc::clone(source)); + let options = vm.env.options; + let nodes = match builtin { + Builtin::Exec => { + parse_module_with_filename_id(source, filename_id, &mut overlay, options.source_scan_threshold) + } + Builtin::Eval => { + let trimmed = source.trim_start(); + let skipped = u32::try_from(source.len() - trimmed.len()).unwrap_or(u32::MAX); + parse_expression_with_interner(trimmed, filename_id, &mut overlay, options.source_scan_threshold) + .map(|expr| vec![Node::Return(Some(expr))]) + .map_err(|e| e.shifted(skipped)) + } + } + .map_err(|e| e.into_run_error(source))?; + + let globals_by_name = names == SnippetNames::NameOverDict; + let mut scratch = NameMap::new(); + let globals = if globals_by_name { + &mut scratch + } else { + &mut *vm.global_names + }; + let nodes = prepare_snippet(nodes, &overlay, globals, names).map_err(|e| e.into_run_error(source))?; + let code = Compiler::compile_snippet(&nodes, &mut overlay, globals, options, globals_by_name) + .map_err(|e| e.into_run_error(source))?; + + let position = CodeRange { + filename: filename_id, + start_byte: 0, + end_byte: u32::try_from(source.len()).unwrap_or(u32::MAX), + }; + let function = Function::new( + Identifier::new(overlay.intern_static(StaticStrings::Module), position), + Signature::default(), + 0, + Vec::new(), + Vec::new(), + Vec::new(), + Vec::new(), + 0, + false, + code, + ); + let index = overlay.functions_len(); + let func_id = u16::try_from(index).map(FunctionId::from_index).map_err(|_| { + SimpleException::new_msg( + ExcType::SyntaxError, + format!("session defines too many functions; maximum is {}", u16::MAX), + ) + })?; + + overlay.push_function(function); + let (namespace, vm) = namespace_guard.into_parts(); + vm.push_snippet_frame(func_id, overlay, namespace)?; + vm.globals.resize_with(vm.global_names.len(), || Value::Undefined); + Ok(CallResult::FramePushed) +} + +/// The snippet's text: a `str`, or `bytes` decoded as UTF-8. +fn snippet_source(name: &str, source: &Value, vm: &mut VM<'_>) -> RunResult> { + let bytes: &[u8] = match source { + Value::InternString(id) => return Ok(Arc::from(vm.interns.get_str(*id))), + Value::InternBytes(id) => vm.interns.get_bytes(*id), + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Str(s) => return Ok(Arc::from(s.as_str())), + HeapData::Bytes(b) => b.as_slice(), + _ => return Err(source_type_error(name)), + }, + _ => return Err(source_type_error(name)), + }; + match str::from_utf8(bytes) { + Ok(text) => Ok(Arc::from(text)), + Err(err) => { + let bad = bytes[err.valid_up_to()]; + let line = bytes[..err.valid_up_to()].split(|b| *b == b'\n').count(); + Err(SimpleException::new_msg( + ExcType::SyntaxError, + format!( + "Non-UTF-8 code starting with '\\x{bad:02x}' on line {line}, but no encoding declared; \ + see https://peps.python.org/pep-0263/ for details (, line {line})" + ), + ) + .into()) + } + } +} + +/// `TypeError` for a `source` that is neither text nor bytes. +fn source_type_error(name: &str) -> RunError { + ExcType::type_error(format!("{name}() arg 1 must be a string, bytes or code object")) +} + +/// Validates the `globals` argument: `None`, or a dict whose id is returned (borrowed). +fn globals_dict(globals: &Value, builtin: Builtin, vm: &mut VM<'_>) -> RunResult> { + match globals { + Value::None => Ok(None), + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::Dict(_)) => Ok(Some(*id)), + other => { + let ty = other.py_type(vm); + Err(match builtin { + // CPython distinguishes a non-dict mapping (anything subscriptable) from the rest. + Builtin::Eval + if matches!( + ty, + Type::List | Type::Tuple | Type::Str | Type::Bytes | Type::Range | Type::Deque + ) => + { + ExcType::type_error("globals must be a real dict; try eval(expr, {}, mapping)") + } + Builtin::Eval => ExcType::type_error("globals must be a dict"), + Builtin::Exec => ExcType::type_error(format!( + "exec() globals must be a dict, not {}", + ty.name(vm.heap, vm.interns) + )), + }) + } + } +} + +/// Validates the `locals` argument: `None`, or a dict whose id is returned (borrowed). +fn locals_dict(locals: &Value, builtin: Builtin, vm: &mut VM<'_>) -> RunResult> { + match locals { + Value::None => Ok(None), + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::Dict(_)) => Ok(Some(*id)), + other => Err(match builtin { + Builtin::Eval => ExcType::type_error("locals must be a mapping"), + Builtin::Exec => ExcType::type_error(format!( + "locals must be a mapping or None, not {}", + other.py_type(vm).name(vm.heap, vm.interns) + )), + }), + } +} diff --git a/crates/bashkit-monty/src/builtins/filter.rs b/crates/bashkit-monty/src/builtins/filter.rs new file mode 100644 index 000000000..af8173872 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/filter.rs @@ -0,0 +1,63 @@ +//! Implementation of the filter() builtin function. +//! +//! This module provides the filter() builtin which filters elements from an iterable +//! based on a predicate function. The implementation supports: +//! - `None` as predicate (filters falsy values) +//! - Builtin functions (len, abs, etc.) +//! - Type constructors (int, str, float, etc.) +//! - User-defined functions (via `call_predicate`) + +use crate::{ + args::ArgValues, + bytecode::VM, + defer_drop, + exception_private::RunResult, + heap::{DropGuard, HeapData}, + predicate::call_predicate, + types::{List, PyTrait}, + value::Value, +}; + +/// Implementation of the filter() builtin function. +/// +/// Filters elements from an iterable based on a predicate function. +/// If the predicate is None, filters out falsy values. +/// +/// Note: In Python this returns an iterator, but we return a list for simplicity. +/// +/// Examples: +/// ```python +/// filter(lambda x: x > 0, [-1, 0, 1, 2]) # [1, 2] +/// filter(None, [0, 1, False, True, '']) # [1, True] +/// ``` +pub fn builtin_filter(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (function, iterable) = args.get_two_args("filter", vm.heap)?; + defer_drop!(function, vm); + + let iter = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iter, vm); + let mut iter = iter.read(vm); + + let out: Vec = Vec::new(); + let mut out_guard = DropGuard::new(out, vm); + let (out, vm) = out_guard.as_parts_mut(); + + while let Some(item) = iter.py_next(vm)? { + let mut item_guard = DropGuard::new(item, vm); + let (item, vm) = item_guard.as_parts_mut(); + let should_include = if let Value::None = function { + // No predicate - use truthiness of element + item.py_bool(vm)? + } else { + call_predicate(function, item, vm)? + }; + + if should_include { + out.push(item_guard.into_inner()); + } + } + + let (out, vm) = out_guard.into_parts(); + let heap_id = vm.heap.allocate(HeapData::List(List::new(out))); + Ok(Value::Ref(heap_id)) +} diff --git a/crates/bashkit-monty/src/builtins/format.rs b/crates/bashkit-monty/src/builtins/format.rs new file mode 100644 index 000000000..32c3acdf7 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/format.rs @@ -0,0 +1,41 @@ +//! Implementation of the format() builtin function. + +use crate::{ + args::{ArgValues, FromArgs, StrArg}, + bytecode::VM, + defer_drop, + exception_private::RunResult, + types::str::allocate_string, + value::Value, +}; + +/// Argument shape for `format(value, format_spec='', /)`. +/// +/// CPython parses it with `PyArg_ParseTuple`, so `style = unpack` gives the +/// `format expected at most 2 arguments` arity wording and the blanket +/// `format() takes no keyword arguments` rejection; `bad_arg` supplies +/// `format() argument 2 must be str, not int`. +#[derive(FromArgs)] +#[from_args(name = "format", style = unpack, bad_arg)] +struct FormatArgs { + #[from_args(pos_only)] + value: Value, + #[from_args(pos_only, default)] + format_spec: Option, +} + +/// Implementation of the format() builtin function. +/// +/// Applies a format-spec mini-language string to a value, sharing the runtime +/// path f-strings and `str.format()` use, so every spec and error behaves the +/// same across all three entry points. +pub fn builtin_format(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let FormatArgs { value, format_spec } = FormatArgs::from_args(args, vm)?; + defer_drop!(value, vm); + defer_drop!(format_spec, vm); + // The spec borrows `vm`, which the formatter needs mutably; it is already + // tracked so copying it out is bounded. + let spec = format_spec.as_ref().map(|spec| spec.as_str(vm).to_owned()); + let formatted = vm.format_runtime_value(value, 0, spec.as_deref())?; + Ok(allocate_string(formatted, vm.heap)) +} diff --git a/crates/bashkit-monty/src/builtins/getattr.rs b/crates/bashkit-monty/src/builtins/getattr.rs new file mode 100644 index 000000000..5b95e0b16 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/getattr.rs @@ -0,0 +1,82 @@ +//! Implementation of the getattr() builtin function. + +use monty_types::ExcType; + +use crate::{ + args::ArgValues, + bytecode::{CallResult, PendingLookupEffect, VM}, + defer_drop, + exception_private::{ExcTypeExt, RunError, RunResult, SimpleException}, + heap::DropWithContext, +}; + +/// Implementation of the getattr() builtin function. +/// +/// Returns the value of the named attribute of an object. +/// If the attribute doesn't exist and a default is provided, returns the default. +/// If no default is provided and the attribute doesn't exist, raises AttributeError. +/// +/// Note: name must be a string. Per Python docs, "Since private name mangling happens +/// at compilation time, one must manually mangle a private attribute's (attributes with +/// two leading underscores) name in order to retrieve it with getattr()." +/// +/// A lazy attribute on a host-backed object suspends to the host like +/// `obj.attr` does; the `default` rides along as a [`PendingLookupEffect`] +/// so an `Undefined` answer yields it instead of raising. +/// +/// Examples: +/// ```python +/// getattr(obj, 'x') # Get obj.x +/// getattr(obj, 'y', None) # Get obj.y or None if not found +/// getattr(module, 'function') # Get module.function +/// ``` +pub fn builtin_getattr(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let positional = args.into_pos_only("getattr", vm.heap)?; + defer_drop!(positional, vm); + + let (object, name, default) = match positional.as_slice() { + too_few @ ([] | [_]) => return Err(ExcType::type_error_at_least("getattr", 2, too_few.len())), + [object, name] => (object, name, None), + [object, name, default] => (object, name, Some(default)), + too_many => return Err(ExcType::type_error_at_most("getattr", 3, too_many.len())), + }; + + let Some(attr) = name.as_either_str(vm.heap).map(|s| s.resolve_interned(vm.interns)) else { + let ty = name.py_type_name(vm); + return Err( + SimpleException::new_msg(ExcType::TypeError, format!("attribute name must be string, not '{ty}'")).into(), + ); + }; + + match object.py_getattr(&attr, vm) { + Ok(CallResult::Value(value)) => Ok(CallResult::Value(value)), + Ok(CallResult::AttrLookup { + name, + class_name, + object_id, + type_object, + effect: _, + }) => Ok(CallResult::AttrLookup { + name, + class_name, + object_id, + type_object, + effect: default.map(|d| PendingLookupEffect::Default(d.clone_with_heap(vm))), + }), + Ok(other) => { + other.drop_with(vm); + // getattr() only retrieves attribute values — OS calls, external calls, + // method calls, and awaits are not supported here + // + // TODO: might need to support this case? + Err(SimpleException::new_msg(ExcType::TypeError, "getattr(): attribute is not a simple value").into()) + } + Err(RunError::Exc(e)) + if let Some(d) = default + && e.exc.exc_type() == ExcType::AttributeError => + { + Ok(CallResult::Value(d.clone_with_heap(vm))) + } + Err(e) => Err(e), + } +} diff --git a/crates/bashkit-monty/src/builtins/hasattr.rs b/crates/bashkit-monty/src/builtins/hasattr.rs new file mode 100644 index 000000000..d6c1096f1 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/hasattr.rs @@ -0,0 +1,85 @@ +//! Implementation of the hasattr() builtin function. + +use monty_types::ExcType; + +use crate::{ + args::ArgValues, + bytecode::{CallResult, PendingLookupEffect, VM}, + defer_drop, + exception_private::{ExcTypeExt, RunError, RunResult, SimpleException}, + heap::DropWithContext, + value::Value, +}; + +/// Implementation of the hasattr() builtin function. +/// +/// Returns True if the object has the named attribute, False otherwise. +/// This function always succeeds and never raises AttributeError. +/// +/// Signature: `hasattr(object, name)` +/// +/// Note: This is implemented by calling getattr(object, name) and returning +/// True if it succeeds, False if it raises an exception. A lazy attribute on a +/// host-backed object suspends to the host like `obj.attr` does, with a +/// [`PendingLookupEffect::HasAttr`] turning the answer into the bool. +/// +/// Examples: +/// ```python +/// hasattr(obj, 'x') # Check if obj.x exists +/// hasattr(slice(1, 10), 'start') # True - slice has start attribute +/// hasattr(42, 'nonexistent') # False - int has no such attribute +/// ``` +pub fn builtin_hasattr(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let positional = args.into_pos_only("hasattr", vm.heap)?; + defer_drop!(positional, vm); + + let (object, name) = match positional.as_slice() { + [object, name] => (object, name), + other => return Err(ExcType::type_error_arg_count("hasattr", 2, other.len())), + }; + + let Some(name) = name.as_either_str(vm.heap).map(|s| s.resolve_interned(vm.interns)) else { + return Err(SimpleException::new_msg( + ExcType::TypeError, + format!("attribute name must be string, not '{}'", name.py_type_name(vm)), + ) + .into()); + }; + + // important: we must own the returned value if py_get_attr succeeds to drop it + let has_attr = match object.py_getattr(&name, vm) { + Ok(CallResult::Value(value)) => { + value.drop_with(vm); + true + } + Ok(CallResult::AttrLookup { + name, + class_name, + object_id, + type_object, + effect: _, + }) => { + return Ok(CallResult::AttrLookup { + name, + class_name, + object_id, + type_object, + effect: Some(PendingLookupEffect::HasAttr), + }); + } + Ok(other) => { + other.drop_with(vm); + // hasattr() only tests attribute values — OS calls, external calls, + // method calls, and awaits are not supported here + // + // TODO: might need to support this case? + return Err( + SimpleException::new_msg(ExcType::TypeError, "hasattr(): attribute is not a simple value").into(), + ); + } + Err(RunError::Exc(e)) if e.exc.exc_type() == ExcType::AttributeError => false, + Err(e) => return Err(e), + }; + + Ok(CallResult::Value(Value::Bool(has_attr))) +} diff --git a/crates/bashkit-monty/src/builtins/hash.rs b/crates/bashkit-monty/src/builtins/hash.rs new file mode 100644 index 000000000..d7a741918 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/hash.rs @@ -0,0 +1,25 @@ +//! Implementation of the hash() builtin function. + +use crate::{ + args::ArgValues, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + value::Value, +}; + +/// Implementation of the hash() builtin function. +/// +/// Returns the hash value of an object (if it has one). +/// Raises TypeError for unhashable types like lists and dicts. +pub fn builtin_hash(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("hash", vm.heap)?; + defer_drop!(value, vm); + match value.py_hash(vm)? { + Some(hash) => { + // Python's hash() returns a signed integer; reinterpret bits for large values + Ok(Value::Int(hash.raw().cast_signed())) + } + None => Err(ExcType::type_error_unhashable(&value.py_type_name(vm))), + } +} diff --git a/crates/bashkit-monty/src/builtins/hex.rs b/crates/bashkit-monty/src/builtins/hex.rs new file mode 100644 index 000000000..e2fac44b0 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/hex.rs @@ -0,0 +1,19 @@ +//! Implementation of the hex() builtin function. + +use crate::{ + args::ArgValues, bytecode::VM, defer_drop, exception_private::RunResult, py_value::PyValue, + types::str::allocate_string_no_interning, value::Value, +}; + +/// Converts an integer or `__index__` result to a hexadecimal string prefixed with `0x`. +pub fn builtin_hex(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("hex", vm.heap)?; + defer_drop!(value, vm); + let index = value.py_index(vm)?; + defer_drop!(index, vm); + + let PyValue::Int(integer) = index.py_value(vm) else { + unreachable!("py_index returned an integer"); + }; + Ok(allocate_string_no_interning(integer.radix_repr(16, vm), vm.heap)) +} diff --git a/crates/bashkit-monty/src/builtins/id.rs b/crates/bashkit-monty/src/builtins/id.rs new file mode 100644 index 000000000..410bb9583 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/id.rs @@ -0,0 +1,13 @@ +//! Implementation of the id() builtin function. + +use crate::{args::ArgValues, bytecode::VM, defer_drop, exception_private::RunResult, value::Value}; + +/// Implementation of the id() builtin function. +/// +/// Returns the identity of an object (unique integer for the object's lifetime). +pub fn builtin_id(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("id", vm.heap)?; + defer_drop!(value, vm); + + Ok(value.id().into_value(vm.heap)) +} diff --git a/crates/bashkit-monty/src/builtins/isinstance.rs b/crates/bashkit-monty/src/builtins/isinstance.rs new file mode 100644 index 000000000..eaf29e368 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/isinstance.rs @@ -0,0 +1,142 @@ +//! Implementation of the isinstance() builtin function. + +use super::Builtins; +use crate::{ + args::ArgValues, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{HeapData, HeapId, HeapRead, HeapReadOutput}, + types::{PyTrait, Tuple, Type}, + value::Value, +}; + +/// Implementation of the isinstance() builtin function. +/// +/// Checks if an object is an instance of a class or a tuple of classes. +pub fn builtin_isinstance(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (obj, classinfo) = args.get_two_args("isinstance", vm.heap)?; + defer_drop!(obj, vm); + defer_drop!(classinfo, vm); + + isinstance_check(obj, classinfo, vm).map(Value::Bool) +} + +/// Checks if `obj` matches a single classinfo entry. +/// +/// Supports: +/// - Single builtin types: `isinstance(x, int)` +/// - Exception types and their hierarchy: `isinstance(err, LookupError)` +/// - User-defined classes: `isinstance(obj, Foo)` (identity of the instance's +/// class; there is no inheritance chain to walk yet) +/// - Host classes: `isinstance(obj, Point)` for a `HostClassType` (exact class +/// id; the host sends no bases) +/// - Tuples (possibly nested) of the above +pub(crate) fn isinstance_check(obj: &Value, classinfo: &Value, vm: &mut VM<'_>) -> RunResult { + match classinfo { + Value::Builtin(Builtins::Type(t)) => Ok(obj.py_type(vm).is_instance_of(*t)), + Value::Builtin(Builtins::ExcType(handler_type)) => { + Ok(matches!(obj.py_type(vm), Type::Exception(exc_type) if exc_type.is_subclass_of(*handler_type))) + } + // A user-defined class: true iff `obj` is an instance of exactly this class. + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::Class(_)) => Ok(instance_of_class(obj, *id, vm)), + // A `collections.namedtuple` class, matched by the instance's `class_id`. + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::NamedTupleClass(_)) => { + Ok(instance_of_namedtuple_class(obj, *id, vm)) + } + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::HostClassType(_)) => { + Ok(instance_of_host_class(obj, *id, vm)) + } + Value::Ref(id) if let HeapReadOutput::Tuple(tuple) = vm.heap.read(*id) => { + isinstance_check_tuple(obj, &tuple, vm) + } + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::GenericAlias(_)) => { + Err(ExcType::isinstance_parameterized_generic()) + } + // `int | None`: true when any member matches, tested in order. + Value::Ref(id) if let HeapData::Union(union) = vm.heap.get(*id) => { + let args = union.args(vm.heap); + defer_drop!(args, vm); + let Some(HeapReadOutput::Tuple(members)) = args.read_heap(vm) else { + unreachable!("Union::args is always a tuple") + }; + isinstance_check_tuple(obj, &members, vm) + } + _ => Err(ExcType::isinstance_arg2_error()), + } +} + +/// Whether `obj` is a host instance whose class entry is `class_id` (exact +/// class only: the host never sends bases, so subclasses are unknown). +fn instance_of_host_class(obj: &Value, class_id: HeapId, vm: &VM<'_>) -> bool { + matches!(obj, Value::Ref(obj_id) if matches!(vm.heap.get(*obj_id), HeapData::HostClass(hc) if hc.class_id() == class_id)) +} + +/// Whether `obj` is an instance whose class object is `class_id`. +fn instance_of_class(obj: &Value, class_id: HeapId, vm: &VM<'_>) -> bool { + matches!(obj, Value::Ref(obj_id) if matches!(vm.heap.get(*obj_id), HeapData::Instance(inst) if inst.class() == class_id)) +} + +/// Whether `obj` is a namedtuple instance built from the class `class_id`. +/// +/// Instances created by Monty internally (`sys.version_info`, host imports) +/// carry no `class_id`, so they never match a factory class. +fn instance_of_namedtuple_class(obj: &Value, class_id: HeapId, vm: &VM<'_>) -> bool { + matches!(obj, Value::Ref(obj_id) if matches!(vm.heap.get(*obj_id), HeapData::NamedTuple(nt) if nt.class_id() == Some(class_id))) +} + +/// Recursively walks a tuple of classinfo entries. +fn isinstance_check_tuple<'h>(obj: &Value, tuple: &HeapRead<'h, Tuple>, vm: &mut VM<'h>) -> RunResult { + let len = tuple.get(vm.heap).as_slice().len(); + let mut guard = vm.recursion_guard()?; + let vm = &mut *guard; + for i in 0..len { + match &tuple.get(vm.heap).as_slice()[i] { + Value::Builtin(Builtins::Type(t)) => { + if obj.py_type(vm).is_instance_of(*t) { + return Ok(true); + } + } + Value::Builtin(Builtins::ExcType(exc)) => { + if matches!(obj.py_type(vm), Type::Exception(et) if et.is_subclass_of(*exc)) { + return Ok(true); + } + } + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::Class(_)) => { + if instance_of_class(obj, *id, vm) { + return Ok(true); + } + } + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::NamedTupleClass(_)) => { + if instance_of_namedtuple_class(obj, *id, vm) { + return Ok(true); + } + } + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::HostClassType(_)) => { + if instance_of_host_class(obj, *id, vm) { + return Ok(true); + } + } + Value::Ref(nested_id) if let HeapReadOutput::Tuple(nested) = vm.heap.read(*nested_id) => { + if isinstance_check_tuple(obj, &nested, vm)? { + return Ok(true); + } + } + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::GenericAlias(_)) => { + return Err(ExcType::isinstance_parameterized_generic()); + } + Value::Ref(id) if let HeapData::Union(union) = vm.heap.get(*id) => { + let args = union.args(vm.heap); + defer_drop!(args, vm); + let Some(HeapReadOutput::Tuple(members)) = args.read_heap(vm) else { + unreachable!("Union::args is always a tuple") + }; + if isinstance_check_tuple(obj, &members, vm)? { + return Ok(true); + } + } + _ => return Err(ExcType::isinstance_arg2_error()), + } + } + Ok(false) +} diff --git a/crates/bashkit-monty/src/builtins/iter.rs b/crates/bashkit-monty/src/builtins/iter.rs new file mode 100644 index 000000000..0a67b5fd9 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/iter.rs @@ -0,0 +1,39 @@ +//! Argument handling for `iter(object[, sentinel])`. + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::{CallResult, VM}, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::HeapData, + types::callable_iterator::CallableIterator, + value::Value, +}; + +/// Acquires an iterator or creates a callable iterator which stops at its sentinel. +pub(crate) fn builtin_iter(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let IterArgs { object, sentinel } = IterArgs::from_args(args, vm)?; + if let Some(sentinel) = sentinel { + if object.is_callable(vm) { + let iter = CallableIterator::new(object, sentinel); + Ok(CallResult::Value(Value::Ref( + vm.heap.allocate(HeapData::CallableIterator(iter)), + ))) + } else { + object.drop_with(vm); + sentinel.drop_with(vm); + Err(ExcType::type_error("iter(v, w): v must be callable")) + } + } else { + object.into_py_iter(vm) + } +} + +/// Argument shape for `iter(object, /)` and `iter(object, sentinel, /)`. +#[derive(FromArgs)] +#[from_args(name = "iter", style = unpack)] +struct IterArgs { + #[from_args(pos_only)] + object: Value, + #[from_args(pos_only, default)] + sentinel: Option, +} diff --git a/crates/bashkit-monty/src/builtins/len.rs b/crates/bashkit-monty/src/builtins/len.rs new file mode 100644 index 000000000..5d15f859b --- /dev/null +++ b/crates/bashkit-monty/src/builtins/len.rs @@ -0,0 +1,26 @@ +//! Implementation of the len() builtin function. + +use crate::{ + args::ArgValues, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult, SimpleException}, + types::PyTrait, + value::Value, +}; + +/// Implementation of the len() builtin function. +/// +/// Returns the length of an object (number of items in a container). +pub fn builtin_len(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("len", vm.heap)?; + defer_drop!(value, vm); + if let Some(len) = value.py_len(vm) { + Ok(Value::Int( + i64::try_from(len).map_err(|_| ExcType::overflow_c_ssize_t())?, + )) + } else { + let type_name = value.py_type_name(vm); + Err(SimpleException::new_msg(ExcType::TypeError, format!("object of type '{type_name}' has no len()")).into()) + } +} diff --git a/crates/bashkit-monty/src/builtins/locals.rs b/crates/bashkit-monty/src/builtins/locals.rs new file mode 100644 index 000000000..ddd7de14a --- /dev/null +++ b/crates/bashkit-monty/src/builtins/locals.rs @@ -0,0 +1,14 @@ +//! Implementation of the locals() builtin function. + +use crate::{args::ArgValues, bytecode::VM, exception_private::RunResult, value::Value}; + +/// Implementation of the `locals()` builtin function. +/// +/// Inside a function this is a snapshot of the frame's local variables +/// (PEP 667: writes to the dict never reach the frame), at module scope a +/// snapshot of the bound globals, and inside an `exec()` / `eval()` snippet +/// the namespace dict the snippet runs in. See `limitations/eval_exec.md`. +pub fn builtin_locals(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + args.check_zero_args("locals", vm.heap)?; + vm.locals_dict() +} diff --git a/crates/bashkit-monty/src/builtins/map.rs b/crates/bashkit-monty/src/builtins/map.rs new file mode 100644 index 000000000..47eb6eda4 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/map.rs @@ -0,0 +1,135 @@ +//! Implementation of the map() builtin function. + +use std::{iter, mem}; + +use crate::{ + args::{ArgValues, FromArgs, KwargsValues}, + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{DropGuard, DropWithContext, HeapData}, + types::{List, iter::checked_preallocation_hint}, + value::Value, +}; + +/// Implementation of the map() builtin function. +/// +/// Applies a function to every item of one or more iterables and returns a list of results. +/// With multiple iterables, stops when the shortest iterable is exhausted. +/// +/// Note: In Python this returns an iterator, but we return a list for simplicity. +/// Note: The `strict=` parameter is not yet supported. +/// +/// Examples: +/// ```python +/// map(abs, [-1, 0, 1, 2]) # [1, 0, 1, 2] +/// map(pow, [2, 3], [3, 2]) # [8, 9] +/// map(str, [1, 2, 3]) # ['1', '2', '3'] +/// ``` +pub fn builtin_map(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + // CPython's map() uses a bespoke arity message + // (`map() must have at least two arguments.`) rather than the generic + // "missing N required positional arguments" wording the macro would + // otherwise produce. Pre-check before delegating to MapArgs so we + // match byte-for-byte; cleanup is handled by the early-return drop. + // + // Only fire the arity check when no kwargs are present — otherwise + // `map(abs, bogus=1)` would report the arity error when CPython reports + // the unknown-kwarg error. Delegating to the macro produces the + // correct `got an unexpected keyword argument` message instead. + let kwargs_empty = match &args { + ArgValues::Kwargs(kwargs) => kwargs.is_empty(), + ArgValues::ArgsKargs { kwargs, .. } => kwargs.is_empty(), + _ => true, + }; + if args.count() < 2 && kwargs_empty { + args.drop_with(vm.heap); + return Err(ExcType::type_error_map_arity()); + } + let MapArgs { + function, + first_iterable, + extra_iterables, + } = MapArgs::from_args(args, vm)?; + defer_drop!(function, vm); + defer_drop_mut!(extra_iterables, vm); + + let first_iter = first_iterable.into_py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(first_iter, vm); + let mut first_iter = first_iter.read(vm); + + let extra_iterators: Vec = Vec::with_capacity(extra_iterables.len()); + defer_drop_mut!(extra_iterators, vm); + + for iterable in extra_iterables.drain(..) { + extra_iterators.push(iterable.into_py_iter(vm)?.require_synchronous(vm)?); + } + + // Validate and clamp the iterator's hint before reserving native memory. + let hint = first_iter.iter_size_hint(vm); + let capacity = checked_preallocation_hint(hint, mem::size_of::(), &vm.heap.tracker)?; + let out = Vec::with_capacity(capacity); + defer_drop_mut!(out, vm); + + // map function over iterables until the shortest iter is exhausted + match extra_iterators.as_mut_slice() { + // map(f, iter) + [] => { + while let Some(item) = first_iter.py_next(vm)? { + let args = ArgValues::One(item); + out.push(vm.evaluate_function(function, args)?); + } + } + // map(f, iter1, iter2) + [single] => { + while let Some(arg1) = first_iter.py_next(vm)? { + let mut arg1_guard = DropGuard::new(arg1, vm); + let Some(arg2) = single.py_next(arg1_guard.ctx())? else { + break; + }; + let (arg1, vm) = arg1_guard.into_parts(); + let args = ArgValues::Two(arg1, arg2); + out.push(vm.evaluate_function(function, args)?); + } + } + // map(f, iter1, iter2, *iterables) + multiple => 'outer: loop { + let items = Vec::with_capacity(1 + multiple.len()); + defer_drop_mut!(items, vm); + + for result in iter::once(first_iter.py_next(vm)).chain(multiple.iter_mut().map(|iter| iter.py_next(vm))) { + if let Some(item) = result? { + items.push(item); + } else { + break 'outer; + } + } + + let args = ArgValues::ArgsKargs { + args: mem::take(items), + kwargs: KwargsValues::Empty, + }; + + out.push(vm.evaluate_function(function, args)?); + }, + } + + let heap_id = vm.heap.allocate(HeapData::List(List::new(mem::take(out)))); + Ok(Value::Ref(heap_id)) +} + +/// Argument shape for `map(function, iterable, *iterables)`. +/// +/// `function` and the first `iterable` are required; any further iterables +/// are collected by `extra_iterables`. `map` doesn't accept kwargs, so the +/// macro's default unknown-kwarg error path is exactly what we want. +#[derive(FromArgs)] +#[from_args(name = "map")] +struct MapArgs { + #[from_args(pos_only)] + function: Value, + #[from_args(pos_only)] + first_iterable: Value, + #[from_args(varargs)] + extra_iterables: Vec, +} diff --git a/crates/bashkit-monty/src/builtins/min_max.rs b/crates/bashkit-monty/src/builtins/min_max.rs new file mode 100644 index 000000000..650a88a06 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/min_max.rs @@ -0,0 +1,243 @@ +//! Implementation of the min() and max() builtin functions. + +use std::{cmp::Ordering, mem}; + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::DropGuard, + types::{CmpOrder, PyTrait}, + value::Value, +}; + +/// Implementation of the min() builtin function. +/// +/// Returns the smallest item in an iterable or the smallest of two or more arguments. +/// Supports two forms: +/// - `min(iterable)` - returns smallest item from iterable +/// - `min(arg1, arg2, ...)` - returns smallest of the arguments +pub fn builtin_min(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let MinArgs { args, key, default } = MinArgs::from_args(args, vm)?; + run_min_max(vm, args, key, default, true) +} + +/// Implementation of the max() builtin function. +/// +/// Returns the largest item in an iterable or the largest of two or more arguments. +/// Supports two forms: +/// - `max(iterable)` - returns largest item from iterable +/// - `max(arg1, arg2, ...)` - returns largest of the arguments +pub fn builtin_max(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let MaxArgs { args, key, default } = MaxArgs::from_args(args, vm)?; + run_min_max(vm, args, key, default, false) +} + +/// Shared implementation for min() and max() after argument extraction. +/// +/// When `is_min` is true, returns the minimum; otherwise returns the maximum. +fn run_min_max( + vm: &mut VM<'_>, + args: Vec, + key: Value, + default: Option, + is_min: bool, +) -> RunResult { + let func_name = if is_min { "min" } else { "max" }; + + // Normalise `key=None` to "no key function" so the comparison path can + // skip the call entirely. + let key_fn = match key { + Value::None => { + key.drop_with(vm); + None + } + _ => Some(key), + }; + defer_drop!(key_fn, vm); + + defer_drop_mut!(default, vm); + defer_drop_mut!(args, vm); + + if args.is_empty() { + return Err(SimpleException::new_msg( + ExcType::TypeError, + format!("{func_name} expected at least 1 argument, got 0"), + ) + .into()); + } + + let first_arg = args.remove(0); + + if args.is_empty() { + // Single argument: iterate over it + let iter = first_arg.into_py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iter, vm); + let mut iter = iter.read(vm); + + let Some(result) = iter.py_next(vm)? else { + if let Some(default) = default.take() { + return Ok(default); + } + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("{func_name}() iterable argument is empty"), + ) + .into()); + }; + + if let Some(key_fn) = key_fn { + let mut result_guard = DropGuard::new(result, vm); + { + let (result, vm) = result_guard.as_parts_mut(); + let result_key = evaluate_key(result.clone_with_heap(vm), key_fn, vm)?; + defer_drop_mut!(result_key, vm); + + while let Some(item) = iter.py_next(vm)? { + defer_drop_mut!(item, vm); + let item_key = evaluate_key(item.clone_with_heap(vm), key_fn, vm)?; + defer_drop_mut!(item_key, vm); + + if candidate_wins(result_key, item_key, is_min, vm)? { + mem::swap(result, item); + mem::swap(result_key, item_key); + } + } + } + Ok(result_guard.into_inner()) + } else { + let mut result_guard = DropGuard::new(result, vm); + let (result, vm) = result_guard.as_parts_mut(); + + while let Some(item) = iter.py_next(vm)? { + defer_drop_mut!(item, vm); + + if candidate_wins(result, item, is_min, vm)? { + mem::swap(result, item); + } + } + + Ok(result_guard.into_inner()) + } + } else { + // Multiple arguments: compare them directly + if default.is_some() { + first_arg.drop_with(vm); + // The deferred drops release `default` and remaining arguments. + return Err(default_with_multiple_args(func_name)); + } + + if let Some(key_fn) = key_fn { + let mut result_guard = DropGuard::new(first_arg, vm); + { + let (result, vm) = result_guard.as_parts_mut(); + let result_key = evaluate_key(result.clone_with_heap(vm), key_fn, vm)?; + defer_drop_mut!(result_key, vm); + + for item in args.drain(..) { + defer_drop_mut!(item, vm); + let item_key = evaluate_key(item.clone_with_heap(vm), key_fn, vm)?; + defer_drop_mut!(item_key, vm); + + if candidate_wins(result_key, item_key, is_min, vm)? { + mem::swap(result, item); + mem::swap(result_key, item_key); + } + } + } + Ok(result_guard.into_inner()) + } else { + let mut result_guard = DropGuard::new(first_arg, vm); + let (result, vm) = result_guard.as_parts_mut(); + + for item in args.drain(..) { + defer_drop_mut!(item, vm); + + if candidate_wins(result, item, is_min, vm)? { + mem::swap(result, item); + } + } + + Ok(result_guard.into_inner()) + } + } +} + +/// Argument shape for `min(*args, key=None, default=...)`. +/// +/// `key` is held as `Value` so `key=None` can be normalised to "no key +/// function". `default` is `Option` (with `default` attr) so the +/// implementation can distinguish "not provided" from "provided with any +/// value" — that distinction matters because `default=` is only valid with a +/// single iterable argument. +#[derive(FromArgs)] +#[from_args(name = "min")] +struct MinArgs { + #[from_args(varargs)] + args: Vec, + #[from_args(default = Value::None)] + key: Value, + #[from_args(default)] + default: Option, +} + +/// Argument shape for `max(*args, key=None, default=...)`. +/// +/// See [`MinArgs`] for field semantics; the only difference is the function +/// name used in error messages. +#[derive(FromArgs)] +#[from_args(name = "max")] +struct MaxArgs { + #[from_args(varargs)] + args: Vec, + #[from_args(default = Value::None)] + key: Value, + #[from_args(default)] + default: Option, +} + +/// Calls the user-provided key function for a single candidate value. +/// +/// The caller passes an owned clone of the candidate so this helper can forward it +/// into the function call without changing ownership of the original item being +/// tracked as the eventual min/max result. +fn evaluate_key(item: Value, key_fn: &Value, vm: &mut VM<'_>) -> RunResult { + vm.evaluate_function(key_fn, ArgValues::One(item)) +} + +/// Returns whether `candidate` should replace `current` as the best value seen so far. +/// +/// `min()` replaces the current winner when the new candidate compares smaller, +/// while `max()` replaces it when the new candidate compares larger. Equal values +/// keep the existing winner so ties preserve the first-seen item, matching CPython. +pub(crate) fn candidate_wins(current: &Value, candidate: &Value, is_min: bool, vm: &mut VM<'_>) -> RunResult { + let ordering = match candidate.py_cmp(current, vm)? { + CmpOrder::Ordered(ordering) => ordering, + // A `NaN` candidate (or `NaN`-carrying container) is neither smaller nor + // larger, so it never displaces the incumbent — matching CPython, where + // `min`/`max` only swap on a strict `<`/`>` and `NaN` yields neither. + CmpOrder::Unordered => return Ok(false), + CmpOrder::Incomparable => return Err(ord_not_supported(candidate, current, is_min, vm)), + }; + + Ok((is_min && ordering == Ordering::Less) || (!is_min && ordering == Ordering::Greater)) +} + +/// Creates the CPython-compatible error for `default=` with multiple positional args. +#[cold] +fn default_with_multiple_args(func_name: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("Cannot specify a default for {func_name}() with multiple positional arguments"), + ) + .into() +} + +#[cold] +fn ord_not_supported(left: &Value, right: &Value, is_min: bool, vm: &VM<'_>) -> RunError { + let left_type = left.py_type_name(vm); + let right_type = right.py_type_name(vm); + let operator = if is_min { "<" } else { ">" }; + ExcType::type_error_ordering(operator, &left_type, &right_type) +} diff --git a/crates/bashkit-monty/src/builtins/mod.rs b/crates/bashkit-monty/src/builtins/mod.rs new file mode 100644 index 000000000..45f582234 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/mod.rs @@ -0,0 +1,186 @@ +//! Python builtin functions, types, and exception constructors. +//! +//! This module provides the interpreter-native implementation of Python builtins. +//! Each builtin function has its own submodule for organization. + +mod abs; +mod all; +mod any; +mod bin; +mod chr; +mod divmod; +mod enumerate; +mod eval_exec; +mod filter; +mod format; +mod getattr; +mod hasattr; +mod hash; +mod hex; +mod id; +pub(crate) mod isinstance; +pub(crate) mod iter; +mod len; +mod locals; +mod map; +mod min_max; // min and max share implementation +pub(crate) use min_max::candidate_wins; +pub(crate) mod next; +pub(crate) mod object_setattr; +mod oct; +pub(crate) mod open; +mod ord; +mod pow; +mod print; +mod repr; +mod reversed; +mod round; +mod setattr; +mod sorted; +mod sum; +mod type_; +mod zip; + +use std::{fmt, fmt::Write, str::FromStr}; + +use crate::{ + args::ArgValues, + bytecode::{CallResult, VM}, + exception_private::{ExcType, ExcTypeExt, RunResult}, + modules::csv, + types::Type, + value::Value, +}; + +/// Enumerates every interpreter-native Python builtins +/// +/// Uses strum derives for automatic `Display`, `FromStr`, and `AsRef` implementations. +/// All variants serialize to lowercase (e.g., `Print` -> "print"). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) enum Builtins { + /// A builtin function like `print`, `len`, `type`, etc. + Function(BuiltinsFunctions), + /// An exception type constructor like `ValueError`, `TypeError`, etc. + ExcType(ExcType), + /// A type constructor like `list`, `dict`, `int`, etc. + Type(Type), +} + +impl Builtins { + /// Resolves builtin names that evaluate directly to singleton values. + #[must_use] + pub fn value_from_name(name: &str) -> Option { + match name { + "Ellipsis" => Some(Value::Ellipsis), + "NotImplemented" => Some(Value::NotImplemented), + _ => name.parse::().ok().map(Value::Builtin), + } + } + + /// Calls this builtin, allowing builtins that need host involvement to yield. + /// + /// Most builtins produce a [`CallResult::Value`]. `iter()` and `next()` can + /// push frames for user methods; `open()` yields its host filesystem operation, + /// and `next()` on an unread file yields the read that loads its buffer. + pub fn call(self, vm: &mut VM<'_>, args: ArgValues) -> RunResult { + match self { + Self::Function(b) => b.call(vm, args), + Self::ExcType(exc) => exc.call(vm, args).map(CallResult::Value), + // `DictReader(f)` on an unread file yields the read that loads it. + Self::Type(Type::CsvDictReader) => csv::dict_reader_call(vm, args), + Self::Type(t) => t.call(vm, args), + } + } + + /// Writes the Python repr() string for this callable to a formatter. + pub fn py_repr_fmt(self, f: &mut W) -> fmt::Result { + match self { + Self::Function(b) => write!(f, ""), + Self::ExcType(e) => write!(f, ""), + Self::Type(t) => write!(f, ""), + } + } + + /// Returns the type of this builtin. + pub fn py_type(self) -> Type { + match self { + Self::Function(_) => Type::BuiltinFunction, + Self::ExcType(_) => Type::Type, + Self::Type(_) => Type::Type, + } + } +} + +impl FromStr for Builtins { + type Err = (); + + fn from_str(s: &str) -> Result { + // Priority: BuiltinsFunctions > ExcType > Type + // Only matches names that are true Python builtins (accessible without imports). + if let Ok(b) = BuiltinsFunctions::from_str(s) { + Ok(Self::Function(b)) + } else if let Ok(exc) = ExcType::from_str(s) { + Ok(Self::ExcType(exc)) + } else if let Some(t) = Type::from_builtin_name(s) { + Ok(Self::Type(t)) + } else { + Err(()) + } + } +} + +pub use monty_types::BuiltinsFunctions; +pub(crate) use type_::type_of_ref; + +pub(crate) trait BuiltinsFunctionsExt: Sized { + fn call(self, vm: &mut VM<'_>, args: ArgValues) -> RunResult; +} + +impl BuiltinsFunctionsExt for BuiltinsFunctions { + fn call(self, vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let r = match self { + Self::Abs => abs::builtin_abs(vm, args), + Self::All => all::builtin_all(vm, args), + Self::Any => any::builtin_any(vm, args), + Self::Bin => bin::builtin_bin(vm, args), + Self::Chr => chr::builtin_chr(vm, args), + Self::Divmod => divmod::builtin_divmod(vm, args), + Self::Enumerate => enumerate::builtin_enumerate(vm, args), + Self::Filter => filter::builtin_filter(vm, args), + Self::Format => format::builtin_format(vm, args), + // `getattr()` / `hasattr()` may suspend a lazy host attribute lookup. + Self::Getattr => return getattr::builtin_getattr(vm, args), + Self::Hasattr => return hasattr::builtin_hasattr(vm, args), + Self::Hash => hash::builtin_hash(vm, args), + Self::Hex => hex::builtin_hex(vm, args), + Self::Id => id::builtin_id(vm, args), + Self::Isinstance => isinstance::builtin_isinstance(vm, args), + Self::Len => len::builtin_len(vm, args), + Self::Map => map::builtin_map(vm, args), + Self::Max => min_max::builtin_max(vm, args), + Self::Min => min_max::builtin_min(vm, args), + // `next()` on an unread file yields the read that loads it. + Self::Next => return next::builtin_next(vm, args), + Self::Oct => oct::builtin_oct(vm, args), + // `open()` yields an OS call rather than a plain value. + Self::Open => return open::builtin_open(vm, args), + Self::Ord => ord::builtin_ord(vm, args), + Self::Pow => pow::builtin_pow(vm, args), + Self::Print => print::builtin_print(vm, args), + Self::Repr => repr::builtin_repr(vm, args), + Self::Reversed => reversed::builtin_reversed(vm, args), + Self::Round => round::builtin_round(vm, args), + Self::Setattr => setattr::builtin_setattr(vm, args), + Self::ObjectSetattr => object_setattr::builtin_object_setattr(vm, args), + Self::Sorted => sorted::builtin_sorted(vm, args), + Self::Sum => sum::builtin_sum(vm, args), + Self::Type => type_::builtin_type(vm, args), + Self::Zip => zip::builtin_zip(vm, args), + // `eval()` / `exec()` push the compiled snippet's frame. + Self::Eval => return eval_exec::builtin_eval(vm, args), + Self::Exec => return eval_exec::builtin_exec(vm, args), + Self::Locals => locals::builtin_locals(vm, args), + }; + r.map(CallResult::Value) + } +} diff --git a/crates/bashkit-monty/src/builtins/next.rs b/crates/bashkit-monty/src/builtins/next.rs new file mode 100644 index 000000000..ec294c0cd --- /dev/null +++ b/crates/bashkit-monty/src/builtins/next.rs @@ -0,0 +1,93 @@ +//! Implementation of the next() builtin function. + +use crate::{ + args::{ArgValues, FromArgs}, + builtins::{Builtins, BuiltinsFunctions}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + frozen::FrozenFunction, + heap::{DropGuard, HeapReadOutput}, + os_dispatch::PostConversionEffect, + types::PyTrait, + value::Value, +}; + +/// Catches exhaustion after a user `__next__` call, including one that suspends. +pub(crate) const NEXT_DEFAULT_SOURCE: &str = r" +def __monty_next_default(iterator, default, next_, stop_iteration): + try: + return next_(iterator) + except stop_iteration: + return default +"; + +/// Argument shape for `next(iterator, default=...)` — positional-only in +/// CPython, so `style = unpack` gives the `PyArg_UnpackTuple` arity wording +/// and the blanket `next() takes no keyword arguments` rejection. +#[derive(FromArgs)] +#[from_args(name = "next", style = unpack)] +struct NextArgs { + #[from_args(pos_only)] + iterator: Value, + #[from_args(pos_only, default)] + default: Option, +} + +/// Implementation of the next() builtin function. +/// +/// Retrieves the next item from an iterator. +/// +/// Two forms are supported: +/// - `next(iterator)` - Returns the next item from the iterator. Raises +/// `StopIteration` when the iterator is exhausted. +/// - `next(iterator, default)` - Returns the next item from the iterator, or +/// `default` if the iterator is exhausted. +/// +/// A file nobody has read yet first loads its buffer from the host: the call +/// yields the read with a `FileNext` effect, which answers it on resume. +pub fn builtin_next(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let NextArgs { iterator, default } = NextArgs::from_args(args, vm)?; + defer_drop!(iterator, vm); + match iterator.read_heap(vm) { + Some(HeapReadOutput::Instance(instance)) => { + if let Some(default) = default { + vm.call_frozen_exact( + FrozenFunction::NextDefault, + [ + iterator.clone_with_heap(vm.heap), + default, + Value::Builtin(Builtins::Function(BuiltinsFunctions::Next)), + Value::Builtin(Builtins::ExcType(ExcType::StopIteration)), + ], + ) + } else { + instance.call_next(vm) + } + } + Some(HeapReadOutput::OpenFile(file)) if file.needs_buffer_load(vm) => { + let effect = PostConversionEffect::FileNext { + file_id: file.id(), + default, + }; + Ok(file.buffer_load_call(vm, effect)) + } + _ => next_native(iterator, default, vm).map(CallResult::Value), + } +} + +/// Advances a native iterator without allocating a continuation for its optional default. +fn next_native(iterator: &Value, default: Option, vm: &mut VM<'_>) -> RunResult { + let mut default_guard = DropGuard::new(default, vm); + let vm = default_guard.ctx(); + let Value::Ref(id) = iterator else { + return Err(ExcType::type_error_not_iterator(&iterator.py_type_name(vm))); + }; + match vm.heap.read(*id).py_next(vm)? { + Some(item) => Ok(item), + None => match default_guard.into_inner() { + Some(default) => Ok(default), + None => Err(ExcType::stop_iteration()), + }, + } +} diff --git a/crates/bashkit-monty/src/builtins/object_setattr.rs b/crates/bashkit-monty/src/builtins/object_setattr.rs new file mode 100644 index 000000000..03ad23907 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/object_setattr.rs @@ -0,0 +1,73 @@ +//! Implementation of `object.__setattr__`, the hook-bypassing attribute write. + +use monty_types::ExcType; + +use crate::{ + args::ArgValues, + bytecode::VM, + defer_drop, + exception_private::{ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{DropWithContext, HeapReadOutput}, + types::py_trait::attribute_name_value, + value::{EitherStr, Value}, +}; + +/// `object.__setattr__(obj, name, value)` — writes an instance attribute +/// without consulting the class. +/// +/// The escape hatch a class that hooks attribute writes needs: its own +/// `__setattr__` has to store the value somehow, and going through `obj.x = v` +/// would call itself. Only instances of user-defined classes are accepted, as +/// CPython rejects anything whose `__setattr__` is not `object`'s. +/// +/// ```python +/// object.__setattr__(point, 'x', 1) +/// ``` +pub fn builtin_object_setattr(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + // CPython reaches this as a slot wrapper bound to `obj`, so its messages + // name the wrapper and count `obj` as the receiver rather than an argument. + let positional = args.into_pos_only("wrapper __setattr__", vm.heap)?; + defer_drop!(positional, vm); + + let (object, name, value) = match positional.as_slice() { + [object, name, value] => (object, name, value), + // With nothing to bind as the receiver, CPython fails in the descriptor + // rather than in the arity check. + [] => { + return Err(ExcType::type_error( + "descriptor '__setattr__' of 'object' object needs an argument".to_owned(), + )); + } + other => return Err(ExcType::type_error_arg_count("__setattr__", 2, other.len() - 1)), + }; + + let Some(name) = name.as_either_str(vm.heap) else { + return Err(SimpleException::new_msg( + ExcType::TypeError, + format!("attribute name must be string, not '{}'", name.py_type_name(vm)), + ) + .into()); + }; + + // Only an instance has a `__dict__` to write into. Everything else gets the + // error CPython's own `object.__setattr__` produces for a type whose + // instances have no attribute storage. + let Value::Ref(heap_id) = object else { + return Err(no_dict_error(object, &name, vm)); + }; + let HeapReadOutput::Instance(instance) = vm.heap.read(*heap_id) else { + return Err(no_dict_error(object, &name, vm)); + }; + + let name = attribute_name_value(&name, vm); + // The write path itself, bypassing whatever the class would have done. + let replaced = instance.set_attr_unchecked(name, value.clone_with_heap(vm), vm)?; + replaced.drop_with(vm); + Ok(Value::None) +} + +/// `object.__setattr__` applied to a value with no instance `__dict__`. +fn no_dict_error(object: &Value, name: &EitherStr, vm: &VM<'_>) -> RunError { + let type_name = object.py_type_name(vm); + ExcType::attribute_error_no_setattr(&type_name, name.as_str(vm.interns)) +} diff --git a/crates/bashkit-monty/src/builtins/oct.rs b/crates/bashkit-monty/src/builtins/oct.rs new file mode 100644 index 000000000..3c4bc4ccf --- /dev/null +++ b/crates/bashkit-monty/src/builtins/oct.rs @@ -0,0 +1,19 @@ +//! Implementation of the oct() builtin function. + +use crate::{ + args::ArgValues, bytecode::VM, defer_drop, exception_private::RunResult, py_value::PyValue, + types::str::allocate_string_no_interning, value::Value, +}; + +/// Converts an integer or `__index__` result to an octal string prefixed with `0o`. +pub fn builtin_oct(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("oct", vm.heap)?; + defer_drop!(value, vm); + let index = value.py_index(vm)?; + defer_drop!(index, vm); + + let PyValue::Int(integer) = index.py_value(vm) else { + unreachable!("py_index returned an integer"); + }; + Ok(allocate_string_no_interning(integer.radix_repr(8, vm), vm.heap)) +} diff --git a/crates/bashkit-monty/src/builtins/open.rs b/crates/bashkit-monty/src/builtins/open.rs new file mode 100644 index 000000000..efba030ae --- /dev/null +++ b/crates/bashkit-monty/src/builtins/open.rs @@ -0,0 +1,263 @@ +//! Implementation of the `open()` builtin. +//! +//! `open()` itself allocates no heap object. It validates its arguments and +//! yields an [`OsFunction::Open`] OS call; the host performs the open-time +//! effect (truncate / create / existence-check) and returns a +//! [`MontyNode::FileHandle`](monty_types::MontyNode::FileHandle), which the +//! resume path converts into the heap [`OpenFile`](crate::types::OpenFile) +//! wrapper and attaches the original filename and `newline` mode. `read()`/`write()` use the host's +//! returned path for full-file OS calls, so filesystem access remains behind `OsFunction`. + +use std::str; + +use monty_types::{MontyPath, OpenCallArgs, OsFunctionCall}; + +use crate::{ + args::{ArgValues, FromArgs, StrArg}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::HeapData, + os_dispatch::{PostConversionEffect, value_as_path_str}, + types::{ + PyTrait, Type, + file::{FileMode, FileName, extract_str_payload}, + }, + value::Value, +}; + +/// Opens a file for reading, writing, or appending. +/// +/// The host performs open-time validation and creation, then returns a file handle. +/// The resume effect preserves the supplied filename for `.name` and `repr()`; +/// subsequent I/O uses the handle's path, independent of later directory changes. +pub(crate) fn builtin_open(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let OpenArgs { + file, + mode, + buffering, + encoding, + errors, + newline, + closefd, + opener, + } = OpenArgs::from_args(args, vm)?; + + // `file` and the unsupported kwargs are raw `Value`s; `mode` holds a + // borrowed str — all need cleanup on every path. + defer_drop!(file, vm); + defer_drop!(mode, vm); + defer_drop!(buffering, vm); + defer_drop!(encoding, vm); + defer_drop!(errors, vm); + defer_drop!(newline, vm); + defer_drop!(closefd, vm); + defer_drop!(opener, vm); + + // Reject non-default values for ignored kwargs so caller code can't + // silently rely on (e.g.) `buffering=0` semantics Monty doesn't model. + validate_ignored_open_kwarg("buffering", buffering, vm)?; + validate_ignored_open_kwarg("encoding", encoding, vm)?; + validate_ignored_open_kwarg("errors", errors, vm)?; + let newline = newline_argument(newline, vm)?; + validate_ignored_open_kwarg("closefd", closefd, vm)?; + validate_ignored_open_kwarg("opener", opener, vm)?; + + let path = extract_path_string(file, vm)?.to_owned(); + // Parse here purely to reject malformed modes before the OS round-trip; + // the file wrapper itself is built from the host's returned FileHandle. + let file_mode = mode + .as_ref() + .map_or("r", |m| m.as_str(vm)) + .parse::() + .map_err(|e| RunError::from(SimpleException::new_msg(ExcType::ValueError, e)))?; + // CPython rejects this pairing before opening; the value itself it checks + // only after (see `apply_open_name`). + if file_mode.is_binary() && newline.is_some() { + return Err(ExcType::value_error("binary mode doesn't take a newline argument")); + } + + let name = if file.py_type(vm) == Type::Bytes { + FileName::Bytes(path.as_bytes().to_vec()) + } else { + FileName::Str(path.clone()) + }; + Ok(CallResult::OsCallWithEffect { + call: OsFunctionCall::Open(OpenCallArgs { + path: MontyPath::new(path), + mode: file_mode, + }), + effect: PostConversionEffect::OpenName { name, newline }.into(), + }) +} + +/// Argument shape for `open(file, mode='r', buffering=-1, encoding=None, +/// errors=None, newline=None, closefd=True, opener=None)`. +/// +/// `mode` is a zero-copy [`StrArg`] (absent → `"r"`) so wrong-type errors +/// flow through the macro's `bad_arg_named` path and match CPython's +/// `open() argument 'mode' must be str, not …` wording verbatim, without +/// copying the mode string. The other kwargs stay as raw `Value` +/// because they have monty-specific validation (`validate_ignored_open_kwarg`) +/// that the macro doesn't model — Monty rejects any *non-default* value to +/// avoid silently dropping semantics it doesn't honour (e.g. `buffering=0`, +/// `opener=my_opener`); `newline` is honoured and extracted by +/// `newline_argument`. `file` is also raw because `open()`'s file-path +/// error wording (`expected str, bytes or os.PathLike object, not …`) doesn't +/// follow the `_PyArg_BadArgument` shape that `bad_arg_named` emits. +#[derive(FromArgs)] +#[from_args(name = "open", bad_arg_named)] +struct OpenArgs { + file: Value, + #[from_args(default)] + mode: Option, + #[from_args(default = Value::Int(-1))] + buffering: Value, + #[from_args(default = Value::None)] + encoding: Value, + #[from_args(default = Value::None)] + errors: Value, + #[from_args(default = Value::None)] + newline: Value, + #[from_args(default = Value::Bool(true))] + closefd: Value, + #[from_args(default = Value::None)] + opener: Value, +} + +/// Extracts a path string accepted by `open()`. +/// +/// Accepts `str` (interned or heap), `bytes` (UTF-8 decoded), `PurePosixPath` +/// and `os.DirEntry`. The error message mentions `os.PathLike` to match +/// CPython, even though full PathLike support is limited to the variants +/// listed above. +fn extract_path_string<'a>(value: &Value, vm: &'a VM<'_>) -> RunResult<&'a str> { + let opt = match value { + Value::InternBytes(bytes_id) => decode_utf8_path(vm.interns.get_bytes(*bytes_id))?, + Value::Ref(id) if let HeapData::Bytes(b) = vm.heap.get(*id) => decode_utf8_path(b.as_slice())?, + _ => value_as_path_str(value, vm.heap, vm.interns), + }; + opt.ok_or_else(|| path_type_error(value, vm)) +} + +/// Decodes a byte path as strict UTF-8, raising `UnicodeDecodeError` on +/// invalid input. +/// +/// # Divergence from CPython +/// +/// CPython routes `bytes` paths through `os.fsdecode`, which on most hosts +/// uses UTF-8 with PEP 383 `surrogateescape` — invalid bytes become lone +/// surrogates `U+DC80`–`U+DCFF` so they round-trip back to the original +/// byte sequence. Monty rejects non-UTF-8 paths outright instead. +/// +/// The choice is deliberate, not a "not yet implemented" gap: +/// +/// 1. **Rust's `String` is strictly valid UTF-8.** Lone surrogates are not +/// Unicode scalar values, so they cannot live in a `String` without +/// `unsafe` code (or a parallel `Vec` path representation, which +/// would require refactoring `Path`, mount dispatch, and the host +/// boundary — see `crates/monty/src/types/path.rs`). +/// 2. **Monty paths are virtual POSIX strings**, not host-OS filenames. +/// The mount table maps them to real host paths only at the boundary; +/// there is no meaningful "filesystem encoding" to apply inside the +/// sandbox. +/// 3. **Hard rejection is predictable.** A lossy fallback (e.g. +/// `from_utf8_lossy`'s `U+FFFD` replacement) would not round-trip and +/// could silently re-route an `open()` call to a different file than +/// the caller asked for. +/// +/// See `limitations/open.md` for the user-facing description. +fn decode_utf8_path(bytes: &[u8]) -> RunResult> { + match str::from_utf8(bytes) { + Ok(s) => Ok(Some(s)), + Err(_) => Err(SimpleException::new_msg(ExcType::UnicodeDecodeError, "can't decode bytes path as UTF-8").into()), + } +} + +/// Extracts `newline` as the raw string CPython sees: `None` stays `None` and +/// a non-str raises the clinic `TypeError`. The value itself is validated +/// after the open, in `apply_open_name`, where CPython validates it. +fn newline_argument(value: &Value, vm: &VM<'_>) -> RunResult> { + if matches!(value, Value::None) { + Ok(None) + } else { + extract_str_payload(value, vm) + .map(Some) + .ok_or_else(|| kwarg_type_error("newline", value, vm)) + } +} + +/// Validates `open()` kwargs that Monty does not actually honor. +/// +/// Monty only models the `file`, `mode` and `newline` arguments. Any other argument set +/// to a non-default value would silently be ignored if accepted, hiding bugs +/// in user code that passes (for example) `buffering=0` expecting an +/// unbuffered file or `opener=my_opener` expecting a custom open hook. To +/// avoid that, the only accepted values are the CPython defaults plus, for +/// `encoding`, the literal `"utf-8"` — which is what Monty already uses. +/// +/// Non-default values raise `TypeError` ("'' argument is not yet +/// supported"). A wrong *type* (e.g. `encoding=123`) is reported as a +/// dedicated type error so it remains diagnosable. +fn validate_ignored_open_kwarg(name: &str, value: &Value, vm: &VM<'_>) -> Result<(), RunError> { + let is_default = match name { + // CPython default is -1 (sentinel for "interpreter picks the + // buffer size"). Monty has no buffering layer to tune. + "buffering" => matches!(value, Value::Int(-1)), + // None is the CPython default; "utf-8" is the encoding Monty + // already uses, so accept it as a documented no-op. + "encoding" => { + if matches!(value, Value::None) { + true + } else if value.is_str(vm.heap) { + let s = match value { + Value::InternString(id) => vm.interns.get_str(*id), + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Str(s) => s.as_str(), + _ => "", + }, + _ => "", + }; + s.eq_ignore_ascii_case("utf-8") || s.eq_ignore_ascii_case("utf8") + } else { + return Err(kwarg_type_error(name, value, vm)); + } + } + // `errors` accepts str or None in CPython; only the default (None) + // is honored by Monty. + "errors" => { + if matches!(value, Value::None) { + true + } else if value.is_str(vm.heap) { + false + } else { + return Err(kwarg_type_error(name, value, vm)); + } + } + // CPython default is True; False requires int-fd open semantics + // Monty does not model. + "closefd" => matches!(value, Value::Bool(true)), + // CPython default is None; a custom opener would run host-side code + // outside the sandbox boundary, which Monty does not support. + "opener" => matches!(value, Value::None), + _ => unreachable!("validated open keyword name"), + }; + if is_default { + Ok(()) + } else { + Err(ExcType::type_error(format!("'{name}' argument is not yet supported"))) + } +} + +/// Creates the path type error used by `open()`. +fn path_type_error(value: &Value, vm: &VM<'_>) -> RunError { + ExcType::type_error_fspath(&value.py_type_name(vm)) +} + +/// The argument-clinic `TypeError` for a str-or-None `open()` kwarg of the wrong type. +fn kwarg_type_error(name: &str, value: &Value, vm: &VM<'_>) -> RunError { + ExcType::type_error(format!( + "open() argument '{name}' must be str or None, not {}", + value.py_type(vm).cpython_arg_name(vm.heap, vm.interns) + )) +} diff --git a/crates/bashkit-monty/src/builtins/ord.rs b/crates/bashkit-monty/src/builtins/ord.rs new file mode 100644 index 000000000..6a49f3ad4 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/ord.rs @@ -0,0 +1,40 @@ +//! Implementation of the ord() builtin function. + +use crate::{ + args::ArgValues, + bytecode::VM, + defer_drop, + exception_private::{ExcType, RunResult, SimpleException}, + py_value::PyValue, + value::Value, +}; + +/// Implementation of the ord() builtin function. +/// +/// Returns the Unicode code point of a one-character string. +pub fn builtin_ord(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("ord", vm.heap)?; + defer_drop!(value, vm); + + if let PyValue::Str(string) = value.py_value(vm) { + let s = string.as_str(vm); + let mut chars = s.chars(); + if let (Some(c), None) = (chars.next(), chars.next()) { + Ok(Value::Int(c as i64)) + } else { + let len = s.chars().count(); + Err(SimpleException::new_msg( + ExcType::TypeError, + format!("ord() expected a character, but string of length {len} found"), + ) + .into()) + } + } else { + let type_name = value.py_type_name(vm); + Err(SimpleException::new_msg( + ExcType::TypeError, + format!("ord() expected string of length 1, but {type_name} found"), + ) + .into()) + } +} diff --git a/crates/bashkit-monty/src/builtins/pow.rs b/crates/bashkit-monty/src/builtins/pow.rs new file mode 100644 index 000000000..891294def --- /dev/null +++ b/crates/bashkit-monty/src/builtins/pow.rs @@ -0,0 +1,42 @@ +//! Implementation of the pow() builtin function. + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + defer_drop, + exception_private::RunResult, + value::Value, +}; + +/// Implementation of the pow() builtin function. +/// +/// Dispatches `__pow__` / `__rpow__`, passing an optional modulus unchanged. +/// Builtin numeric types accept a modulus only for integer operands. +pub fn builtin_pow(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let PowArgs { base, exp, modulus } = PowArgs::from_args(args, vm)?; + defer_drop!(base, vm); + defer_drop!(exp, vm); + defer_drop!(modulus, vm); + base.py_pow(exp, Some(modulus), vm) +} + +/// `pow(base, exp[, mod])` — CPython accepts all three as positional-or-keyword +/// (and `mod` defaults to `None`), but Monty has not plumbed kwarg dispatch +/// through to the dispatch body yet. `kwargs_not_supported_yet` rejects +/// any kwarg with `NotImplementedError: pow() does not yet support +/// keyword arguments` (replacing the previous `TypeError: pow() takes no +/// keyword arguments` from `into_pos_only`) while the macro takes over +/// positional arity validation — the bespoke +/// `pow expected 2 or 3 arguments, got N` message becomes CPython's +/// `pow() takes at most 3 arguments (N given)` / +/// `pow() missing required argument 'X' (pos N)`. The `modulus` field +/// will be renamed to `r#mod` and lose the flag when kwargs are +/// implemented. +#[derive(FromArgs)] +#[from_args(name = "pow", style = c_named, at_most_total, kwargs_not_supported_yet)] +struct PowArgs { + base: Value, + exp: Value, + #[from_args(default = Value::None)] + modulus: Value, +} diff --git a/crates/bashkit-monty/src/builtins/print.rs b/crates/bashkit-monty/src/builtins/print.rs new file mode 100644 index 000000000..777b9fa97 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/print.rs @@ -0,0 +1,127 @@ +//! Implementation of the print() builtin function. + +use monty_types::PrintStream; + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + defer_drop, + exception_private::{ExcType, RunResult, SimpleException}, + intern::StaticStrings, + py_value::PyValue, + types::PyTrait, + value::{Marker, Value}, +}; + +/// Implementation of the print() builtin function. +/// +/// Supports the following keyword arguments: +/// - `sep`: separator between values (default: " ") +/// - `end`: string appended after the last value (default: "\n") +/// - `file`: `sys.stdout` (the default) or `sys.stderr`; anything else raises +/// `TypeError`, since Monty has no file objects to write into +/// - `flush`: whether to flush the stream (accepted but ignored — Monty +/// doesn't buffer stdout) +pub fn builtin_print(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let PrintArgs { + objects, + sep, + end, + file, + flush: _, + } = PrintArgs::from_args(args, vm)?; + defer_drop!(objects, vm); + defer_drop!(sep, vm); + defer_drop!(end, vm); + defer_drop!(file, vm); + + // `sep` and `end` are checked before `file` because CPython reports them in + // that order: `print(x, sep=1, file=3)` raises about `sep`, not the file. + let sep_str = extract_string_kwarg(sep, "sep", vm)?; + let end_str = extract_string_kwarg(end, "end", vm)?; + let stream = print_stream(file, vm)?; + + let mut first = true; + for value in objects.as_slice() { + if first { + first = false; + } else if let Some(sep) = &sep_str { + vm.print_writer.write(stream, sep.as_str().into())?; + } else { + vm.print_writer.push(stream, ' ')?; + } + let s = value.py_str(vm)?; + defer_drop!(s, vm); + // Resolve the `str` `Value` against the heap/interns tables directly so + // the `&str` borrow stays disjoint from the `&mut vm.print_writer` write. + vm.print_writer + .write(stream, s.to_str_heap(vm.heap, vm.interns)?.into())?; + } + + if let Some(end) = end_str { + vm.print_writer.write(stream, end.into())?; + } else { + vm.print_writer.push(stream, '\n')?; + } + + Ok(Value::None) +} + +/// Resolves the `file` kwarg to the stream `print()` should write to. +/// +/// `sys.stdout` and `sys.stderr` are opaque markers rather than file objects +/// (see `limitations/sys.md`), so they are matched by identity. Any other +/// value, including a class defining `write()`, has nothing to write into. +fn print_stream(file: &Value, vm: &VM<'_>) -> RunResult { + match file { + Value::None | Value::Marker(Marker(StaticStrings::Stdout)) => Ok(PrintStream::Stdout), + Value::Marker(Marker(StaticStrings::Stderr)) => Ok(PrintStream::Stderr), + _ => Err(SimpleException::new_msg( + ExcType::TypeError, + format!( + "print() 'file' argument must be sys.stdout or sys.stderr, not {}", + file.py_type_name(vm) + ), + ) + .into()), + } +} + +/// Argument shape for `print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)`. +/// +/// Every kwarg is held as a raw `Value` so the caller can do the +/// "must be None or str" coercion inline, and so `flush` can be accepted +/// without forcing a type check. `file` is resolved by `print_stream`. +#[derive(FromArgs)] +#[from_args(name = "print")] +struct PrintArgs { + #[from_args(varargs)] + objects: Vec, + #[from_args(default = Value::None)] + sep: Value, + #[from_args(default = Value::None)] + end: Value, + #[from_args(default = Value::None)] + file: Value, + /// Accepted from Python for CPython compatibility but never consumed: + /// Monty doesn't buffer stdout, so there is nothing to flush. + #[expect(dead_code, reason = "accepted but ignored — Monty doesn't buffer stdout")] + #[from_args(default = Value::None)] + flush: Value, +} + +/// Extracts a string value from a print() kwarg. +/// +/// The kwarg can be None (returns None) or a string (returns Some). +/// Raises TypeError for other types. +fn extract_string_kwarg(value: &Value, name: &str, vm: &VM<'_>) -> RunResult> { + match value.py_value(vm) { + PyValue::None => Ok(None), + PyValue::Str(string) => Ok(Some(string.as_str(vm).to_owned())), + _ => Err(SimpleException::new_msg( + ExcType::TypeError, + format!("{} must be None or a string, not {}", name, value.py_type_name(vm)), + ) + .into()), + } +} diff --git a/crates/bashkit-monty/src/builtins/repr.rs b/crates/bashkit-monty/src/builtins/repr.rs new file mode 100644 index 000000000..25fdb6fe5 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/repr.rs @@ -0,0 +1,14 @@ +//! Implementation of the repr() builtin function. + +use crate::{args::ArgValues, bytecode::VM, defer_drop, exception_private::RunResult, types::PyTrait, value::Value}; + +/// Implementation of the repr() builtin function. +/// +/// Returns a string containing a printable representation of an object. +/// `py_repr` already yields a heap `str` `Value`, so it is returned as-is +/// without an intermediate `String` round-trip. +pub fn builtin_repr(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("repr", vm.heap)?; + defer_drop!(value, vm); + value.py_repr(vm) +} diff --git a/crates/bashkit-monty/src/builtins/reversed.rs b/crates/bashkit-monty/src/builtins/reversed.rs new file mode 100644 index 000000000..624e2f001 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/reversed.rs @@ -0,0 +1,75 @@ +//! Implementation of the reversed() builtin function. + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::HeapData, + types::{List, iter::collect_owned_iterable}, + value::Value, +}; + +/// Argument shape for `reversed(sequence, /)` — positional-only, so +/// `style = unpack` gives CPython's exact-arity wording +/// (`reversed expected 1 argument, got 2`) and the blanket +/// `reversed() takes no keyword arguments` rejection. +#[derive(FromArgs)] +#[from_args(name = "reversed", style = unpack)] +struct ReversedArgs { + #[from_args(pos_only)] + sequence: Value, +} + +/// Implementation of the reversed() builtin function. +/// +/// Returns a list with elements in reverse order. +/// Note: In Python this returns an iterator, but we return a list for simplicity. +pub fn builtin_reversed(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReversedArgs { sequence } = ReversedArgs::from_args(args, vm)?; + + // Being iterable is not enough: CPython needs `__reversed__`, or + // `__len__` + `__getitem__`. Check before iterating so unordered and + // one-shot iterables are rejected rather than silently reversed. + if !is_reversible(&sequence, vm) { + let err = ExcType::type_error_not_reversible(&sequence.py_type_name(vm)); + sequence.drop_with(vm); + return Err(err); + } + + // Collect all items + let mut items: Vec<_> = collect_owned_iterable(sequence, vm)?; + + // Reverse in place + items.reverse(); + + let heap_id = vm.heap.allocate(HeapData::List(List::new(items))); + Ok(Value::Ref(heap_id)) +} + +/// Whether `reversed()` accepts this value, mirroring CPython's requirement of +/// `__reversed__` or `__len__` + `__getitem__`. +/// +/// Deliberately a positive allowlist: a newly iterable type must opt in here +/// rather than becoming reversible by accident. Sets and iterators are excluded +/// (no ordering / one-shot), as are user instances — `__reversed__` is not +/// dispatched, see `limitations/classes.md`. +fn is_reversible(value: &Value, vm: &VM<'_>) -> bool { + match value { + Value::InternString(_) | Value::InternBytes(_) => true, + Value::Ref(id) => matches!( + vm.heap.get(*id), + HeapData::List(_) + | HeapData::Tuple(_) + | HeapData::NamedTuple(_) + | HeapData::Deque(_) + | HeapData::Str(_) + | HeapData::Bytes(_) + | HeapData::Range(_) + | HeapData::Dict(_) + | HeapData::DictKeysView(_) + | HeapData::DictItemsView(_) + | HeapData::DictValuesView(_) + ), + _ => false, + } +} diff --git a/crates/bashkit-monty/src/builtins/round.rs b/crates/bashkit-monty/src/builtins/round.rs new file mode 100644 index 000000000..71dba95fe --- /dev/null +++ b/crates/bashkit-monty/src/builtins/round.rs @@ -0,0 +1,34 @@ +//! Implementation of the round() builtin function. + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + types::PyTrait, + value::Value, +}; + +/// CPython's keyword-capable `round(number, ndigits=None)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "round", style = c_named, at_most_total)] +struct RoundArgs { + number: Value, + #[from_args(default = Value::None)] + ndigits: Value, +} + +/// Rounds through `__round__`, leaving precision coercion to the receiving type. +pub fn builtin_round(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let RoundArgs { number, ndigits } = RoundArgs::from_args(args, vm)?; + defer_drop!(number, vm); + defer_drop!(ndigits, vm); + let ndigits = if matches!(ndigits, Value::None) { + None + } else { + Some(ndigits) + }; + number + .py_round_impl(ndigits, vm)? + .ok_or_else(|| ExcType::type_error_missing_numeric_dunder(&number.py_type_name(vm), "__round__")) +} diff --git a/crates/bashkit-monty/src/builtins/setattr.rs b/crates/bashkit-monty/src/builtins/setattr.rs new file mode 100644 index 000000000..1d16785f1 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/setattr.rs @@ -0,0 +1,44 @@ +//! Implementation of the setattr() builtin function. + +use monty_types::ExcType; + +use crate::{ + args::ArgValues, + bytecode::VM, + defer_drop, + exception_private::{ExcTypeExt, RunResult, SimpleException}, + value::Value, +}; + +/// Implementation of the setattr() builtin function. +/// +/// Sets the named attribute on the given object to the specified value +/// This is the counterpart to getattr(). Returns None on success +/// +/// Examples: +/// ```python +/// setattr(obj, 'x', 42) # Set obj.x = 42 +/// setattr(obj, 'name', 'foo') # Set obj.name = 'foo' +/// ``` +pub fn builtin_setattr(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let positional = args.into_pos_only("setattr", vm.heap)?; + defer_drop!(positional, vm); + + let (object, name, value) = match positional.as_slice() { + [object, name, value] => (object, name, value), + other => return Err(ExcType::type_error_arg_count("setattr", 3, other.len())), + }; + + let Some(name) = name.as_either_str(vm.heap).map(|s| s.resolve_interned(vm.interns)) else { + return Err(SimpleException::new_msg( + ExcType::TypeError, + format!("attribute name must be string, not '{}'", name.py_type_name(vm)), + ) + .into()); + }; + + // note: py_set_attr takes ownership of the inc-ref'd value and drops it on error + object.py_set_attr(&name, value.clone_with_heap(vm), vm)?; + + Ok(Value::None) +} diff --git a/crates/bashkit-monty/src/builtins/sorted.rs b/crates/bashkit-monty/src/builtins/sorted.rs new file mode 100644 index 000000000..261f3e970 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/sorted.rs @@ -0,0 +1,47 @@ +//! Implementation of the sorted() builtin function. + +use crate::{ + args::ArgValues, + bytecode::VM, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{DropGuard, DropWithContext, HeapData}, + sorting::parse_and_sort, + types::{List, iter::collect_owned_iterable}, + value::Value, +}; + +/// Implementation of the sorted() builtin function. +/// +/// Returns a new sorted list from the items in an iterable. CPython's +/// `sorted(iterable, /, *, key=None, reverse=False)` is implemented by +/// converting the iterable to a list and delegating to `list.sort`, so +/// the kwargs and any kwarg-related errors are owned by `sort`. We mirror +/// that by extracting the iterable positionally and handing the rest off +/// to [`parse_and_sort`] — the same entry point `list.sort` uses — so +/// unknown-kwarg errors uniformly read `sort() got an unexpected keyword +/// argument 'X'` without any wording overrides. +pub fn builtin_sorted(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (mut pos_iter, kwargs) = args.into_parts(); + let pos_count = pos_iter.len(); + if pos_count != 1 { + pos_iter.drop_with(vm); + kwargs.drop_with(vm); + return Err(ExcType::type_error_expected_exact("sorted", 1, pos_count)); + } + let iterable = pos_iter.next().expect("checked pos_count == 1"); + + let items: Vec<_> = collect_owned_iterable(iterable, vm)?; + let mut items_guard = DropGuard::new(items, vm); + let (items, vm) = items_guard.as_parts_mut(); + + let sort_args = if kwargs.is_empty() { + ArgValues::Empty + } else { + ArgValues::Kwargs(kwargs) + }; + parse_and_sort(items, sort_args, vm)?; + + let (items, vm) = items_guard.into_parts(); + let heap_id = vm.heap.allocate(HeapData::List(List::new(items))); + Ok(Value::Ref(heap_id)) +} diff --git a/crates/bashkit-monty/src/builtins/sum.rs b/crates/bashkit-monty/src/builtins/sum.rs new file mode 100644 index 000000000..f22029b08 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/sum.rs @@ -0,0 +1,65 @@ +//! Implementation of the sum() builtin function. + +use std::mem; + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::DropGuard, + types::{PyTrait, Type}, + value::Value, +}; + +/// Argument shape for `sum(iterable, /, start=0)` — Argument Clinic in +/// CPython, so `start` is keyword-capable while `iterable` is positional-only. +/// `at_most_total` reproduces `_PyArg_UnpackKeywords`' total pre-count +/// (`sum() takes at most 2 arguments (3 given)`). +#[derive(FromArgs)] +#[from_args(name = "sum", at_most_total)] +struct SumArgs { + #[from_args(pos_only)] + iterable: Value, + #[from_args(default = Value::Int(0))] + start: Value, +} + +/// Implementation of the sum() builtin function. +/// +/// Sums the items of an iterable from left to right with an optional start value. +/// The default start value is 0. Str and bytes start values are explicitly +/// rejected, pointing at `''.join(seq)` / `b''.join(seq)` instead. +pub fn builtin_sum(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let SumArgs { iterable, start } = SumArgs::from_args(args, vm)?; + defer_drop_mut!(start, vm); + + let iter = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iter, vm); + let mut iter = iter.read(vm); + + // Reject str/bytes start values - Python explicitly forbids these + match start.py_type(vm) { + Type::Str => return Err(ExcType::type_error_sum_start("strings", "''")), + Type::Bytes => return Err(ExcType::type_error_sum_start("bytes", "b''")), + _ => {} + } + // Take the start value out of its guard (dropping `None` is a no-op). + let accumulator = mem::replace(start, Value::None); + + // DropGuard for accumulator: on success we extract it via into_inner(), + // on any error path it's dropped automatically + let mut acc_guard = DropGuard::new(accumulator, vm); + let (accumulator, vm) = acc_guard.as_parts_mut(); + + // Sum all items + while let Some(item) = iter.py_next(vm)? { + defer_drop!(item, vm); + + let new_value = accumulator.py_add(item, vm)?; + let old = mem::replace(accumulator, new_value); + old.drop_with(vm); + } + + Ok(acc_guard.into_inner()) +} diff --git a/crates/bashkit-monty/src/builtins/type_.rs b/crates/bashkit-monty/src/builtins/type_.rs new file mode 100644 index 000000000..4bd4c940b --- /dev/null +++ b/crates/bashkit-monty/src/builtins/type_.rs @@ -0,0 +1,184 @@ +//! Implementation of the type() builtin function. + +use super::Builtins; +use crate::{ + args::{ArgValues, KwargsValues}, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{DropWithContext, HeapData}, + intern::StaticStrings, + types::{Class, Dict, PyTrait}, + value::Value, +}; + +/// Implementation of the type() builtin function. +/// +/// The 1-arg form returns the type of an object; the 3-arg form +/// `type(name, bases, dict)` dynamically creates a new class, mirroring +/// CPython (except that `bases` must be empty — Monty classes cannot +/// inherit). Any other positional count is a `TypeError`. +/// +/// This hand-rolls `args.into_parts()` rather than using `#[derive(FromArgs)]` +/// because the "exactly 1 *or* 3 positionals, same name" overload isn't +/// expressible by any of the binder families — CPython special-cases `type`'s +/// argument parsing in `type_new`/`type_init` for the same reason. +pub fn builtin_type(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (mut pos, kwargs) = args.into_parts(); + match pos.len() { + 1 => { + let value = pos.next().expect("length checked"); + if kwargs.is_empty() { + Ok(type_of(vm, value)) + } else { + value.drop_with(vm); + kwargs.drop_with(vm); + Err(ExcType::type_error_no_kwargs("type")) + } + } + 3 => { + let name = pos.next().expect("length checked"); + let bases = pos.next().expect("length checked"); + let namespace = pos.next().expect("length checked"); + create_class(vm, name, bases, namespace, kwargs) + } + _ => { + pos.drop_with(vm); + kwargs.drop_with(vm); + Err(ExcType::type_error("type() takes 1 or 3 arguments")) + } + } +} + +/// The 1-arg `type(obj)` form. +fn type_of(vm: &mut VM<'_>, value: Value) -> Value { + defer_drop!(value, vm); + type_of_ref(vm, value) +} + +/// The type of a borrowed value. +/// +/// For an instance of a user-defined class the type *is* the class object +/// itself, so `type(x) is Foo` holds via reference identity; a host class +/// instance returns the `HostClassType` entry it owns (one per host class, so +/// identity holds there too); everything else returns the builtin `Type` +/// marker. Borrowing rather than consuming so callers that only need the type +/// of a value they still own (e.g. `functools.lru_cache(typed=True)` keying) +/// don't have to clone it first. +pub(crate) fn type_of_ref(vm: &mut VM<'_>, value: &Value) -> Value { + if let Value::Ref(id) = value + && let HeapData::Instance(inst) = vm.heap.get(*id) + { + let class_id = inst.class(); + vm.heap.inc_ref(class_id); + Value::Ref(class_id) + } else if let Value::Ref(id) = value + && let HeapData::NamedTuple(nt) = vm.heap.get(*id) + && let Some(class_id) = nt.class_id() + { + // A factory-made namedtuple's type is its class object, so + // `type(p) is Point` holds by identity (self-describing internal named + // tuples like `sys.version_info` have no class and fall through). + vm.heap.inc_ref(class_id); + Value::Ref(class_id) + } else if let Value::Ref(id) = value + && let HeapData::HostClass(hc) = vm.heap.get(*id) + { + let class_id = hc.class_id(); + vm.heap.inc_ref(class_id); + Value::Ref(class_id) + } else { + Value::Builtin(Builtins::Type(value.py_type(vm))) + } +} + +/// The 3-arg `type(name, bases, dict)` form: dynamically creates a class. +/// +/// Follows CPython's validation order (name, then bases, then dict, then +/// keyword rejection) and message wording (`type.__new__() argument N must +/// be ...`), except that non-string namespace keys raise a `TypeError` +/// where CPython merely warns. The namespace dict is *copied* into the +/// class — later mutation of the source dict must not affect the class — +/// and a `__doc__ = None` entry is synthesized when the dict omits it, +/// matching CPython's `type` descriptor default (compiled `class` bodies +/// get their `__doc__` from the parser instead). +fn create_class( + vm: &mut VM<'_>, + name: Value, + bases: Value, + namespace: Value, + kwargs: KwargsValues, +) -> RunResult { + defer_drop!(name, vm); + defer_drop!(bases, vm); + defer_drop!(namespace, vm); + defer_drop!(kwargs, vm); + + let Some(class_name) = name.as_either_str(vm.heap) else { + let got = name.py_type(vm).cpython_arg_name(vm.heap, vm.interns); + return Err(ExcType::type_error_bad_arg_pos("type.__new__", 1, "str", got)); + }; + + match bases { + Value::Ref(id) if let HeapData::Tuple(t) = vm.heap.get(*id) => { + // Monty divergence: classes cannot inherit, so even `(object,)` is + // rejected — the parse-time equivalent (`class Foo(Bar)`) is a + // syntax error, and this is its runtime counterpart. + if !t.as_slice().is_empty() { + return Err(ExcType::type_error("type() bases are not supported")); + } + } + _ => { + let got = bases.py_type(vm).cpython_arg_name(vm.heap, vm.interns); + return Err(ExcType::type_error_bad_arg_pos("type.__new__", 2, "tuple", got)); + } + } + + let Value::Ref(ns_id) = namespace else { + let got = namespace.py_type(vm).cpython_arg_name(vm.heap, vm.interns); + return Err(ExcType::type_error_bad_arg_pos("type.__new__", 3, "dict", got)); + }; + let HeapData::Dict(source) = vm.heap.get(*ns_id) else { + let got = namespace.py_type(vm).cpython_arg_name(vm.heap, vm.interns); + return Err(ExcType::type_error_bad_arg_pos("type.__new__", 3, "dict", got)); + }; + + if !kwargs.is_empty() { + // CPython forwards extra keywords to `__init_subclass__`, which + // `object` rejects with this message — synthesize the equivalent. + let name_str = class_name.as_str(vm.interns); + return Err(ExcType::type_error_no_kwargs(&format!("{name_str}.__init_subclass__"))); + } + + // Monty divergence: CPython only emits a `RuntimeWarning` for non-string + // namespace keys; Monty has no warnings machinery, so silently accepting + // them would hide the mistake — raise instead. Validated before cloning + // any pairs so the error path has nothing to clean up. + if let Some((bad_key, _)) = source.iter().find(|(k, _)| !k.is_str(vm.heap)) { + let name_str = class_name.as_str(vm.interns); + let key_type = bad_key.py_type_heap(vm.heap).name(vm.heap, vm.interns); + return Err(ExcType::type_error(format!( + "non-string key ({key_type}) in the namespace of class '{name_str}'" + ))); + } + + // Copy the namespace (CPython semantics: the class owns an independent + // dict). `clone_with_heap` takes `&Heap`, so the pairs can be cloned + // while `source` still borrows the heap immutably. + let mut pairs: Vec<(Value, Value)> = source + .iter() + .map(|(k, v)| (k.clone_with_heap(vm.heap), v.clone_with_heap(vm.heap))) + .collect(); + if source.get_by_str("__doc__", vm.heap, vm.interns).is_none() { + pairs.push(( + Value::InternString(vm.interns.intern_static(StaticStrings::DunderDoc)), + Value::None, + )); + } + let namespace_dict = Dict::from_pairs(pairs, vm)?; + + let class_id = vm + .heap + .allocate(HeapData::Class(Box::new(Class::new(class_name, namespace_dict)))); + Ok(Value::Ref(class_id)) +} diff --git a/crates/bashkit-monty/src/builtins/zip.rs b/crates/bashkit-monty/src/builtins/zip.rs new file mode 100644 index 000000000..560cf09e1 --- /dev/null +++ b/crates/bashkit-monty/src/builtins/zip.rs @@ -0,0 +1,118 @@ +//! Implementation of the zip() builtin function. + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{ExcType, RunError, RunResult, SimpleException}, + heap::{DropGuard, HeapData}, + types::{List, PyTrait, allocate_tuple, tuple::TupleVec}, + value::Value, +}; + +/// Implementation of the zip() builtin function. +/// +/// Returns a list of tuples, where the i-th tuple contains the i-th element +/// from each of the argument iterables. Stops when the shortest iterable is exhausted. +/// When `strict=True`, raises `ValueError` if any iterable has a different length. +/// Note: In Python this returns an iterator, but we return a list for simplicity. +pub fn builtin_zip(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ZipArgs { iterables, strict } = ZipArgs::from_args(args, vm)?; + defer_drop_mut!(iterables, vm); + // CPython's `strict` is truthy-checked (not strict typed), so test the raw + // value rather than asking the macro to coerce to a strict `bool`. + defer_drop!(strict, vm); + let strict = strict.py_bool(vm)?; + + if iterables.is_empty() { + // zip() with no arguments returns empty list + let heap_id = vm.heap.allocate(HeapData::List(List::new(Vec::new()))); + return Ok(Value::Ref(heap_id)); + } + + // Create iterators for each iterable + let iterators: Vec = Vec::with_capacity(iterables.len()); + defer_drop_mut!(iterators, vm); + for iterable in iterables.drain(..) { + iterators.push(iterable.into_py_iter(vm)?.require_synchronous(vm)?); + } + let mut iterators = iterators.iter().map(|iter| iter.read(vm)).collect::>(); + + let mut result_guard = DropGuard::new(Vec::new(), vm); + let (result, vm) = result_guard.as_parts_mut(); + + // Zip until shortest iterator is exhausted + 'outer: loop { + let mut items_guard = DropGuard::new(TupleVec::with_capacity(iterators.len()), vm); + let (tuple_items, vm) = items_guard.as_parts_mut(); + + for (i, iter) in iterators.iter_mut().enumerate() { + if let Some(item) = iter.py_next(vm)? { + tuple_items.push(item); + } else { + // This iterator is exhausted - stop zipping + + if strict { + // In strict mode, if i > 0 then argument i+1 ran out before + // the earlier ones, so it is "shorter." + if i > 0 { + return Err(strict_length_error(i + 1, i, "shorter")); + } + // i == 0: first iterator exhausted — verify every remaining + // iterator is also exhausted. If any still yields a value, + // that argument is "longer" than all preceding exhausted ones. + // j is the 0-based index; iterators 0..j are all exhausted, + // so j gives the count for the error message. + for (j, remaining) in iterators.iter_mut().enumerate().skip(1) { + if let Some(extra) = remaining.py_next(vm)? { + extra.drop_with(vm); + return Err(strict_length_error(j + 1, j, "longer")); + } + } + } + + break 'outer; + } + } + + // Create tuple from collected items + let (tuple_items, vm) = items_guard.into_parts(); + let tuple_val = allocate_tuple(tuple_items, vm.heap); + result.push(tuple_val); + } + + let (result, vm) = result_guard.into_parts(); + let heap_id = vm.heap.allocate(HeapData::List(List::new(result))); + Ok(Value::Ref(heap_id)) +} + +/// Argument shape for `zip(*iterables, strict=False)`. +/// +/// `strict` is held as a `Value` because CPython evaluates it via truthiness +/// (`py_bool`), not strict-type equality, so accepting any value is correct. +#[derive(FromArgs)] +#[from_args(name = "zip")] +struct ZipArgs { + #[from_args(varargs)] + iterables: Vec, + #[from_args(default = Value::Bool(false))] + strict: Value, +} + +/// Builds the `ValueError` for `zip(strict=True)` when iterables have different lengths. +/// +/// Matches CPython's error format: +/// - `"zip() argument 2 is shorter than argument 1"` (singular) +/// - `"zip() argument 4 is shorter than arguments 1-3"` (plural) +fn strict_length_error(exhausted_arg: usize, num_longer_args: usize, relation: &str) -> RunError { + let others = if num_longer_args == 1 { + "argument 1".to_owned() + } else { + format!("arguments 1-{num_longer_args}") + }; + SimpleException::new_msg( + ExcType::ValueError, + format!("zip() argument {exhausted_arg} is {relation} than {others}"), + ) + .into() +} diff --git a/crates/bashkit-monty/src/bytecode/builder.rs b/crates/bashkit-monty/src/bytecode/builder.rs new file mode 100644 index 000000000..c50473c7c --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/builder.rs @@ -0,0 +1,912 @@ +//! Builder for emitting bytecode during compilation. +//! +//! `CodeBuilder` provides methods for emitting opcodes and operands, handling +//! forward jumps with patching, and tracking source locations for tracebacks. + +use super::{ + code::{Code, ExceptionEntry, HandlerKind, LocationEntry}, + compiler::CompileError, + op::{Opcode, Operand}, +}; +use crate::{intern::StringId, parse::CodeRange, value::Value}; + +/// Builder for emitting bytecode during compilation. +/// +/// Handles encoding opcodes and operands into raw bytes, managing forward jumps +/// that need patching, and tracking source locations for traceback generation. +/// +/// The builder maintains an internal "dead code" state; during dead code emission +/// no bytes are written and no work is done. +#[derive(Debug, Default)] +pub struct CodeBuilder { + /// The bytecode being built. + bytecode: Vec, + + /// Constants collected during compilation. + constants: Vec, + + /// Source location entries for traceback generation. + location_table: Vec, + + /// Exception handler entries. + exception_table: Vec, + + /// Current source location (set before emitting instructions). + current_location: Option, + + /// Current focus location within the source range. + current_focus: Option, + + /// Operand-stack depth before the next opcode, or `None` in dead code. + /// Unconditional terminators include `AssertFailed`, but not `Assert`. + current_stack_depth: Option, + + /// Local variable names indexed by slot number. + /// + /// Populated during compilation to enable proper NameError messages + /// when accessing undefined local variables. + local_names: Vec>, +} + +impl CodeBuilder { + /// Creates a new empty `CodeBuilder` in the dead-code state — no region + /// is open yet. Call `enter_region(0)` (or another depth, for an + /// exception-table-reached region) before emitting. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Sets the current source location for subsequent instructions. + /// + /// This location will be recorded in the location table when the next + /// instruction is emitted. Call this before emitting instructions that + /// correspond to source code. + pub fn set_location(&mut self, range: CodeRange, focus: Option) { + self.current_location = Some(range); + self.current_focus = focus; + } + + /// Emits a no-operand instruction and updates stack depth tracking. + pub fn emit(&mut self, op: Opcode) -> Result<(), CompileError> { + self.emit_with_operand(op, Operand::None) + } + + /// Emits an instruction with a u8 operand and updates stack depth tracking. + pub fn emit_u8(&mut self, op: Opcode, operand: u8) -> Result<(), CompileError> { + self.emit_with_operand(op, Operand::U8(operand)) + } + + /// Emits an instruction with an i8 operand and updates stack depth tracking. + pub fn emit_i8(&mut self, op: Opcode, operand: i8) -> Result<(), CompileError> { + self.emit_with_operand(op, Operand::I8(operand)) + } + + /// Emits an instruction with two u8 operands and updates stack depth tracking. + /// + /// Used for UnpackEx: before_count (u8) + after_count (u8) + pub fn emit_u8_u8(&mut self, op: Opcode, operand1: u8, operand2: u8) -> Result<(), CompileError> { + self.emit_with_operand(op, Operand::U8U8(operand1, operand2)) + } + + /// Emits an instruction with a u16 operand (little-endian) and updates stack depth tracking. + pub fn emit_u16(&mut self, op: Opcode, operand: u16) -> Result<(), CompileError> { + self.emit_with_operand(op, Operand::U16(operand)) + } + + /// Emits two u16 operands, e.g. attribute and dotted-path IDs for `LoadSubmodule`. + pub fn emit_u16_u16(&mut self, op: Opcode, operand1: u16, operand2: u16) -> Result<(), CompileError> { + self.emit_with_operand(op, Operand::U16U16(operand1, operand2)) + } + + /// Emits an instruction with a u16 operand followed by a u8 operand. + /// + /// Used for `MakeFunction`, `CallAttr`, `CallAttrExtended`. + pub fn emit_u16_u8(&mut self, op: Opcode, operand1: u16, operand2: u8) -> Result<(), CompileError> { + self.emit_with_operand(op, Operand::U16U8(operand1, operand2)) + } + + /// Emits an instruction with a u16 operand followed by two u8 operands. + /// + /// Used for MakeClosure: func_id (u16) + defaults_count (u8) + cell_count (u8) + pub fn emit_u16_u8_u8( + &mut self, + op: Opcode, + operand1: u16, + operand2: u8, + operand3: u8, + ) -> Result<(), CompileError> { + self.emit_with_operand(op, Operand::U16U8U8(operand1, operand2, operand3)) + } + + /// Emits `CallBuiltinFunction` instruction. + /// + /// Operands: builtin_id (u8) + arg_count (u8) + /// + /// The builtin_id is the `#[repr(u8)]` discriminant of `BuiltinsFunctions`. + /// This is an optimization that avoids constant pool lookup and stack manipulation. + pub fn emit_call_builtin_function(&mut self, builtin_id: u8, arg_count: u8) -> Result<(), CompileError> { + self.emit_with_operand(Opcode::CallBuiltinFunction, Operand::U8U8(builtin_id, arg_count)) + } + + /// Emits `CallBuiltinType` instruction. + /// + /// Operands: type_id (u8) + arg_count (u8) + /// + /// The type_id is the `#[repr(u8)]` discriminant of `BuiltinsTypes`. + /// This is an optimization for type constructors like `list()`, `int()`, `str()`. + pub fn emit_call_builtin_type(&mut self, type_id: u8, arg_count: u8) -> Result<(), CompileError> { + self.emit_with_operand(Opcode::CallBuiltinType, Operand::U8U8(type_id, arg_count)) + } + + /// Emits CallFunctionKw with inline keyword names. + /// + /// Operands: pos_count (u8) + kw_count (u8) + kw_count * name_id (u16 each) + /// + /// The kwname_ids slice contains StringId indices for each keyword argument + /// name, in order matching how the values were pushed to the stack. + pub fn emit_call_function_kw(&mut self, pos_count: u8, kwname_ids: &[u16]) -> Result<(), CompileError> { + self.emit_with_operand(Opcode::CallFunctionKw, Operand::CallKw { pos_count, kwname_ids }) + } + + /// Emits CallAttrKw with inline keyword names. + /// + /// Operands: attr_name_id (u16) + pos_count (u8) + kw_count (u8) + kw_count * name_id (u16 each) + /// + /// The kwname_ids slice contains StringId indices for each keyword argument + /// name, in order matching how the values were pushed to the stack. + pub fn emit_call_attr_kw( + &mut self, + attr_name_id: u16, + pos_count: u8, + kwname_ids: &[u16], + ) -> Result<(), CompileError> { + self.emit_with_operand( + Opcode::CallAttrKw, + Operand::CallAttrKw { + attr_name_id, + pos_count, + kwname_ids, + }, + ) + } + + /// Emits a forward jump instruction, returning a label to patch later. + /// + /// After `Jump` the tracker transitions to dead (it's unconditional). + /// All other jumps continue to fall through. + /// + /// Returns a `CompileError` if the jump-taken target depth doesn't fit + /// in `u16`, mirroring the same overflow case `adjust_stack` detects. + /// + /// # Panics + /// + /// Panics on non-jump opcodes (`op.jump_taken_stack_effect()` is the + /// shared invariant check). + pub fn emit_jump(&mut self, op: Opcode) -> Result { + let Some(pre_depth) = self.current_stack_depth else { + // Dead code, emit dummy jump label + return Ok(JumpLabel { inner: None }); + }; + // Capture the opcode position (where patch_jump will overwrite the i16) + // before `emit_with_operand` pushes the bytes. + let offset = self.current_offset(); + // Capture the source location now so any later `patch_jump` overflow + // anchors the diagnostic at this jump site rather than the (often + // unrelated) statement where the patch happens to resolve. + let source_position = self.current_location.unwrap_or_default(); + // Jump-taken target depth. `jump_taken_delta` panics for non-jumps. + let target_depth = u16::try_from(i32::from(pre_depth) + i32::from(op.jump_taken_stack_effect())) + .map_err(|_| self.stack_too_large())?; + // Emit jump with dummy offset; patch_jump is required to fill in the real offset later. + self.emit_with_operand(op, Operand::Offset(RelativeOffset(0)))?; + Ok(JumpLabel { + inner: Some(JumpLabelInner { + offset, + stack_depth: target_depth, + source_position, + }), + }) + } + + /// Patches a forward jump to point to the current bytecode location. + /// + /// State transitions: if the builder is emitting dead code, `patch_jump` + /// re-establishes the live depth from `label.stack_depth`. + /// + /// Returns a `CompileError` if the resolved jump offset doesn't fit in + /// `i16`, which means the function is too large for our bytecode encoding. + /// + /// # Panics + /// + /// In debug builds, panics if the jump label has a different stack depth + /// compared to the current depth (if live) — this indicates a compiler bug + /// in stack-effect tracking rather than a user-input-driven overflow. + pub fn patch_jump(&mut self, label: JumpLabel) -> Result<(), CompileError> { + let Some(label) = label.inner else { + // emit_jump was dead code, nothing to do + return Ok(()); + }; + + let stack_depth = self.current_stack_depth.unwrap_or_else(|| { + self.new_code_region(label.stack_depth); + label.stack_depth + }); + + let target = JumpTargetInner { + offset: self.current_offset(), + stack_depth, + }; + + let offset = calculate_jump_offset(label, target) + .ok_or_else(|| jump_too_large_at(label.source_position))? + .as_i16(); + let bytes = offset.to_le_bytes(); + self.bytecode[label.offset.0 + 1] = bytes[0]; + self.bytecode[label.offset.0 + 2] = bytes[1]; + Ok(()) + } + + /// Emits a backward jump to a known target. Any jump opcode is accepted; + /// `Opcode::jump_taken_delta` is the shared source of truth for the + /// jump-taken stack effect (and panics for non-jump opcodes). + /// + /// Returns a `CompileError` if the jump offset doesn't fit in `i16`, + /// which means the function is too large for our bytecode encoding. + /// + /// # Panics + /// - Panics if the jump target was emitted in dead code, and the current + /// code is live. + /// - In debug builds, panics if the current stack depth plus the jump's stack + /// effect do not match the jump target stack depth. + /// - Panics on non-jump opcodes. + pub fn emit_jump_to(&mut self, op: Opcode, target: JumpTarget) -> Result<(), CompileError> { + let Some(target_depth) = self.current_stack_depth else { + // Emitting dead code, do no work + return Ok(()); + }; + + let label = JumpLabelInner { + offset: self.current_offset(), + stack_depth: target_depth + .checked_add_signed(op.jump_taken_stack_effect()) + .ok_or_else(|| self.stack_too_large())?, + // Backward jumps are emitted and resolved at the same spot, so + // there's no patch-time/emit-time split; either position is the + // same statement. + source_position: self.current_location.unwrap_or_default(), + }; + let Some(target) = target.0 else { + // Target is dead code + unreachable!("emit_jump_to: cannot jump from live code to dead code"); + }; + + let offset = calculate_jump_offset(label, target).ok_or_else(|| self.jump_too_large())?; + self.emit_with_operand(op, Operand::Offset(offset)) + } + + /// Returns the current bytecode position as an opaque `Offset`. + /// + /// Use this to capture the bounds of try/except/finally regions for + /// `ExceptionEntry::new`. + #[must_use] + pub fn current_offset(&self) -> Offset { + Offset(self.bytecode.len()) + } + + /// Returns the current source position for compile-time diagnostics. + #[must_use] + pub fn current_position(&self) -> CodeRange { + self.current_location.unwrap_or_default() + } + + /// Returns a `JumpTarget` capturing both the current bytecode position and + /// the stack depth at that position. + #[must_use] + pub fn current_jump_target(&self) -> JumpTarget { + JumpTarget(self.current_stack_depth.map(|depth| JumpTargetInner { + offset: self.current_offset(), + stack_depth: depth, + })) + } + + /// Registers the names of slots `0..names.len()` in one pass. + /// + /// Used for module frames, whose namespace is known in full before + /// compilation starts; a long REPL session's globals run to thousands of + /// slots, so this must stay a plain copy rather than a per-slot insert. + /// Must be called before any [`register_local_name`](Self::register_local_name). + pub fn register_local_names(&mut self, names: &[StringId]) { + debug_assert!(self.local_names.is_empty(), "register_local_names must run first"); + self.local_names.extend(names.iter().map(|&name| Some(name))); + } + + /// Registers a local variable name for a given slot. + /// + /// This is called during compilation when we encounter a variable access. + /// The name is used to generate proper NameError messages. + pub fn register_local_name(&mut self, slot: u16, name: StringId) { + let slot_idx = slot as usize; + // Extend the vector if needed + if slot_idx >= self.local_names.len() { + self.local_names.resize(slot_idx + 1, None); + } + // Only set if not already set (first occurrence determines the name) + if self.local_names[slot_idx].is_none() { + self.local_names[slot_idx] = Some(name); + } + } + + /// Emits a `RaiseUnboundLocal` opcode carrying the comprehension target + /// name to be reported in `UnboundLocalError`. + /// + /// Used by the comprehension compiler at sites where static analysis + /// proves the target is read before its `for` clause assigns it. + pub fn emit_raise_unbound_local(&mut self, name_id: StringId) -> Result<(), CompileError> { + let name_idx = u16::try_from(name_id.index()).map_err(|_| self.name_id_too_large())?; + self.emit_with_operand(Opcode::RaiseUnboundLocal, Operand::U16(name_idx)) + } + + /// Emits a `LoadLocal` instruction, using specialized variants for common slots. + pub fn emit_load_local(&mut self, slot: u16) -> Result<(), CompileError> { + match slot { + 0 => self.emit(Opcode::LoadLocal0), + 1 => self.emit(Opcode::LoadLocal1), + 2 => self.emit(Opcode::LoadLocal2), + 3 => self.emit(Opcode::LoadLocal3), + _ => { + if let Ok(s) = u8::try_from(slot) { + self.emit_u8(Opcode::LoadLocal, s) + } else { + self.emit_u16(Opcode::LoadLocalW, slot) + } + } + } + } + + /// Emits a `LoadGlobalCallable` instruction for call-context loads. + /// + /// The `name_id` is encoded directly in the operand to avoid the ambiguity + /// of looking up global names from a function's local_names array (global slots + /// and local slots use different namespaces). + pub fn emit_load_global_callable(&mut self, slot: u16, name_id: StringId) -> Result<(), CompileError> { + let name_id_u16 = u16::try_from(name_id.index()).map_err(|_| self.name_id_too_large())?; + self.emit_with_operand(Opcode::LoadGlobalCallable, Operand::U16U16(slot, name_id_u16)) + } + + /// Emits a `LoadName` / `StoreName` / `DeleteName` with its slot, interned + /// name and `NAME_*` flags; the name is encoded for the same reason as in + /// [`emit_load_global_callable`](Self::emit_load_global_callable). + pub fn emit_name_op(&mut self, op: Opcode, slot: u16, name_id: StringId, flags: u8) -> Result<(), CompileError> { + let name_id_u16 = u16::try_from(name_id.index()).map_err(|_| self.name_id_too_large())?; + self.emit_with_operand(op, Operand::U16U16U8(slot, name_id_u16, flags)) + } + + /// Emits `StoreLocal`, using wide variant for slots > 255. + pub fn emit_store_local(&mut self, slot: u16) -> Result<(), CompileError> { + if let Ok(s) = u8::try_from(slot) { + self.emit_u8(Opcode::StoreLocal, s) + } else { + self.emit_u16(Opcode::StoreLocalW, slot) + } + } + + /// Adds a constant to the pool, returning its index. + /// + /// Returns a `CompileError` if the constant pool would exceed `u16::MAX` + /// entries — `LoadConst` and related opcodes encode the index in `u16`, + /// so any function with more than `65 536` distinct constants exceeds the + /// bytecode format. + pub fn add_const(&mut self, value: Value) -> Result { + let idx_u16 = u16::try_from(self.constants.len()).map_err(|_| self.constant_pool_full())?; + self.constants.push(value); + Ok(idx_u16) + } + + /// Adds an exception handler entry built from the given region bounds. + /// + /// Entries should be added in innermost-first order for nested try blocks. + /// Returns a `CompileError` if any of the offsets exceeds the `u32` cap + /// in `ExceptionEntry` — practically unreachable given the i16 jump + /// limit, but kept honest for the same reason as `bytecode_too_large`. + pub fn add_exception_entry( + &mut self, + start: Offset, + end: Offset, + handler: Offset, + stack_depth: u16, + exception_stack_count: u16, + kind: HandlerKind, + ) -> Result<(), CompileError> { + let start = start.as_u32().ok_or_else(|| self.bytecode_too_large())?; + let end = end.as_u32().ok_or_else(|| self.bytecode_too_large())?; + let handler = handler.as_u32().ok_or_else(|| self.bytecode_too_large())?; + let entry = ExceptionEntry::new(start, end, handler, stack_depth, exception_stack_count, kind); + self.exception_table.push(entry); + Ok(()) + } + + /// Returns the current stack depth, or `None` if not currently emitting a code region. + #[must_use] + pub fn stack_depth(&self) -> Option { + self.current_stack_depth + } + + /// Reports whether the tracker is in the dead-code state. + /// + /// Used by compile_block to stop emitting after a terminator and by emit + /// helpers to decide whether to bother computing live target depths. + #[must_use] + pub fn is_dead(&self) -> bool { + self.current_stack_depth.is_none() + } + + /// Finishes a compiled body, transferring its buffers and metadata to `Code`. + #[must_use] + pub fn build(self) -> Code { + // Unnamed slots use the sentinel understood by local-name lookup. + let local_names = self.local_names.into_iter().map(Option::unwrap_or_default).collect(); + Code::new( + self.bytecode, + self.constants, + self.location_table, + self.exception_table, + local_names, + ) + } + + /// Records the current location in the location table if set. + /// + /// Returns a `CompileError` if the bytecode offset has grown past + /// `u32::MAX` — the i16 jump-offset cap means this is practically + /// unreachable, but `LocationEntry`'s offset is `u32` so we surface the + /// limit cleanly rather than panic. + fn record_location(&mut self) -> Result<(), CompileError> { + if let Some(range) = self.current_location { + let offset = u32::try_from(self.bytecode.len()).map_err(|_| self.bytecode_too_large())?; + self.location_table + .push(LocationEntry::new(offset, range, self.current_focus)); + } + Ok(()) + } + + /// Opens a new code region at the given stack depth. + /// + /// Use this: + /// - After `CodeBuilder::new()`, with `depth = 0`, to start the initial + /// region (the top of a function or module body). + /// - For points reached via the exception table (handler entries with the + /// exception on stack at `base + 1`, finally cleanup) where the depth + /// comes from outside the fall-through graph. + /// + /// # Panics + /// + /// Panics if the builder is currently emitting live code. + pub fn new_code_region(&mut self, depth: u16) { + match self.current_stack_depth { + Some(d) => { + panic!("enter_region: cannot start new code region at depth {depth} while currently at live depth {d}") + } + None => self.current_stack_depth = Some(depth), + } + } + + /// Adjusts the stack depth by the given delta. + /// + /// Positive values indicate pushes, negative values indicate pops. + /// In the dead-code state this is a no-op: dead code can be emitted + /// freely. + fn adjust_stack(&mut self, delta: i32) -> Result<(), CompileError> { + let Some(depth) = self.current_stack_depth else { + return Ok(()); + }; + let new_depth = i32::from(depth) + delta; + // Stack depth shouldn't go negative (indicates compiler bug) + debug_assert!(new_depth >= 0, "Stack depth went negative: {new_depth}"); + let new_depth = u16::try_from(new_depth.max(0)).map_err(|_| self.stack_too_large())?; + self.current_stack_depth = Some(new_depth); + Ok(()) + } + + /// Emits an instruction, recording its location and stack effect. + /// Unconditional terminators enter dead code, where emission is a no-op. + /// Jump helpers use this path to keep stack-depth tracking centralized. + fn emit_with_operand(&mut self, op: Opcode, operand: Operand<'_>) -> Result<(), CompileError> { + if self.is_dead() { + return Ok(()); + } + self.record_location()?; + self.bytecode.push(op as u8); + match operand { + Operand::None => {} + Operand::U8(b) => self.bytecode.push(b), + Operand::I8(b) => self.bytecode.push(b.to_ne_bytes()[0]), + Operand::U16(w) => self.bytecode.extend(w.to_le_bytes()), + Operand::Offset(relative) => self.bytecode.extend(relative.0.to_le_bytes()), + Operand::U8U8(a, b) => { + self.bytecode.push(a); + self.bytecode.push(b); + } + Operand::U16U8(w, b) => { + self.bytecode.extend(w.to_le_bytes()); + self.bytecode.push(b); + } + Operand::U16U16(w1, w2) => { + self.bytecode.extend(w1.to_le_bytes()); + self.bytecode.extend(w2.to_le_bytes()); + } + Operand::U16U8U8(w, b1, b2) => { + self.bytecode.extend(w.to_le_bytes()); + self.bytecode.push(b1); + self.bytecode.push(b2); + } + Operand::U16U16U8(w1, w2, b) => { + self.bytecode.extend(w1.to_le_bytes()); + self.bytecode.extend(w2.to_le_bytes()); + self.bytecode.push(b); + } + Operand::CallKw { pos_count, kwname_ids } => { + let kw_count = u8::try_from(kwname_ids.len()).map_err(|_| self.kw_count_too_large())?; + self.bytecode.push(pos_count); + self.bytecode.push(kw_count); + for &name_id in kwname_ids { + self.bytecode.extend(name_id.to_le_bytes()); + } + } + Operand::CallAttrKw { + attr_name_id, + pos_count, + kwname_ids, + } => { + let kw_count = u8::try_from(kwname_ids.len()).map_err(|_| self.kw_count_too_large())?; + self.bytecode.extend(attr_name_id.to_le_bytes()); + self.bytecode.push(pos_count); + self.bytecode.push(kw_count); + for &name_id in kwname_ids { + self.bytecode.extend(name_id.to_le_bytes()); + } + } + } + self.adjust_stack(op.stack_effect(operand))?; + if matches!( + op, + Opcode::ReturnValue + | Opcode::Raise + | Opcode::Reraise + | Opcode::RaiseUnboundLocal + | Opcode::AssertFailed + | Opcode::Jump + ) { + self.current_stack_depth = None; + } + + Ok(()) + } + + #[cold] + #[inline(never)] + fn jump_too_large(&self) -> CompileError { + jump_too_large_at(self.current_location.unwrap_or_default()) + } + + /// Builds the `CompileError` for a `StringId` that doesn't fit in the + /// `u16` operand of a name-bearing opcode. Used by emit helpers that + /// inline the name id directly (e.g. `LoadGlobalCallable`). + /// + /// The count is `u16::MAX + 1` (`65 536`) because a `u16` operand can + /// address indices `0..=u16::MAX`, so the format can name that many + /// distinct interned strings before overflowing. + #[cold] + #[inline(never)] + fn name_id_too_large(&self) -> CompileError { + CompileError::new( + format!( + "module has too many distinct names; the bytecode format supports up to {} interned strings", + usize::from(u16::MAX) + 1, + ), + self.current_location.unwrap_or_default(), + ) + } + + /// Builds the `CompileError` for a `CallFunctionKw`/`CallAttrKw` keyword + /// count that doesn't fit in `u8`. Anchored to the builder's current + /// location (the call expression). + #[cold] + #[inline(never)] + fn kw_count_too_large(&self) -> CompileError { + CompileError::new( + format!("call has too many keyword arguments; maximum is {} per call", u8::MAX), + self.current_location.unwrap_or_default(), + ) + } + + /// Builds the `CompileError` for a `add_const` that would overflow the + /// per-`Code` constant pool's `u16` index. One function/module body can + /// hold at most `u16::MAX + 1` distinct constants (the check fires when + /// the pool already holds `u16::MAX + 1` entries — indices `0..=u16::MAX`). + #[cold] + #[inline(never)] + fn constant_pool_full(&self) -> CompileError { + CompileError::new( + format!( + "function has too many constants; maximum is {} per function", + usize::from(u16::MAX) + 1, + ), + self.current_location.unwrap_or_default(), + ) + } + + /// Builds the `CompileError` for an operand-stack depth or `emit_jump` + /// target depth that doesn't fit in `u16`. The same message is used by + /// `adjust_stack`, `emit_jump`, and `emit_jump_to` so the user sees one + /// consistent diagnostic for "too much stuff pushed" regardless of which + /// path detects it. + #[cold] + #[inline(never)] + fn stack_too_large(&self) -> CompileError { + CompileError::new( + "function too large: required stack exceeds u16::MAX", + self.current_location.unwrap_or_default(), + ) + } + + /// Builds the `CompileError` for a `record_location` whose bytecode + /// position doesn't fit in the `u32` field of `LocationEntry`. Practically + /// unreachable because the `i16` jump-offset cap kicks in at ~32 KB of + /// bytecode, but kept defensive in case future opcodes loosen that limit. + /// The count is `u32::MAX + 1` because the check happens on the pre-push + /// length and the next byte makes it that many bytes total. + #[cold] + #[inline(never)] + fn bytecode_too_large(&self) -> CompileError { + CompileError::new( + format!( + "function bytecode too large; maximum is {} bytes", + u64::from(u32::MAX) + 1, + ), + self.current_location.unwrap_or_default(), + ) + } +} + +/// Builds the `CompileError` for a jump offset that doesn't fit in `i16`, +/// anchored to an explicit source position rather than the builder's current +/// location. Used by `patch_jump` so a forward-jump overflow is reported at +/// the original `emit_jump` site (captured in `JumpLabelInner::source_position`) +/// rather than the unrelated statement where the patch happens to resolve. +#[cold] +#[inline(never)] +fn jump_too_large_at(position: CodeRange) -> CompileError { + CompileError::new("function too large: jump offset exceeds i16 range", position) +} + +/// Label for a forward jump that needs patching. +#[derive(Debug, Clone, Copy)] +pub struct JumpLabel { + /// `Option` is none to allow for the dead code case, in which case + /// the jump is unreachable and patch_jump needs do no work. + inner: Option, +} + +#[derive(Debug, Clone, Copy)] +struct JumpLabelInner { + /// Position of the jump's opcode byte. `patch_jump` writes the relative + /// i16 at `offset.0 + 1`. + offset: Offset, + /// The stack depth that the jump-taken path leaves on the stack + /// when the jump is taken to the target. Used in `calculate_jump_offset` + /// to enforce the invariant that all paths arriving at a given bytecode + /// position have the same stack depth. + stack_depth: u16, + /// Source location of the jump itself (the statement that emitted it), + /// captured at `emit_jump` time. Used by `patch_jump` so an offset + /// overflow anchors the diagnostic at the jump site rather than at the + /// patch site, which is usually a different (and less informative) + /// statement. + source_position: CodeRange, +} + +/// A position in the bytecode stream. +/// +/// Returned by `CodeBuilder::current_offset` and consumed by `emit_jump_to` +/// (as a backward-jump target) and `ExceptionEntry::new` (as the bounds of +/// try/except/finally regions). The wrapped `usize` is intentionally private: +/// `Offset` values can only originate from the builder, which prevents +/// arbitrary integers from being used in places where the bytecode position +/// is a load-bearing invariant. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Offset(usize); + +impl Offset { + /// Returns the offset as a `u32` — the serialized form used by + /// `ExceptionEntry` and `LocationEntry` — or `None` if the bytecode + /// position exceeds `u32::MAX`. + /// + /// Reachable only with > 4 GB of generated bytecode in a single function, + /// which the `i16` jump-offset cap already prevents in practice. Returns + /// `Option` rather than panicking so the rare overflow surfaces through + /// the caller's `CompileError` path (see `CodeBuilder::bytecode_too_large`) + /// alongside the other limit failures. + #[must_use] + pub fn as_u32(self) -> Option { + u32::try_from(self.0).ok() + } +} + +/// Relative offset used as jump operand. +/// +/// Jumps are computed as per x86 convention: the offset is relative to the position +/// immediately after the jump instruction. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RelativeOffset(i16); + +impl RelativeOffset { + #[must_use] + pub fn as_i16(self) -> i16 { + self.0 + } +} + +/// Calculate the jump offset from a jump instruction at `from` to a target at `to`. +/// +/// Returns `None` if the offset doesn't fit in `i16` — the caller (always +/// `&mut self` on the builder) converts that into a `CompileError` anchored +/// to the current source location via `jump_too_large`. +fn calculate_jump_offset(from: JumpLabelInner, to: JumpTargetInner) -> Option { + // All jumps are currently 3 byte instructions: opcode + i16 offset + const JUMP_BYTECODE_SIZE: usize = size_of::() + size_of::(); + + // Jumps are calculated from after the jump instruction; the label is the position of the jump itself + let from_i64 = i64::try_from(from.offset.0 + JUMP_BYTECODE_SIZE).expect("bytecode offset exceeds i64"); + let to_i64 = i64::try_from(to.offset.0).expect("bytecode offset exceeds i64"); + + // stack depth must match at merge point - if this fails, it indicates the builder + // is not tracking stack effect correctly for some instructions + debug_assert_eq!( + from.stack_depth, to.stack_depth, + "jump merge: arriving with depth {} but jump target has depth {}", + from.stack_depth, to.stack_depth, + ); + + let raw_offset = to_i64 - from_i64; + i16::try_from(raw_offset).ok().map(RelativeOffset) +} + +/// Target for a backward jump. +#[derive(Debug, Clone, Copy)] +pub struct JumpTarget(Option); + +#[derive(Debug, Clone, Copy)] +struct JumpTargetInner { + offset: Offset, + /// The stack depth that at this position. Used in `calculate_jump_offset` + /// to enforce the invariant that all paths arriving at a given bytecode. + stack_depth: u16, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_emit_basic() { + let mut builder = CodeBuilder::new(); + builder.new_code_region(0); + builder.emit(Opcode::LoadNone).unwrap(); + builder.emit(Opcode::Pop).unwrap(); + + let code = builder.build(); + assert_eq!(code.bytecode(), &[Opcode::LoadNone as u8, Opcode::Pop as u8]); + } + + #[test] + fn test_emit_u8_operand() { + let mut builder = CodeBuilder::new(); + builder.new_code_region(0); + builder.emit_u8(Opcode::LoadLocal, 42).unwrap(); + + let code = builder.build(); + assert_eq!(code.bytecode(), &[Opcode::LoadLocal as u8, 42]); + } + + #[test] + fn test_emit_u16_operand() { + let mut builder = CodeBuilder::new(); + builder.new_code_region(0); + builder.emit_u16(Opcode::LoadConst, 0x1234).unwrap(); + + let code = builder.build(); + assert_eq!(code.bytecode(), &[Opcode::LoadConst as u8, 0x34, 0x12]); + } + + #[test] + fn test_forward_jump() { + let mut builder = CodeBuilder::new(); + builder.new_code_region(0); + let jump = builder.emit_jump(Opcode::Jump).unwrap(); + builder.new_code_region(0); + builder.emit(Opcode::LoadNone).unwrap(); + builder.emit(Opcode::Pop).unwrap(); + builder.patch_jump(jump).unwrap(); + builder.emit(Opcode::LoadNone).unwrap(); // Return value + builder.emit(Opcode::ReturnValue).unwrap(); + + let code = builder.build(); + assert_eq!( + code.bytecode(), + &[ + Opcode::Jump as u8, + 2i16.to_le_bytes()[0], + 2i16.to_le_bytes()[1], // 2 bytes to jump from the end of the jump instruction to the LoadNone after the patch + Opcode::LoadNone as u8, + Opcode::Pop as u8, + Opcode::LoadNone as u8, + Opcode::ReturnValue as u8, + ] + ); + } + + #[test] + fn test_backward_jump() { + let mut builder = CodeBuilder::new(); + builder.new_code_region(0); + let loop_start = builder.current_jump_target(); + builder.emit(Opcode::LoadNone).unwrap(); // offset 0, 1 byte + builder.emit(Opcode::Pop).unwrap(); // offset 1, 1 byte + builder.emit_jump_to(Opcode::Jump, loop_start).unwrap(); // offset 2, target 0 + + let code = builder.build(); + // Jump at offset 2, target at offset 0 + // Offset = 0 - (2 + 3) = -5 + let expected_offset = (-5i16).to_le_bytes(); + assert_eq!( + code.bytecode(), + &[ + Opcode::LoadNone as u8, + Opcode::Pop as u8, + Opcode::Jump as u8, + expected_offset[0], + expected_offset[1], + ] + ); + } + + #[test] + fn test_load_local_specialization() { + let mut builder = CodeBuilder::new(); + builder.new_code_region(0); + builder.emit_load_local(0).unwrap(); + builder.emit_load_local(1).unwrap(); + builder.emit_load_local(2).unwrap(); + builder.emit_load_local(3).unwrap(); + builder.emit_load_local(4).unwrap(); + builder.emit_load_local(256).unwrap(); + + let code = builder.build(); + assert_eq!( + code.bytecode(), + &[ + Opcode::LoadLocal0 as u8, + Opcode::LoadLocal1 as u8, + Opcode::LoadLocal2 as u8, + Opcode::LoadLocal3 as u8, + Opcode::LoadLocal as u8, + 4, + Opcode::LoadLocalW as u8, + 0, + 1, // 256 in little-endian + ] + ); + } + + #[test] + fn test_add_const() { + let mut builder = CodeBuilder::new(); + builder.new_code_region(0); + let idx1 = builder.add_const(Value::Int(42)).unwrap(); + let idx2 = builder.add_const(Value::None).unwrap(); + + assert_eq!(idx1, 0); + assert_eq!(idx2, 1); + } +} diff --git a/crates/bashkit-monty/src/bytecode/code.rs b/crates/bashkit-monty/src/bytecode/code.rs new file mode 100644 index 000000000..62f0f3845 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/code.rs @@ -0,0 +1,304 @@ +//! Code object containing compiled bytecode and metadata. +//! +//! A `Code` object represents a compiled function or module. It contains the raw +//! bytecode instructions, a constant pool, source location information for tracebacks, +//! and an exception handler table. + +use crate::{intern::StringId, parse::CodeRange, value::Value}; + +/// Compiled bytecode for a function or module. +/// +/// This is the output of the bytecode compiler and the input to the VM. +/// Each function has its own Code object; module-level code also gets one. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct Code { + /// Variable-width instructions, addressed by body-relative offsets. + #[serde(with = "serde_bytes")] + #[serde(rename = "B")] + bytecode: Vec, + + /// Immediate constants indexed by `LoadConst`; heap literals live in `Interns`. + #[serde(rename = "C")] + constants: Vec, + + /// Source location table for tracebacks. + /// + /// Maps bytecode offsets to source locations. Used to generate Python-style + /// tracebacks with line numbers and caret markers when exceptions occur. + #[serde(rename = "L")] + location_table: Vec, + + /// Exception handler table. + /// + /// Maps protected bytecode ranges to their exception handlers. Consulted when + /// an exception is raised to find the appropriate handler. Entries are ordered + /// innermost-first for nested try blocks. + #[serde(rename = "E")] + exception_table: Vec, + + /// Local variable names for error messages. + /// + /// Maps slot indices to variable names. Used to generate proper NameError + /// messages when accessing undefined local variables (e.g., "name 'x' is not defined"). + #[serde(rename = "N")] + local_names: Vec, +} + +impl Code { + /// Creates an empty code object for tests that only need VM context. + #[cfg(test)] + pub(crate) fn empty() -> Self { + Self::new(Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()) + } + + /// Creates a new Code object with all components. + /// + /// This is typically called by `CodeBuilder::build()` after compilation. + #[must_use] + pub fn new( + bytecode: Vec, + constants: Vec, + location_table: Vec, + exception_table: Vec, + local_names: Vec, + ) -> Self { + Self { + bytecode, + constants, + location_table, + exception_table, + local_names, + } + } + + /// Returns the raw bytecode bytes. + #[must_use] + pub fn bytecode(&self) -> &[u8] { + &self.bytecode + } + + /// Returns the constant referenced by a `LoadConst` operand. + /// Panics for an index not produced by this code's compiler. + #[must_use] + pub fn constant(&self, index: u16) -> &Value { + &self.constants[usize::from(index)] + } + + /// Returns the local variable name for a given slot index. + /// + /// Used to generate proper NameError messages when accessing undefined locals. + #[must_use] + pub fn local_name(&self, slot: u16) -> Option { + self.local_names.get(slot as usize).copied() + } + + /// Finds the location entry for a given bytecode offset. + /// + /// Location entries are recorded at instruction boundaries. This method finds + /// the most recent entry at or before the given offset. + /// + /// Returns `None` if the location table is empty, the offset is before + /// the first recorded location, or the offset exceeds `u32::MAX` (an + /// invariant violation; we degrade gracefully rather than panic since + /// this is on the traceback hot path). + #[must_use] + pub fn location_for_offset(&self, offset: usize) -> Option<&LocationEntry> { + let offset_u32 = u32::try_from(offset).ok()?; + // Entries are sorted by bytecode offset: take the last at or before `offset`. + let after = self + .location_table + .partition_point(|entry| entry.bytecode_offset <= offset_u32); + after.checked_sub(1).map(|index| &self.location_table[index]) + } + + /// Finds an exception handler for the given bytecode offset. + /// + /// Searches the exception table for an entry whose protected range contains + /// the given offset. Returns the first (innermost) matching handler, since + /// entries are ordered innermost-first for nested try blocks. + /// + /// Returns `None` if no handler covers this offset. + #[must_use] + pub fn find_exception_handler(&self, offset: u32) -> Option<&ExceptionEntry> { + self.exception_table.iter().find(|entry| entry.contains(offset)) + } +} + +impl Clone for Code { + /// Constants are immediates, so copying compiled code needs no heap references. + fn clone(&self) -> Self { + Self { + bytecode: self.bytecode.clone(), + constants: self.constants.iter().map(Value::copy_immediate).collect(), + location_table: self.location_table.clone(), + exception_table: self.exception_table.clone(), + local_names: self.local_names.clone(), + } + } +} + +/// Source location for a bytecode instruction, used for tracebacks. +/// +/// Python 3.11+ tracebacks show carets under the relevant expression: +/// ```text +/// File "test.py", line 2, in foo +/// return a + b + c +/// ~~^~~ +/// ``` +/// +/// The `range` covers the full expression (`a + b`), while `focus` points +/// to the specific operator (`+`) that caused the error. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct LocationEntry { + /// Bytecode offset this entry applies to. + /// + /// The entry applies from this offset until the next entry's offset + /// (or end of bytecode). + #[serde(rename = "B")] + bytecode_offset: u32, + + /// Full source range of the expression (for the underline). + #[serde(rename = "R")] + range: CodeRange, + + /// Optional focus point within the range (for the ^ caret). + /// + /// If None, the entire range is underlined without a focus caret. + /// This can be populated later for Python 3.11-style focused tracebacks. + #[serde(rename = "F")] + focus: Option, +} + +impl LocationEntry { + /// Creates a new location entry. + #[must_use] + pub fn new(bytecode_offset: u32, range: CodeRange, focus: Option) -> Self { + Self { + bytecode_offset, + range, + focus, + } + } + + /// Returns the full source range. + #[must_use] + pub fn range(&self) -> CodeRange { + self.range + } +} + +/// Whether a handler reads the exception value from the operand stack. +/// Pushing it for a cleanup handler that only re-raises is wasted work on +/// every level an exception propagates through. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum HandlerKind { + /// `except` dispatch and `with`, which read the value off the stack. + Consuming, + /// Only re-raises: the VM skips the push, the compiler the matching `Pop`. + Cleanup, +} + +/// Entry in the exception table - maps a protected bytecode range to its handler. +/// +/// Instead of maintaining a runtime stack of handlers (push/pop during execution), +/// we use a static table that's consulted when an exception is raised. This is +/// simpler and matches CPython 3.11+'s approach. +/// +/// For nested try blocks, multiple entries may cover the same bytecode offset. +/// Entries are ordered innermost-first, so the VM uses the first matching entry. +/// +/// # Example +/// +/// For `try: x = bar(); y = baz() except ValueError as e: print(e)`: +/// ```text +/// 0: LOAD_GLOBAL 'bar' +/// 4: CALL_FUNCTION 0 +/// 8: STORE_LOCAL 'x' +/// ... +/// 24: JUMP 50 # skip handler if no exception +/// 30: # exception handler starts here +/// ``` +/// Entry: `{ start: 0, end: 24, handler: 30, stack_depth: 0 }` +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +pub struct ExceptionEntry { + /// Start of protected bytecode range (inclusive). + #[serde(rename = "S")] + start: u32, + + /// End of protected bytecode range (exclusive). + #[serde(rename = "E")] + end: u32, + + /// Bytecode offset of the exception handler. + #[serde(rename = "H")] + handler: u32, + + /// Stack depth when entering the try block. + /// + /// Used to unwind the operand stack before jumping to handler. + /// The VM pops values until the stack reaches this depth, then + /// pushes the exception value. + #[serde(rename = "D")] + stack_depth: u16, + + /// This frame's `exception_stack` depth at region entry. + /// Unwinding trims later entries so bare `raise` cannot revive exceptions + /// from abandoned handlers. + #[serde(rename = "C")] + exception_stack_count: u16, + + /// Whether the handler wants the exception on the operand stack. + kind: HandlerKind, +} + +impl ExceptionEntry { + /// Creates a new exception table entry. + #[must_use] + pub fn new( + start: u32, + end: u32, + handler: u32, + stack_depth: u16, + exception_stack_count: u16, + kind: HandlerKind, + ) -> Self { + Self { + start, + end, + handler, + stack_depth, + exception_stack_count, + kind, + } + } + + /// Whether the VM must push the exception value before entering the handler. + #[must_use] + pub fn pushes_exception(&self) -> bool { + matches!(self.kind, HandlerKind::Consuming) + } + + /// Returns the handler bytecode offset. + #[must_use] + pub fn handler(&self) -> u32 { + self.handler + } + + /// Returns the stack depth to unwind to. + #[must_use] + pub fn stack_depth(&self) -> u16 { + self.stack_depth + } + + /// Returns this frame's exception-stack depth at region entry. + #[must_use] + pub fn exception_stack_count(&self) -> u16 { + self.exception_stack_count + } + + /// Returns true if the given bytecode offset is within this entry's protected range. + #[must_use] + pub fn contains(&self, offset: u32) -> bool { + offset >= self.start && offset < self.end + } +} diff --git a/crates/bashkit-monty/src/bytecode/compiler.rs b/crates/bashkit-monty/src/bytecode/compiler.rs new file mode 100644 index 000000000..a25b8bb3d --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/compiler.rs @@ -0,0 +1,4111 @@ +//! Bytecode compiler for transforming AST to bytecode. +//! +//! The compiler traverses the prepared AST (`PreparedNode` and `Expr` types from `expressions.rs`) +//! and emits bytecode instructions using `CodeBuilder`. It handles variable scoping, +//! control flow, and expression evaluation order following Python semantics. +//! +//! Functions are compiled recursively: when a `PreparedFunctionDef` is encountered, +//! its body is compiled to bytecode and a `Function` struct is created. All compiled +//! functions are appended to the session's intern table. + +use std::borrow::Cow; + +use monty_types::{MontyException, StackFrame}; + +use super::{ + RESERVED_MODULE_DUNDERS, + builder::{CodeBuilder, JumpLabel, JumpTarget, Offset}, + code::{Code, HandlerKind}, + op::{FORMAT_VALUE_HAS_SPEC, FORMAT_VALUE_STATIC_SPEC, NAME_CALLABLE, NAME_GLOBAL_ONLY, Opcode, assert_flags}, +}; +use crate::{ + args::{ArgExprs, CallArg, CallKwarg, Kwarg}, + builtins::{Builtins, BuiltinsFunctions}, + exception_private::{ExcType, RunError, SimpleException}, + expressions::{ + AssignTarget, Callable, CaptureSource, CmpOperator, Comprehension, DictItem, Expr, ExprLoc, Identifier, + ImportName, Literal, NameScope, Node, Operator, PreparedFunctionDef, PreparedNode, SequenceItem, Submodule, + UnpackTarget, + }, + fstring::{ConversionFlag, FStringPart, FormatSpec}, + function::Function, + intern::{CompileInterns, StringId}, + name_map::NameMap, + namespace::NamespaceId, + parse::{CodeRange, ExceptHandler, Try, syntax_error_in_snippet}, + run::CompileOptions, + source_map::{SourceMap, StackFrameExt}, + types::Type, + value::{EitherStr, Value}, +}; + +/// Maximum number of arguments allowed in a function call. +/// +/// This limit comes from the bytecode format: `CallFunction` and `CallAttr` +/// use a u8 operand for the argument count, so max 255. Python itself has no +/// such limit but we need one for our bytecode encoding. +const MAX_CALL_ARGS: usize = 255; + +/// Maximum number of distinct names in a single namespace (module or function). +/// +/// `LoadLocal`/`LoadGlobal`/`StoreLocal`/etc. encode the namespace slot in 16 +/// bits, so the slot index must fit in `u16`. CPython has no equivalent limit +/// but this is intrinsic to our compact bytecode encoding — exceeding it +/// surfaces to the user as a `SyntaxError`. +const MAX_NAMESPACE_SIZE: usize = u16::MAX as usize; + +/// Maximum number of targets in a single tuple-unpacking pattern (e.g. +/// `a, b, c = it` or the nested form `(a, b), c = it`). +/// +/// `UnpackSequence` / `UnpackEx` encode the per-level target count in `u8`, +/// so any individual unpacking level is capped at 255 targets (with +/// `UnpackEx` splitting that count into before-star and after-star halves). +const MAX_UNPACK_TARGETS: usize = 255; + +/// Maximum number of `for ... in ...` clauses in a single comprehension. +/// +/// `compile_comprehension_generators` recurses once per generator clause, so +/// without an up-front guard a syntactically valid source file with tens of +/// thousands of clauses can exhaust the Rust call stack during compilation — +/// well before runtime resource limits become active. The cap also matches +/// the `u8` operand consumed by `ListAppend` / `SetAdd` / `DictSetItem`: +/// each additional generator adds one iterator layer (plus its target +/// leaves) to the operand stack, and the bytecode format can only encode a +/// `u8` depth. CPython has no equivalent limit but real Python comprehension +/// usage is far below this cap. +const MAX_COMP_GENERATORS: usize = 255; + +/// Maximum number of emitted copies of `finally` bodies in one code object. +/// +/// Non-local exits require stack-specific copies, and nested `finally` blocks +/// can otherwise amplify a small source tree exponentially before VM resource +/// limits exist. +const MAX_FINALLY_COPIES: u16 = 1024; + +/// Converts a `usize` namespace size into the `u16` slot count expected by +/// the bytecode, surfacing a `CompileError` if the limit is exceeded. +/// +/// `kind` ("module", "function", "lambda", or "class body") is interpolated +/// into the error message so the user can distinguish which scope hit the cap. The position +/// is left as the default `CodeRange` because the relevant location is the +/// whole compile unit — there is no single offending statement to highlight. +fn check_namespace_size_u16(size: usize, kind: &'static str) -> Result { + u16::try_from(size).map_err(|_| namespace_too_large(size, kind)) +} + +#[cold] +#[inline(never)] +fn namespace_too_large(size: usize, kind: &'static str) -> CompileError { + CompileError::new( + format!( + "{kind} uses too many distinct names ({size}); the bytecode format supports up to {MAX_NAMESPACE_SIZE}" + ), + CodeRange::default(), + ) +} + +/// Converts a tuple-unpacking target count into the `u8` operand for +/// `UnpackSequence` (or the before/after halves of `UnpackEx`). +fn check_unpack_targets(count: usize, position: CodeRange) -> Result { + u8::try_from(count).map_err(|_| too_many_unpack_targets(count, position)) +} + +/// Rejects comprehensions with more than [`MAX_COMP_GENERATORS`] for-clauses +/// before recursive compilation, so attacker-controlled source cannot +/// trigger a Rust stack overflow during `Compiler::compile_module`. +/// +/// Anchored to the body expression's position because that's the +/// comprehension's most stable location to point at in a traceback caret. +fn check_comp_generators(count: usize, position: CodeRange) -> Result<(), CompileError> { + if count > MAX_COMP_GENERATORS { + Err(CompileError::new( + format!("comprehension has too many nested clauses ({count}); maximum is {MAX_COMP_GENERATORS}"), + position, + )) + } else { + Ok(()) + } +} + +/// Returns a position that locates `target` in source for error reporting. +/// +/// `Name` carries the identifier's position, `Starred` its inner target's, and +/// every other form its own. Used by comp-target unpacking when the per-leaf +/// position isn't available at the error point. +fn target_position(target: &UnpackTarget) -> CodeRange { + match target { + UnpackTarget::Name(ident) => ident.position, + UnpackTarget::Starred(inner) => target_position(inner), + UnpackTarget::Tuple { position, .. } + | UnpackTarget::Attr { position, .. } + | UnpackTarget::Subscript { position, .. } => *position, + } +} + +/// Whether an expression can resume a pushed/suspended call at its end offset. +fn return_expr_needs_padding(expr: &ExprLoc) -> bool { + match &expr.expr { + Expr::Call { .. } | Expr::AttrCall { .. } | Expr::IndirectCall { .. } | Expr::Await(_) => true, + Expr::IfElse { orelse, .. } => return_expr_needs_padding(orelse), + Expr::Op { + op: Operator::And | Operator::Or, + right, + .. + } => return_expr_needs_padding(right), + _ => false, + } +} + +#[cold] +#[inline(never)] +fn too_many_unpack_targets(count: usize, position: CodeRange) -> CompileError { + CompileError::new( + format!("too many targets in tuple unpacking ({count}); maximum is {MAX_UNPACK_TARGETS}"), + position, + ) +} + +/// Converts an in-memory collection length (list/tuple/dict/set literal element +/// count, dict pair count) into the `u16` operand of `BuildList`/`BuildTuple`/ +/// `BuildDict`/`BuildSet`. +fn check_collection_size_u16(count: usize, position: CodeRange) -> Result { + u16::try_from(count).map_err(|_| collection_too_large(count, position)) +} + +#[cold] +#[inline(never)] +fn collection_too_large(count: usize, position: CodeRange) -> CompileError { + CompileError::new( + format!( + "collection literal has too many elements ({count}); maximum is {}", + u16::MAX + ), + position, + ) +} + +/// Converts the index of a newly-defined function into the `u16` operand used +/// by `MakeFunction`/`MakeClosure`. The cap is the total number of +/// `def`/`lambda`/comprehension function objects in the *whole module*, since +/// `FunctionId`s are allocated linearly across nested scopes. +fn check_function_count_u16(func_id: usize, position: CodeRange) -> Result { + u16::try_from(func_id).map_err(|_| too_many_functions(func_id, position)) +} + +#[cold] +#[inline(never)] +fn too_many_functions(func_id: usize, position: CodeRange) -> CompileError { + CompileError::new( + format!( + "module defines too many functions/lambdas ({}); maximum is {}", + func_id + 1, + u16::MAX + ), + position, + ) +} + +/// Converts a `StringId` (intern pool index) into the `u16` operand used by +/// every name-bearing opcode (`LoadAttr`, `StoreAttr`, `LoadGlobal`, +/// `CallFunctionKw` keyword names, etc.). Called inline at every emission +/// site — overflow only happens when the intern pool exceeded `u16::MAX` +/// during parse/prepare, so the error construction is `#[cold]` and the +/// success path inlines to a single `as u16`. +fn check_name_index_u16(name_id: StringId, position: CodeRange) -> Result { + u16::try_from(name_id.index()).map_err(|_| name_index_too_large(position)) +} + +#[cold] +#[inline(never)] +fn name_index_too_large(position: CodeRange) -> CompileError { + CompileError::new( + format!( + "module has too many distinct names; the bytecode format supports up to {} interned strings", + usize::from(u16::MAX) + 1, + ), + position, + ) +} + +/// Converts a call-related count (positional args, keyword args, defaults, +/// closure cells) into the `u8` operand used by the corresponding opcodes. +/// `kind` (e.g. "default parameter values") is interpolated into the error +/// message so the diagnostic identifies which kind of count overflowed. +fn check_call_args_u8(count: usize, kind: &'static str, position: CodeRange) -> Result { + u8::try_from(count).map_err(|_| too_many_call_args(count, kind, position)) +} + +#[cold] +#[inline(never)] +fn too_many_call_args(count: usize, kind: &'static str, position: CodeRange) -> CompileError { + CompileError::new(format!("more than {MAX_CALL_ARGS} {kind} ({count})"), position) +} + +/// Compiles prepared AST nodes to bytecode. +/// +/// The compiler traverses the AST and emits bytecode instructions using +/// `CodeBuilder`. It handles variable scoping, control flow, and expression +/// evaluation order following Python semantics. +/// +/// Functions are compiled recursively through [`CompileInterns`]. +/// Each function's body is compiled before registering it, so nested functions +/// receive lower IDs. Those IDs become MakeFunction/MakeClosure operands. +pub struct Compiler<'a, 'i> { + /// Current code being built. + pub(super) code: CodeBuilder, + + /// Compilation tables: private overlay for an existing session, direct insertion for a fresh program. + pub(super) interns: &'a mut CompileInterns<'i>, + + /// Enclosing control blocks whose cleanup is emitted by non-local exits. + /// This mirrors CPython's compiler `fblockinfo` stack and keeps each + /// `finally` body masked while its inline copy is compiled. + fblocks: Vec>, + + /// Number of `finally` body copies emitted into this code object. + finally_copies: u16, + + /// Whether the compiler is currently compiling module-level code. + /// + /// At module level, `Local` scope maps to global opcodes + /// (`LoadGlobal`/`StoreGlobal`/`DeleteGlobal`) because module locals live in the + /// globals array. In function bodies this is `false` and these scopes use local + /// opcodes that index into the stack. + is_module_scope: bool, + + /// Number of stack-resident locals in the running frame for this code object. + /// + /// - Function scope: equals the function's `namespace_size` (params + cells + + /// free vars + assigned locals). + /// - Module scope: `0` — module-level "locals" live in `self.globals`, so + /// nothing is stored in the frame's locals region. + frame_locals: u16, + + /// Compile-time storage state for active comprehension target slots. + /// + /// Slot IDs are unique among nested comprehensions and reused by siblings. + /// Each entry records whether the target is unbound, stack-backed, or + /// cell-backed, together with its absolute frame-stack offset. + comp_slots: Vec>, + + /// Settings for this scope and its nested compilers. + flags: ScopeFlags, +} + +/// Compiler settings inherited by nested scopes, with await restrictions reset for functions. +#[derive(Debug, Clone, Copy)] +struct ScopeFlags { + /// Whether to compile pytest-style assert failure annotations. + assert_message_annotations: bool, + /// Whether global-scope names compile to the `*Name` opcodes (with + /// `NAME_GLOBAL_ONLY`) because the running frame's globals are an explicit + /// `exec()` / `eval()` dict. + globals_by_name: bool, + /// Rejects `await` at snippet top level and in its class bodies. + /// Nested function bodies reset this restriction. + forbid_await: bool, +} + +/// Jump targets needed to compile `break` and `continue`. +struct LoopInfo { + /// Loop start and its stack depth, used by `continue`. + start: JumpTarget, + /// `break` jumps awaiting the loop's final target. + break_jumps: Vec, +} + +/// Exception-table ranges owned by one active control block. +/// +/// Inline cleanup interrupts only the exited region; enclosing regions remain +/// open so they can catch failures from inner cleanup code. +struct Region { + /// Completed sub-ranges, in emission order. + ranges: Vec<(Offset, Offset)>, + /// Start of the currently open sub-range; `None` while interrupted. + open_start: Option, + /// Operand-stack depth at region entry (`ExceptionEntry::stack_depth`). + stack_depth: u16, + /// Frame-relative `exception_stack` length at region entry + /// (`ExceptionEntry::exception_stack_count`). + exc_stack_count: u16, +} + +impl Region { + /// Opens a region starting at `start`. + fn open(start: Offset, stack_depth: u16, exc_stack_count: u16) -> Self { + Self { + ranges: Vec::new(), + open_start: Some(start), + stack_depth, + exc_stack_count, + } + } + + /// Closes the current sub-range at `at`; the region stays interrupted + /// until [`resume`](Self::resume). No-op if already interrupted. + fn interrupt(&mut self, at: Offset) { + if let Some(start) = self.open_start.take() + && start != at + { + self.ranges.push((start, at)); + } + } + + /// Re-opens the region at `at` after an interruption. + fn resume(&mut self, at: Offset) { + assert!( + self.open_start.is_none(), + "Region::resume on a region that is already open" + ); + self.open_start = Some(at); + } + + /// Emits each non-empty sub-range, in emission order, to `handler`. + /// Uninterrupted regions — all but those split by a non-local exit — emit + /// their single range without allocating. + fn add_entries( + mut self, + end: Offset, + code: &mut CodeBuilder, + handler: Offset, + kind: HandlerKind, + ) -> Result<(), CompileError> { + if self.ranges.is_empty() { + match self.open_start { + Some(start) if start != end => { + code.add_exception_entry(start, end, handler, self.stack_depth, self.exc_stack_count, kind) + } + _ => Ok(()), + } + } else { + self.interrupt(end); + for (start, end) in self.ranges { + code.add_exception_entry(start, end, handler, self.stack_depth, self.exc_stack_count, kind)?; + } + Ok(()) + } + } +} + +/// Enclosing construct whose cleanup runs for non-local control flow. +/// Mirrors CPython's `fblockinfo`; combined `try` forms use an outer +/// `FinallyTry` around their `try/except/else` body. +enum FBlock<'a> { + /// A `while` loop. No stack contribution. + WhileLoop(LoopInfo), + /// A `for` loop: the iterator sits on the operand stack and is popped + /// when `break`/`return` exits the loop. + ForLoop(LoopInfo), + /// The protected body of a `try` with handlers; exceptions route to the + /// handler-dispatch code. + TryExcept { region: Region }, + /// A protected `try/finally`; `finally` is emitted inline for each exit. + FinallyTry { + region: Region, + finally: &'a [PreparedNode], + }, + /// An `except` body, including cleanup for its active exception and target. + ExceptHandler { + name: Option<&'a Identifier>, + region: Region, + }, + /// An exception-path `finally` whose exception is swallowed on escape. + FinallyEnd, + /// A `with` body: the context manager sits on the operand stack and + /// `__exit__` is invoked when control exits the block. + With { region: Region }, + /// A return value to discard if control escapes an inline `finally`. + PopValue, +} + +impl<'a> FBlock<'a> { + /// The block's protected region, if it owns one. + fn region_mut(&mut self) -> Option<&mut Region> { + match self { + Self::TryExcept { region } + | Self::FinallyTry { region, .. } + | Self::ExceptHandler { region, .. } + | Self::With { region } => Some(region), + Self::WhileLoop(_) | Self::ForLoop(_) | Self::FinallyEnd | Self::PopValue => None, + } + } + + /// Extracts a `ForLoop` or panics on a compiler invariant bug. + fn expect_for_loop(self) -> LoopInfo { + match self { + Self::ForLoop(info) => info, + _ => panic!("expected a for-loop frame block"), + } + } + + /// Extracts a `WhileLoop` or panics on a compiler invariant bug. + fn expect_while_loop(self) -> LoopInfo { + match self { + Self::WhileLoop(info) => info, + _ => panic!("expected a while-loop frame block"), + } + } + + /// Extracts a `TryExcept` region or panics on a compiler invariant bug. + fn expect_try_except(self) -> Region { + match self { + Self::TryExcept { region } => region, + _ => panic!("expected a try/except frame block"), + } + } + + /// Extracts a `FinallyTry` region or panics on a compiler invariant bug. + fn expect_finally_try(self) -> Region { + match self { + Self::FinallyTry { region, .. } => region, + _ => panic!("expected a try/finally frame block"), + } + } + + /// Extracts an `ExceptHandler` block or panics on an invariant bug. + fn expect_except_handler(self) -> (Option<&'a Identifier>, Region) { + match self { + Self::ExceptHandler { name, region } => (name, region), + _ => panic!("expected an except-handler frame block"), + } + } + + /// Extracts a `With` region or panics on a compiler invariant bug. + fn expect_with(self) -> Region { + match self { + Self::With { region } => region, + _ => panic!("expected a with frame block"), + } + } + + /// Verifies that this is an exception-path `finally` block. + fn expect_finally_end(self) { + assert!(matches!(self, Self::FinallyEnd), "expected a finally-end frame block"); + } + + /// Verifies that this is a pending-return-value block. + fn expect_pop_value(self) { + assert!(matches!(self, Self::PopValue), "expected a pending-value frame block"); + } +} + +/// Simulated operand while compiling nested comprehension targets. +/// Tracking is required because `LiftToTop` reorders values before their final +/// stack offsets are known. +enum SimItem<'a> { + /// A finalized target awaiting its absolute stack offset. + Leaf(u16), + /// A value awaiting its next unpack or lift operation. + Pending(&'a UnpackTarget), +} + +/// Storage selected for an active comprehension target. +#[derive(Clone, Copy)] +enum CompSlot { + /// A captured target whose stable cell has not been assigned yet. + UnboundCell(u16), + /// An uncaptured target stored directly at this frame-stack offset. + Value(u16), + /// A captured target stored in the cell at this frame-stack offset. + Cell(u16), +} + +impl<'a, 'i> Compiler<'a, 'i> { + /// Creates a compiler for a module or function. + /// `frame_locals` is zero at module scope or the function namespace size; + /// comprehension slots follow it on the operand stack. + fn new(interns: &'a mut CompileInterns<'i>, is_module_scope: bool, frame_locals: u16, flags: ScopeFlags) -> Self { + let mut code = CodeBuilder::new(); + code.new_code_region(0); + Self { + code, + interns, + fblocks: Vec::new(), + finally_copies: 0, + is_module_scope, + frame_locals, + comp_slots: Vec::new(), + flags, + } + } + + /// Compiles module-level statements, returning the last expression or None. + /// On failure the caller discards the overlay, or the whole interner in direct mode. + pub fn compile_module( + nodes: &[PreparedNode], + interns: &mut CompileInterns<'_>, + globals: &NameMap, + options: CompileOptions, + ) -> Result { + Self::compile_module_inner(nodes, interns, globals, options, None) + } + + /// Compiles a prepared `eval()` / `exec()` snippet, rejecting top-level await. + /// `globals_by_name` selects name lookups for an explicit globals dict. + /// The caller must discard the private intern overlay on failure. + pub(crate) fn compile_snippet( + nodes: &[PreparedNode], + interns: &mut CompileInterns<'_>, + globals: &NameMap, + options: CompileOptions, + globals_by_name: bool, + ) -> Result { + Self::compile_module_inner(nodes, interns, globals, options, Some(globals_by_name)) + } + + /// Shared module compiler; `snippet` is `Some(globals_by_name)` for eval/exec. + fn compile_module_inner( + nodes: &[PreparedNode], + interns: &mut CompileInterns<'_>, + globals: &NameMap, + options: CompileOptions, + snippet: Option, + ) -> Result { + check_namespace_size_u16(globals.len(), "module")?; + // Module frames have `locals_count = 0` at runtime (globals live in + // `self.globals`), so comp-var offsets are emitted as plain operand- + // stack indices. + let flags = ScopeFlags { + assert_message_annotations: options.assert_message_annotations.enabled(), + globals_by_name: snippet.unwrap_or(false), + forbid_await: snippet.is_some(), + }; + let mut compiler = Compiler::new(interns, true, 0, flags); + + // All globals are "local names" in the module + compiler.code.register_local_names(globals.names()); + + compiler.compile_block(nodes)?; + + // Module returns None if no explicit return + compiler.code.emit(Opcode::LoadNone)?; + compiler.code.emit(Opcode::ReturnValue)?; + + Ok(compiler.code.build()) + } + + /// Compiles a function body to bytecode, appending any nested functions to `interns`. + /// + /// Used internally when compiling function definitions. The function body is + /// compiled to bytecode with an implicit `return None` at the end if there's + /// no explicit return statement. + fn compile_function_body( + func_def: &PreparedFunctionDef, + interns: &mut CompileInterns<'_>, + num_locals: u16, + flags: ScopeFlags, + ) -> Result { + // Function frames have `locals_count = num_locals` at runtime, so + // comp-var load/store opcodes use `num_locals + offset` to skip past + // the locals region into the operand-stack region. + let flags = ScopeFlags { + forbid_await: false, + ..flags + }; + let mut compiler = Compiler::new(interns, false, num_locals, flags); + // Parameters, and the cells captured parameters live in, are named up + // front: a body that never mentions one still reports it from `locals()`. + let param_names: Vec = func_def.signature.param_names().collect(); + compiler.code.register_local_names(¶m_names); + for (cell_slot, param_index) in func_def.cell_var_slots.iter().zip(&func_def.cell_param_indices) { + if let Some(name) = param_index.and_then(|index| param_names.get(index)) { + compiler.code.register_local_name(cell_slot.as_u16(), *name); + } + } + // A captured cell is a local even if this body only passes it to another closure. + for (slot, name) in func_def.free_var_slots.iter().zip(&func_def.free_var_names) { + compiler.code.register_local_name(slot.as_u16(), *name); + } + compiler.compile_block(&func_def.body)?; + + // Implicit return None if no explicit return + compiler.code.emit(Opcode::LoadNone)?; + compiler.code.emit(Opcode::ReturnValue)?; + + Ok(compiler.code.build()) + } + + /// Compiles statements, retaining `finally` bodies for inline cleanup. + pub(super) fn compile_block(&mut self, nodes: &'a [PreparedNode]) -> Result<(), CompileError> { + for node in nodes { + if self.code.is_dead() { + // Don't bother compiling dead code + break; + } + self.compile_stmt(node)?; + } + Ok(()) + } + + // ======================================================================== + // Statement Compilation + // ======================================================================== + + /// Compiles a single statement. + fn compile_stmt(&mut self, node: &'a PreparedNode) -> Result<(), CompileError> { + // Node is an alias, use qualified path for matching + match node { + Node::Expr(expr) => { + self.compile_expr(expr)?; + self.code.emit(Opcode::Pop)?; // Discard result + } + Node::Return(expr) => { + self.compile_return(expr.as_ref())?; + } + Node::Assign { target, object } => { + self.compile_expr(object)?; + self.compile_store(target)?; + } + Node::UnpackAssign { + targets, + targets_position, + object, + } => { + self.compile_expr(object)?; + self.emit_unpack_store(targets, *targets_position)?; + } + Node::OpAssign { target, op, value } => { + let Some(opcode) = operator_to_inplace_opcode(op) else { + return Err(CompileError::new( + "matrix multiplication augmented assignment (@=) is not yet supported", + target.position, + )); + }; + self.compile_name(target)?; + self.compile_expr(value)?; + self.code.emit(opcode)?; + self.compile_store(target)?; + } + Node::SubscriptOpAssign { + target, + index, + op, + value, + target_position, + } => { + let Some(opcode) = operator_to_inplace_opcode(op) else { + return Err(CompileError::new( + "matrix multiplication augmented assignment (@=) is not yet supported", + *target_position, + )); + }; + self.compile_expr(target)?; + self.compile_expr(index)?; + self.code.emit(Opcode::Dup2)?; + self.code.set_location(*target_position, None); + self.code.emit(Opcode::BinarySubscr)?; + self.compile_expr(value)?; + self.code.emit(opcode)?; + self.code.emit(Opcode::Rot3)?; + self.code.set_location(*target_position, None); + self.code.emit(Opcode::StoreSubscr)?; + } + Node::SubscriptAssign { + target, + index, + value, + target_position, + } => { + self.compile_expr(value)?; + self.emit_subscript_store(target, index, *target_position)?; + } + Node::AttrOpAssign { + object, + attr, + op, + value, + target_position, + } => { + let Some(opcode) = operator_to_inplace_opcode(op) else { + return Err(CompileError::new( + "matrix multiplication augmented assignment (@=) is not yet supported", + *target_position, + )); + }; + let name_id = attr.string_id().expect("LoadAttr requires interned attr name"); + let name_idx = check_name_index_u16(name_id, *target_position)?; + // Stack: compile object, dup for later store, load attr, apply op, rotate, store + self.compile_expr(object)?; // [obj] + self.code.emit(Opcode::Dup)?; // [obj, obj] + self.code.set_location(*target_position, None); + self.code.emit_u16(Opcode::LoadAttr, name_idx)?; // [obj, attr_val] + self.compile_expr(value)?; // [obj, attr_val, rhs] + self.code.emit(opcode)?; // [obj, result] + self.code.emit(Opcode::Rot2)?; // [result, obj] + self.code.set_location(*target_position, None); + self.code.emit_u16(Opcode::StoreAttr, name_idx)?; // [] + } + Node::AttrAssign { + object, + attr, + target_position, + value, + } => { + self.compile_expr(value)?; + self.emit_attr_store(object, attr, *target_position)?; + } + Node::ChainAssign { targets, object } => { + // Python evaluates the RHS once, then assigns to each target in + // left-to-right source order. We materialise the value on the stack + // and, for every target except the last, emit `Dup` to keep a copy + // underneath the target-specific store logic. The final target + // consumes the remaining copy, leaving the stack balanced. + self.compile_expr(object)?; + let (last, rest) = targets.split_last().expect("chained assignment has targets"); + for target in rest { + self.code.emit(Opcode::Dup)?; + self.compile_assign_target(target)?; + } + self.compile_assign_target(last)?; + } + Node::If { test, body, or_else } => self.compile_if(test, body, or_else)?, + Node::For { + target, + iter, + body, + or_else, + } => self.compile_for(target, iter, body, or_else)?, + Node::While { test, body, or_else } => self.compile_while(test, body, or_else)?, + Node::Assert { test, msg } => self.compile_assert(test, msg.as_ref())?, + Node::Raise(expr) => { + if let Some(exc) = expr { + self.compile_expr(exc)?; + self.code.emit(Opcode::Raise)?; + } else { + self.code.emit(Opcode::Reraise)?; + } + } + Node::FunctionDef { def, decorators } => self.compile_function_def(def, decorators)?, + Node::ClassDef { + name, + body, + members, + decorators, + position, + } => self.compile_class_def(name, body, members, decorators, *position)?, + Node::Try(try_block) => self.compile_try(try_block)?, + Node::Match { + subject, + cases, + position, + } => self.compile_match(subject, cases, *position)?, + Node::With { + context, target, body, .. + } => self.compile_with(context, target.as_ref(), body)?, + Node::Import { names } => { + for import_name in names { + self.compile_import(import_name)?; + } + } + Node::ImportFrom { + module_name, + submodules, + names, + position, + } => self.compile_import_from(*module_name, submodules, names, *position)?, + Node::Break { position } => self.compile_break(*position)?, + Node::Continue { position } => self.compile_continue(*position)?, + // These are handled during the prepare phase and produce no bytecode + Node::Pass | Node::Global { .. } | Node::Nonlocal { .. } => {} + } + Ok(()) + } + + /// Compiles a function definition. + /// + /// This involves: + /// 1. Recursively compiling the function body to bytecode + /// 2. Creating a Function struct with the compiled Code + /// 3. Adding the Function to the session's intern table + /// 4. Emitting bytecode to evaluate defaults and create the function at runtime + fn compile_function_def( + &mut self, + func_def: &PreparedFunctionDef, + decorators: &[ExprLoc], + ) -> Result<(), CompileError> { + // Pushed in source order so they sit below the function value: the + // applying calls below then run bottom-up, like CPython's `f = deco(f)`. + for decorator in decorators { + self.compile_expr(decorator)?; + } + // Build the function object on the stack... + self.emit_make_function(func_def, "function")?; + // ...then apply each decorator, reversed so the bottom-most (last pushed) + // applies first, each located at its own decorator so a traceback pins the + // one that raised. + for decorator in decorators.iter().rev() { + self.code.set_location(decorator.position, None); + self.code.emit_u8(Opcode::CallFunction, 1)?; + } + // ...and bind the (possibly decorated) function to its name slot. + self.compile_store(&func_def.name)?; + Ok(()) + } + + /// Compiles a lambda expression. + /// + /// This is similar to `compile_function_def` but does NOT store the function + /// to a name slot — it stays on the stack as the expression result. The + /// lambda's `PreparedFunctionDef` already has `` as its name. + fn compile_lambda(&mut self, func_def: &PreparedFunctionDef) -> Result<(), CompileError> { + self.emit_make_function(func_def, "lambda") + } + + /// Compiles a function body and emits the bytecode that builds the runtime + /// function/closure object, leaving it on the operand stack. + /// + /// Shared by `def` definitions, lambdas, and class methods. The caller decides + /// what to do with the resulting value: store it to a name + /// ([`compile_function_def`](Self::compile_function_def)), leave it as an + /// expression result ([`compile_lambda`](Self::compile_lambda)), or fold it + /// into a class namespace ([`compile_class_def`](Self::compile_class_def)). + /// + /// `what` labels the construct ("function"/"lambda"/"method") for the + /// namespace-size error message. Net stack effect is `+1`: even when free + /// variables are captured, the pushed cells are consumed by `MakeClosure`. + fn emit_make_function(&mut self, func_def: &PreparedFunctionDef, what: &'static str) -> Result<(), CompileError> { + let flags = self.flags; + self.emit_make_callable(func_def, what, |interns, namespace_size| { + Self::compile_function_body(func_def, interns, namespace_size, flags) + }) + } + + /// Shared core of [`emit_make_function`](Self::emit_make_function) and + /// [`emit_make_class_body`](Self::emit_make_class_body): compiles a callable's + /// body via `compile_body`, registers the resulting [`Function`], pushes its + /// default values, and emits `MakeFunction`/`MakeClosure`, leaving the + /// function/closure value on the operand stack (net stack effect `+1`). + /// + /// `compile_body` is the only thing that varies: ordinary functions/lambdas + /// use [`compile_function_body`](Self::compile_function_body) (implicit + /// `return None` tail), while a class body uses + /// [`compile_class_body`](Self::compile_class_body) (assemble-namespace + + /// return-class tail). It receives the intern tables (nested functions are + /// appended to them first, so they get lower ids) and this body's namespace + /// size; it returns the compiled body code. + fn emit_make_callable( + &mut self, + func_def: &PreparedFunctionDef, + what: &'static str, + compile_body: impl FnOnce(&mut CompileInterns<'_>, u16) -> Result, + ) -> Result<(), CompileError> { + let func_pos = func_def.name.position; + + // Bound the bytecode-operand counts before compiling — the `u8` casts + // below depend on these fitting in 255. + let defaults_count = check_call_args_u8(func_def.default_exprs.len(), "default parameter values", func_pos)?; + let cell_count = check_call_args_u8(func_def.free_var_enclosing_slots.len(), "closure variables", func_pos)?; + + // 1. Compile the body recursively. + let namespace_size = check_namespace_size_u16(func_def.namespace_size, what)?; + let body_code = compile_body(self.interns, namespace_size)?; + + // 2. Create the compiled Function and add it to the table + // `Function` retains the legacy numeric source metadata for serialized-code + // compatibility, although closure construction is fully emitted here. + let enclosing_slot_metadata = func_def + .free_var_enclosing_slots + .iter() + .map(|source| match source { + CaptureSource::Namespace(slot) => *slot, + CaptureSource::CompVar(slot) => { + NamespaceId::new(usize::from(*slot)).expect("comp-var slot fits in NamespaceId") + } + }) + .collect(); + let function = Function::new( + func_def.name, + func_def.signature.clone(), + func_def.namespace_size, + enclosing_slot_metadata, + func_def.free_var_slots.clone(), + func_def.cell_var_slots.clone(), + func_def.cell_param_indices.clone(), + func_def.default_exprs.len(), + func_def.is_async, + body_code, + ); + let func_id = self.interns.push_function(function); + + // 3. Compile and push default values (evaluated at definition time) + for default_expr in &func_def.default_exprs { + self.compile_expr(default_expr)?; + } + let func_id_u16 = check_function_count_u16(func_id, func_pos)?; + + // 4. Emit MakeFunction or MakeClosure (if has free vars) + if func_def.free_var_enclosing_slots.is_empty() { + // MakeFunction: func_id (u16) + defaults_count (u8) + self.code + .emit_u16_u8(Opcode::MakeFunction, func_id_u16, defaults_count)?; + } else { + // Push captured cells from enclosing scope. + for source in &func_def.free_var_enclosing_slots { + let slot = match source { + CaptureSource::Namespace(slot) => slot.as_u16(), + CaptureSource::CompVar(slot) => match self.comp_slots.get(usize::from(*slot)).copied().flatten() { + Some(CompSlot::UnboundCell(offset) | CompSlot::Cell(offset)) => offset, + Some(CompSlot::Value(_)) | None => { + panic!("captured comprehension cell must be active while building closure") + } + }, + }; + self.code.emit_load_local(slot)?; + } + // MakeClosure: func_id (u16) + defaults_count (u8) + cell_count (u8) + self.code + .emit_u16_u8_u8(Opcode::MakeClosure, func_id_u16, defaults_count, cell_count)?; + } + + Ok(()) + } + + /// Compiles a `class Foo: ...` definition. + /// + /// Modelled on CPython's class-body code object: the class body is compiled + /// to a synthetic zero-arg function (via + /// [`emit_make_class_body`](Self::emit_make_class_body)) that runs the class + /// statements in its own scope and returns the assembled `Class`. We emit + /// that function value, call it with zero args, and bind the result to the + /// class name. + fn compile_class_def( + &mut self, + name: &Identifier, + body: &PreparedFunctionDef, + members: &[Identifier], + decorators: &[ExprLoc], + position: CodeRange, + ) -> Result<(), CompileError> { + // Pushed in source order so they sit below the class value: the applying + // calls below then run bottom-up, like CPython's `cls = deco(cls)`. + for decorator in decorators { + self.compile_expr(decorator)?; + } + // Build the class-body function/closure value on the stack... + self.emit_make_class_body(body, members, name, position)?; + // ...call it with zero args — it runs the body and returns the `Class`. + // Record the class statement as the call site so a traceback from inside + // the class body attributes this frame to the `class` statement (like + // CPython) rather than falling back to `CodeRange::default()`. + self.code.set_location(position, None); + self.code.emit_u8(Opcode::CallFunction, 0)?; + // Each call consumes the callable below the current value: `deco(value)`. + // Reversed so the bottom-most (last pushed) applies first, and located at + // its own decorator so a traceback pins the one that raised, like CPython. + for decorator in decorators.iter().rev() { + self.code.set_location(decorator.position, None); + self.code.emit_u8(Opcode::CallFunction, 1)?; + } + // ...and bind the (possibly decorated) class object to the name's slot. + self.compile_store(name)?; + Ok(()) + } + + /// Emits the class-body function value (a `MakeFunction`/`MakeClosure`), + /// leaving it on the operand stack (net stack effect `+1`). + /// + /// Sibling of [`emit_make_function`](Self::emit_make_function): identical + /// closure/cell handling, but compiles the body with + /// [`compile_class_body`](Self::compile_class_body) so the emitted code ends + /// by assembling the namespace and returning the `Class`. + fn emit_make_class_body( + &mut self, + body: &PreparedFunctionDef, + members: &[Identifier], + class_name: &Identifier, + position: CodeRange, + ) -> Result<(), CompileError> { + let flags = self.flags; + self.emit_make_callable(body, "class body", |interns, namespace_size| { + Self::compile_class_body( + &body.body, + members, + class_name, + position, + interns, + namespace_size, + flags, + ) + }) + } + + /// Compiles a class body, mirroring + /// [`compile_function_body`](Self::compile_function_body) but replacing the + /// implicit `LoadNone; ReturnValue` tail with a `type(name, (), {...})` + /// call: push the class name and an empty bases tuple, then for each + /// member (in source order) push `LoadConst ` and the member's value + /// from its class-body slot, build the namespace dict, and call the 3-arg + /// `type()` builtin (which builds the `Class`), then `ReturnValue`. + /// + /// Members are plain locals (the prepare phase forces class-body locals to + /// never be cells — see `prepare_class_def`), so [`compile_name`](Self::compile_name) + /// emits `LoadLocal`; it would transparently emit `LoadCell` if that ever + /// changed, so no assumption is hard-coded here. + fn compile_class_body( + body: &[PreparedNode], + members: &[Identifier], + class_name: &Identifier, + position: CodeRange, + interns: &mut CompileInterns<'_>, + num_locals: u16, + flags: ScopeFlags, + ) -> Result { + let mut compiler = Compiler::new(interns, false, num_locals, flags); + compiler.compile_block(body)?; + + // Assembly errors (e.g. resource limits while building the dict) + // should point at the class statement, not the last member's line. + compiler.code.set_location(position, None); + + // type(name, (), {members...}): push the name and empty bases tuple... + let class_name_const = compiler.code.add_const(Value::InternString(class_name.name_id))?; + compiler.code.emit_u16(Opcode::LoadConst, class_name_const)?; + compiler.code.emit_u16(Opcode::BuildTuple, 0)?; + + // ...then the namespace dict: (name, value) for each member in order. + for member in members { + let name_const = compiler.code.add_const(Value::InternString(member.name_id))?; + compiler.code.emit_u16(Opcode::LoadConst, name_const)?; + compiler.compile_name(member)?; + } + let member_count = check_collection_size_u16(members.len(), position)?; + compiler.code.emit_u16(Opcode::BuildDict, member_count)?; + + // ...and call the 3-arg type() builtin, which builds the class object. + compiler + .code + .emit_call_builtin_function(BuiltinsFunctions::Type as u8, 3)?; + compiler.code.emit(Opcode::ReturnValue)?; + + Ok(compiler.code.build()) + } + + /// Compiles an import, resolving the module only when execution reaches it. + /// Resolves every dotted component; binds the last if aliased, otherwise the top-level module. + fn compile_import(&mut self, import: &ImportName) -> Result<(), CompileError> { + let position = import.binding.position; + self.code.set_location(position, None); + self.code + .emit_u16(Opcode::LoadModule, check_name_index_u16(import.module_name, position)?)?; + if import.binds_top_level { + self.code.emit(Opcode::Dup)?; + } + self.compile_submodules(&import.submodules, position)?; + if import.binds_top_level { + self.code.emit(Opcode::Pop)?; + } + self.compile_store(&import.binding) + } + + /// Replaces the stack top with each successive submodule of a dotted import. + fn compile_submodules(&mut self, submodules: &[Submodule], position: CodeRange) -> Result<(), CompileError> { + for submodule in submodules { + let name_idx = check_name_index_u16(submodule.name, position)?; + let path_idx = check_name_index_u16(submodule.path, position)?; + self.code.emit_u16_u16(Opcode::LoadSubmodule, name_idx, path_idx)?; + } + Ok(()) + } + + /// Creates the module once, then loads and binds each imported attribute. + /// Missing modules and attributes raise only when execution reaches the import. + fn compile_import_from( + &mut self, + module_name: StringId, + submodules: &[Submodule], + names: &[(StringId, Identifier)], + position: CodeRange, + ) -> Result<(), CompileError> { + self.code.set_location(position, None); + let module_idx = check_name_index_u16(module_name, position)?; + self.code.emit_u16(Opcode::LoadModule, module_idx)?; + self.compile_submodules(submodules, position)?; + for (i, (import_name, binding)) in names.iter().enumerate() { + // Preserve the module for subsequent attributes; the last load consumes it. + if i < names.len() - 1 { + self.code.emit(Opcode::Dup)?; + } + let name_idx = check_name_index_u16(*import_name, position)?; + // LoadModule or the last LoadSubmodule saved the error's module name on the frame. + self.code.emit_u16(Opcode::LoadAttrImport, name_idx)?; + self.compile_store(binding)?; + } + Ok(()) + } + + // ======================================================================== + // Expression Compilation + // ======================================================================== + + /// Compiles an expression, leaving its value on the stack. + pub(super) fn compile_expr(&mut self, expr_loc: &ExprLoc) -> Result<(), CompileError> { + // Set source location for traceback info + self.code.set_location(expr_loc.position, None); + + match &expr_loc.expr { + Expr::Literal(lit) => self.compile_literal(lit)?, + + Expr::Name(ident) => self.compile_name(ident)?, + + Expr::Builtin(builtin) => { + let idx = self.code.add_const(Value::Builtin(*builtin))?; + self.code.emit_u16(Opcode::LoadConst, idx)?; + } + + Expr::Op { left, op, right } => { + self.compile_binary_op(left, op, right, expr_loc.position)?; + } + + Expr::CmpOp { left, op, right } => { + self.compile_expr(left)?; + self.compile_expr(right)?; + // Restore the full comparison expression's position for traceback caret range + self.code.set_location(expr_loc.position, None); + self.code.emit(cmp_operator_to_opcode(*op))?; + } + + Expr::ChainCmp { left, comparisons } => { + self.compile_chain_comparison(left, comparisons, expr_loc.position)?; + } + + Expr::Not(operand) => { + self.compile_expr(operand)?; + // Restore the full expression's position for traceback caret range + self.code.set_location(expr_loc.position, None); + self.code.emit(Opcode::UnaryNot)?; + } + + Expr::UnaryMinus(operand) => { + self.compile_expr(operand)?; + // Restore the full expression's position for traceback caret range + self.code.set_location(expr_loc.position, None); + self.code.emit(Opcode::UnaryNeg)?; + } + + Expr::UnaryPlus(operand) => { + self.compile_expr(operand)?; + // Restore the full expression's position for traceback caret range + self.code.set_location(expr_loc.position, None); + self.code.emit(Opcode::UnaryPos)?; + } + + Expr::UnaryInvert(operand) => { + self.compile_expr(operand)?; + // Restore the full expression's position for traceback caret range + self.code.set_location(expr_loc.position, None); + self.code.emit(Opcode::UnaryInvert)?; + } + + Expr::List(elements) => { + if has_unpack_seq(elements) { + // Generalized path: build incrementally for PEP 448 *unpacks + self.code.emit_u16(Opcode::BuildList, 0)?; + for item in elements { + match item { + SequenceItem::Value(e) => { + self.compile_expr(e)?; + self.code.emit_u8(Opcode::ListAppend, 0)?; + } + SequenceItem::Unpack(e) => { + self.compile_expr(e)?; + self.code.emit(Opcode::ListExtend)?; + } + } + } + } else { + // Fast path: all values, single BuildList. + // SAFETY: has_unpack_seq(elements) is false, so every item is Value. + for item in elements { + let SequenceItem::Value(e) = item else { + unreachable!("list fast path: only Value items") + }; + self.compile_expr(e)?; + } + let count = check_collection_size_u16(elements.len(), expr_loc.position)?; + self.code.emit_u16(Opcode::BuildList, count)?; + } + } + + Expr::Tuple(elements) => { + if has_unpack_seq(elements) { + // Generalized path: build via list then convert for PEP 448 *unpacks + self.code.emit_u16(Opcode::BuildList, 0)?; + for item in elements { + match item { + SequenceItem::Value(e) => { + self.compile_expr(e)?; + self.code.emit_u8(Opcode::ListAppend, 0)?; + } + SequenceItem::Unpack(e) => { + self.compile_expr(e)?; + self.code.emit(Opcode::ListExtend)?; + } + } + } + self.code.emit(Opcode::ListToTuple)?; + } else { + // Fast path: all values, single BuildTuple. + // SAFETY: has_unpack_seq(elements) is false, so every item is Value. + for item in elements { + let SequenceItem::Value(e) = item else { + unreachable!("tuple fast path: only Value items") + }; + self.compile_expr(e)?; + } + let count = check_collection_size_u16(elements.len(), expr_loc.position)?; + self.code.emit_u16(Opcode::BuildTuple, count)?; + } + } + + Expr::Dict(dict_items) => { + if has_unpack_dict(dict_items) { + // Generalized path: build incrementally for PEP 448 **unpacks + self.code.emit_u16(Opcode::BuildDict, 0)?; + for item in dict_items { + match item { + DictItem::Pair(key, value) => { + self.compile_expr(key)?; + self.compile_expr(value)?; + // depth=0: dict is at TOS after key/value are popped + self.code.emit_u8(Opcode::DictSetItem, 0)?; + } + DictItem::Unpack(e) => { + self.compile_expr(e)?; + // depth=0: dict is directly below mapping on stack + self.code.emit_u8(Opcode::DictUpdate, 0)?; + } + } + } + } else { + // Fast path: all pairs, single BuildDict. + // SAFETY: has_unpack_dict(dict_items) is false, so every item is Pair. + for item in dict_items { + let DictItem::Pair(key, value) = item else { + unreachable!("dict fast path: only Pair items") + }; + self.compile_expr(key)?; + self.compile_expr(value)?; + } + let count = check_collection_size_u16(dict_items.len(), expr_loc.position)?; + self.code.emit_u16(Opcode::BuildDict, count)?; + } + } + + Expr::Set(elements) => { + if has_unpack_seq(elements) { + // Generalized path: build incrementally for PEP 448 *unpacks + self.code.emit_u16(Opcode::BuildSet, 0)?; + for item in elements { + match item { + SequenceItem::Value(e) => { + self.compile_expr(e)?; + self.code.emit_u8(Opcode::SetAdd, 0)?; + } + SequenceItem::Unpack(e) => { + self.compile_expr(e)?; + self.code.emit_u8(Opcode::SetExtend, 0)?; + } + } + } + } else { + // Fast path: all values, single BuildSet. + // SAFETY: has_unpack_seq(elements) is false, so every item is Value. + for item in elements { + let SequenceItem::Value(e) = item else { + unreachable!("set fast path: only Value items") + }; + self.compile_expr(e)?; + } + let count = check_collection_size_u16(elements.len(), expr_loc.position)?; + self.code.emit_u16(Opcode::BuildSet, count)?; + } + } + + Expr::Subscript { object, index } => { + self.compile_expr(object)?; + self.compile_expr(index)?; + // Restore the full subscript expression's position for traceback + self.code.set_location(expr_loc.position, None); + self.code.emit(Opcode::BinarySubscr)?; + } + + Expr::IfElse { test, body, orelse } => { + self.compile_if_else_expr(test, body, orelse)?; + } + + Expr::AttrGet { object, attr } => { + self.compile_expr(object)?; + // Restore the full expression's position for traceback caret range + self.code.set_location(expr_loc.position, None); + let name_id = attr.string_id().expect("LoadAttr requires interned attr name"); + let name_idx = check_name_index_u16(name_id, expr_loc.position)?; + self.code.emit_u16(Opcode::LoadAttr, name_idx)?; + } + + Expr::Call { callable, args } => { + self.compile_call(callable, args, expr_loc.position)?; + } + + Expr::AttrCall { object, attr, args } => { + // Compile the object (will be on the stack) + self.compile_expr(object)?; + + // Compile the attribute call arguments and emit CallAttr + self.compile_method_call(attr, args, expr_loc.position)?; + } + + Expr::IndirectCall { callable, args } => { + // Compile the callable expression (e.g., a lambda) + self.compile_expr(callable)?; + + // Compile arguments and emit the call + self.compile_call_args(args, expr_loc.position)?; + } + + Expr::FString(parts) => { + // Compile each part and build the f-string + let part_count = self.compile_fstring_parts(parts)?; + self.code.emit_u16(Opcode::BuildFString, part_count)?; + } + + Expr::ListComp { + elt, + generators, + captured_slots, + } => { + self.compile_list_comp(elt, generators, captured_slots)?; + } + + Expr::SetComp { + elt, + generators, + captured_slots, + } => { + self.compile_set_comp(elt, generators, captured_slots)?; + } + + Expr::DictComp { + key, + value, + generators, + captured_slots, + } => { + self.compile_dict_comp(key, value, generators, captured_slots)?; + } + + Expr::Lambda { func_def } => { + self.compile_lambda(func_def)?; + } + + Expr::LambdaRaw { .. } => { + // LambdaRaw should be converted to Lambda during prepare phase + unreachable!("Expr::LambdaRaw should not exist after prepare phase") + } + + Expr::Await(value) => { + if self.flags.forbid_await { + return Err(CompileError::new("'await' outside function", expr_loc.position)); + } + // Await expressions: compile the inner expression, then emit Await + // Await handles ExternalFuture, Coroutine, and GatherFuture + self.compile_expr(value)?; + // Restore the full expression's position for traceback caret range + self.code.set_location(expr_loc.position, None); + self.code.emit(Opcode::Await)?; + } + + Expr::Slice { lower, upper, step } => { + // Compile slice components: start, stop, step (push None for missing) + if let Some(lower) = lower { + self.compile_expr(lower)?; + } else { + self.code.emit(Opcode::LoadNone)?; + } + if let Some(upper) = upper { + self.compile_expr(upper)?; + } else { + self.code.emit(Opcode::LoadNone)?; + } + if let Some(step) = step { + self.compile_expr(step)?; + } else { + self.code.emit(Opcode::LoadNone)?; + } + self.code.emit(Opcode::BuildSlice)?; + } + + Expr::Named { target, value } => { + // Compile the value expression (leaves result on stack) + self.compile_expr(value)?; + // Duplicate so value remains after store + self.code.emit(Opcode::Dup)?; + // Store to target (pops one copy) + self.compile_store(target)?; + } + } + Ok(()) + } + + // ======================================================================== + // Literal Compilation + // ======================================================================== + + /// Compiles a literal value. + /// + /// This is where parse-time literals cross into runtime `Value`s: a few + /// have a dedicated opcode, a complex literal is built by a constructor + /// call, and everything else is loaded from the constant pool. + fn compile_literal(&mut self, literal: &Literal) -> Result<(), CompileError> { + let value = match literal { + Literal::None => return self.code.emit(Opcode::LoadNone), + Literal::Bool(true) => return self.code.emit(Opcode::LoadTrue), + Literal::Bool(false) => return self.code.emit(Opcode::LoadFalse), + Literal::Int(n) if let Ok(small) = i8::try_from(*n) => { + return self.code.emit_i8(Opcode::LoadSmallInt, small); + } + // `Xj` is `complex(0.0, X)`: a complex value lives on the heap, so it + // is built by a constructor call rather than loaded from the pool. + Literal::Complex(imag) => { + for part in [0.0, *imag] { + let idx = self.code.add_const(Value::Float(part))?; + self.code.emit_u16(Opcode::LoadConst, idx)?; + } + let type_id = Type::Complex + .callable_to_u8() + .expect("complex is a callable builtin type"); + return self.code.emit_call_builtin_type(type_id, 2); + } + Literal::Ellipsis => Value::Ellipsis, + Literal::Int(n) => Value::Int(*n), + Literal::Float(v) => Value::Float(*v), + Literal::Str(string_id) => Value::InternString(*string_id), + Literal::Bytes(bytes_id) => Value::InternBytes(*bytes_id), + Literal::LongInt(long_int_id) => Value::InternLongInt(*long_int_id), + Literal::Marker(marker) => Value::Marker(*marker), + }; + let idx = self.code.add_const(value)?; + self.code.emit_u16(Opcode::LoadConst, idx) + } + + // ======================================================================== + // Variable Operations + // ======================================================================== + + /// Compiles loading a variable onto the stack. + /// + /// At module level, `Local` scopes emits global opcodes + /// because module-level locals live in the globals array. + fn compile_name(&mut self, ident: &Identifier) -> Result<(), CompileError> { + let slot = ident.namespace_id().as_u16(); + match ident.scope { + NameScope::Local => { + // True local - register name and mark as assigned for UnboundLocalError + self.code.register_local_name(slot, ident.name_id); + if self.is_module_scope { + self.code.emit_u16(Opcode::LoadGlobal, slot) + } else { + self.code.emit_load_local(slot) + } + } + NameScope::Global if self.flags.globals_by_name => { + self.code + .emit_name_op(Opcode::LoadName, slot, ident.name_id, NAME_GLOBAL_ONLY) + } + NameScope::Global => { + // Global name - only a "local" name at module scope + if self.is_module_scope { + self.code.register_local_name(slot, ident.name_id); + } + self.code.emit_u16(Opcode::LoadGlobal, slot) + } + NameScope::Name => { + self.code.register_local_name(slot, ident.name_id); + self.code.emit_name_op(Opcode::LoadName, slot, ident.name_id, 0) + } + NameScope::Cell => { + // Register the name for NameError messages (unbound free variable) + self.code.register_local_name(slot, ident.name_id); + // Emit local slot index — the VM reads the cell HeapId from the stack + self.code.emit_u16(Opcode::LoadCell, slot) + } + NameScope::CompVar => match self.comp_slots.get(usize::from(slot)).copied().flatten() { + Some(CompSlot::Value(offset)) => self.code.emit_load_local(offset), + Some(CompSlot::Cell(offset)) => self.code.emit_u16(Opcode::LoadCell, offset), + Some(CompSlot::UnboundCell(_)) | None => self.code.emit_raise_unbound_local(ident.name_id), + }, + } + } + + /// Compiles loading a variable in call context (e.g., `foo()` loads `foo`). + /// + /// For `Global` scope, emits a callable-aware load opcode that pushes + /// an external function for undefined names instead of yielding + /// `NameLookup`. This allows execution to reach `CallFunction`, which naturally + /// yields `FunctionCall` — giving the host a chance to handle external function calls. + /// + /// For `Local` and `Cell` scopes, delegates to `compile_name` since those can't + /// be external functions (they're always defined locally or captured). + fn compile_name_callable(&mut self, ident: &Identifier) -> Result<(), CompileError> { + let slot = ident.namespace_id().as_u16(); + match ident.scope { + NameScope::Global if self.flags.globals_by_name => { + self.code + .emit_name_op(Opcode::LoadName, slot, ident.name_id, NAME_CALLABLE | NAME_GLOBAL_ONLY) + } + NameScope::Name => { + self.code.register_local_name(slot, ident.name_id); + self.code + .emit_name_op(Opcode::LoadName, slot, ident.name_id, NAME_CALLABLE) + } + NameScope::Global => { + // Global scope - name_id is encoded in the operand because global slot + // indices are in a different namespace from local slots, so looking up + // the name from the current frame's local_names would be incorrect + self.code + .emit_load_global_callable(ident.namespace_id().as_u16(), ident.name_id) + } + // Local, Cell, and CompVar can't be external functions - use regular load + NameScope::Local | NameScope::Cell | NameScope::CompVar => self.compile_name(ident), + } + } + + /// Compiles storing the top of stack to a variable. + /// + /// At module level, `Local` scope emits `StoreGlobal` + /// because module-level locals live in the globals array. + pub(super) fn compile_store(&mut self, target: &Identifier) -> Result<(), CompileError> { + let slot = target.namespace_id().as_u16(); + match target.scope { + NameScope::Local => { + // Module-level `Local` binds the global namespace; function-level + // `Local` is a genuine local that may freely shadow a dunder name. + if self.is_module_scope { + self.check_reserved_dunder_store(target)?; + } + self.code.register_local_name(slot, target.name_id); + if self.is_module_scope { + self.code.emit_u16(Opcode::StoreGlobal, slot) + } else { + self.code.emit_store_local(slot) + } + } + NameScope::Global => { + if self.flags.globals_by_name { + self.code + .emit_name_op(Opcode::StoreName, slot, target.name_id, NAME_GLOBAL_ONLY) + } else { + self.check_reserved_dunder_store(target)?; + self.code.emit_u16(Opcode::StoreGlobal, slot) + } + } + // A snippet namespace is a real dict, so it may bind any name, + // reserved module dunders included. + NameScope::Name => { + self.code.register_local_name(slot, target.name_id); + self.code.emit_name_op(Opcode::StoreName, slot, target.name_id, 0) + } + NameScope::Cell => { + // Named so `locals()` reports a cell the body only ever assigns. + self.code.register_local_name(slot, target.name_id); + // Emit local slot index — the VM reads the cell HeapId from the stack + self.code.emit_u16(Opcode::StoreCell, slot) + } + NameScope::CompVar => { + // Comp-var stores never go through `compile_store`. They are + // handled by `compile_comp_target_unpack`, which leaves the + // value on the operand stack as the natural result of + // `FOR_ITER` (and any subsequent `UNPACK_SEQUENCE` / + // `LIFT_TO_TOP` for nested tuples). + unreachable!( + "compile_store called with NameScope::CompVar — comp targets are stored via compile_comp_target_unpack" + ) + } + } + } + + /// Rejects assignment to a read-only module dunder at module/global scope. + /// + /// Monty exposes [`RESERVED_MODULE_DUNDERS`] with fixed values for CPython + /// compatibility but, unlike CPython, has no module namespace to write into, + /// so rebinding one is unsupported and surfaces as `NotImplementedError`. + /// Only stores to slot-backed module globals invoke this; explicit globals + /// dicts and function locals may bind these names. + fn check_reserved_dunder_store(&self, target: &Identifier) -> Result<(), CompileError> { + let name = self.interns.get_str(target.name_id); + if RESERVED_MODULE_DUNDERS.contains(&name) { + Err(CompileError::not_implemented( + format!("cannot reassign read-only module attribute '{name}'"), + target.position, + )) + } else { + Ok(()) + } + } + + // ======================================================================== + // Binary Operator Compilation + // ======================================================================== + + /// Compiles a binary operation. + /// + /// `parent_pos` is the position of the full binary expression (e.g., `1 / 0`), + /// which we restore before emitting the opcode so tracebacks show the right range. + fn compile_binary_op( + &mut self, + left: &ExprLoc, + op: &Operator, + right: &ExprLoc, + parent_pos: CodeRange, + ) -> Result<(), CompileError> { + match op { + // Short-circuit AND: evaluate left, jump if falsy + Operator::And => { + self.compile_expr(left)?; + let end_jump = self.code.emit_jump(Opcode::JumpIfFalseOrPop)?; + self.compile_expr(right)?; + self.code.patch_jump(end_jump)?; + } + + // Short-circuit OR: evaluate left, jump if truthy + Operator::Or => { + self.compile_expr(left)?; + let end_jump = self.code.emit_jump(Opcode::JumpIfTrueOrPop)?; + self.compile_expr(right)?; + self.code.patch_jump(end_jump)?; + } + + // Regular binary operators + _ => { + self.compile_expr(left)?; + self.compile_expr(right)?; + // Restore the full expression's position for traceback caret range + self.code.set_location(parent_pos, None); + self.code.emit(operator_to_opcode(op))?; + } + } + Ok(()) + } + + /// Compiles a chain comparison expression like `a < b < c < d`. + /// + /// Chain comparisons evaluate each intermediate value only once and short-circuit + /// on the first false result. Uses stack manipulation to avoid namespace pollution. + /// + /// Bytecode strategy for `a < b < c`: + /// ```text + /// eval a # Stack: [a] + /// eval b # Stack: [a, b] + /// Dup # Stack: [a, b, b] + /// Rot3 # Stack: [b, a, b] + /// CompareLt # Stack: [b, result1] + /// JumpIfFalseOrPop # if false: jump to cleanup; if true: pop, stack=[b] + /// eval c # Stack: [b, c] + /// CompareLt # Stack: [result2] + /// Jump @end + /// @cleanup: # Stack: [b, False] + /// Rot2 # Stack: [False, b] + /// Pop # Stack: [False] + /// @end: + /// ``` + fn compile_chain_comparison( + &mut self, + left: &ExprLoc, + comparisons: &[(CmpOperator, ExprLoc)], + position: CodeRange, + ) -> Result<(), CompileError> { + let n = comparisons.len(); + + // Compile leftmost operand + self.compile_expr(left)?; + + // Track jump targets for short-circuit cleanup + let mut cleanup_jumps = Vec::with_capacity(n - 1); + + for (i, (op, right)) in comparisons.iter().enumerate() { + let is_last = i == n - 1; + + // Compile the right operand + self.compile_expr(right)?; + + if !is_last { + // Keep a copy of the intermediate for the next comparison + self.code.emit(Opcode::Dup)?; + // Reorder: [prev, curr, curr] -> [curr, prev, curr] + self.code.emit(Opcode::Rot3)?; + } + + // Emit comparison + self.code.set_location(position, None); + self.code.emit(cmp_operator_to_opcode(*op))?; + + if !is_last { + // Short-circuit: if false, jump to cleanup + let jump = self.code.emit_jump(Opcode::JumpIfFalseOrPop)?; + cleanup_jumps.push(jump); + } + } + + // Jump past cleanup (result already on stack). + let end_jump = self.code.emit_jump(Opcode::Jump)?; + + // Cleanup: remove the saved intermediate value, keep False result. + for jump in cleanup_jumps { + self.code.patch_jump(jump)?; + } + self.code.emit(Opcode::Rot2)?; // [False, intermediate] + self.code.emit(Opcode::Pop)?; // [False] + + self.code.patch_jump(end_jump)?; + Ok(()) + } + + // ======================================================================== + // Control Flow Compilation + // ======================================================================== + + /// Compiles an if/else statement. + fn compile_if( + &mut self, + test: &ExprLoc, + body: &'a [PreparedNode], + or_else: &'a [PreparedNode], + ) -> Result<(), CompileError> { + self.compile_expr(test)?; + + if or_else.is_empty() { + // Simple if without else + let end_jump = self.code.emit_jump(Opcode::JumpIfFalse)?; + self.compile_block(body)?; + self.code.patch_jump(end_jump)?; + } else { + // If with else + let else_jump = self.code.emit_jump(Opcode::JumpIfFalse)?; + self.compile_block(body)?; + let end_jump = self.code.emit_jump(Opcode::Jump)?; + self.code.patch_jump(else_jump)?; + self.compile_block(or_else)?; + self.code.patch_jump(end_jump)?; + } + Ok(()) + } + + /// Compiles a ternary conditional expression. + fn compile_if_else_expr(&mut self, test: &ExprLoc, body: &ExprLoc, orelse: &ExprLoc) -> Result<(), CompileError> { + self.compile_expr(test)?; + let else_jump = self.code.emit_jump(Opcode::JumpIfFalse)?; + self.compile_expr(body)?; + let end_jump = self.code.emit_jump(Opcode::Jump)?; + self.code.patch_jump(else_jump)?; + self.compile_expr(orelse)?; + self.code.patch_jump(end_jump)?; + Ok(()) + } + + /// Compiles a function call expression. + /// + /// For builtin calls with positional-only arguments, emits the optimized `CallBuiltin` + /// opcode which avoids pushing/popping the callable on the stack. + /// + /// For other calls, pushes the callable onto the stack, then all arguments, then emits + /// `CallFunction` or `CallFunctionKw`. + /// + /// The `call_pos` is the position of the full call expression for proper traceback caret. + fn compile_call(&mut self, callable: &Callable, args: &ArgExprs, call_pos: CodeRange) -> Result<(), CompileError> { + // Check if we can use the optimized CallBuiltinFunction path: + // - Callable must be a builtin function (known at compile time) + // - Arguments must be positional-only (Empty, One, Two, or Args) + if let Callable::Builtin(Builtins::Function(builtin_func)) = callable + && let Some(arg_count) = self.compile_builtin_call(args, call_pos)? + { + // Optimization applied - CallBuiltinFunction emitted + self.code.set_location(call_pos, None); + self.code.emit_call_builtin_function(*builtin_func as u8, arg_count)?; + return Ok(()); + } + // Fall through to standard path for kwargs/unpacking + + // Check if we can use the optimized CallBuiltinType path: + // - Callable must be a builtin type constructor (known at compile time) + // - Arguments must be positional-only (Empty, One, Two, or Args) + if let Callable::Builtin(Builtins::Type(t)) = callable + && let Some(type_id) = t.callable_to_u8() + && let Some(arg_count) = self.compile_builtin_call(args, call_pos)? + { + // Optimization applied - CallBuiltinType emitted + self.code.set_location(call_pos, None); + self.code.emit_call_builtin_type(type_id, arg_count)?; + return Ok(()); + } + // Fall through to standard path for kwargs/unpacking or non-callable types + + // Standard path: push callable, compile args, emit CallFunction/CallFunctionKw + // Push the callable (use name position for NameError caret range) + match callable { + Callable::Builtin(builtin) => { + let idx = self.code.add_const(Value::Builtin(*builtin))?; + self.code.emit_u16(Opcode::LoadConst, idx)?; + } + Callable::Name(ident) => { + // Use callable-aware load opcodes so undefined names produce ExtFunction + // instead of yielding NameLookup, allowing CallFunction to yield FunctionCall + self.code.set_location(ident.position, None); + self.compile_name_callable(ident)?; + } + } + + // Compile arguments and emit the call + // Restore full call position before CallFunction for call-related errors + match args { + ArgExprs::Empty => { + self.code.set_location(call_pos, None); + self.code.emit_u8(Opcode::CallFunction, 0)?; + } + ArgExprs::One(arg) => { + self.compile_expr(arg)?; + self.code.set_location(call_pos, None); + self.code.emit_u8(Opcode::CallFunction, 1)?; + } + ArgExprs::Two(arg1, arg2) => { + self.compile_expr(arg1)?; + self.compile_expr(arg2)?; + self.code.set_location(call_pos, None); + self.code.emit_u8(Opcode::CallFunction, 2)?; + } + ArgExprs::Args(args) => { + // Check argument count limit before compiling + if args.len() > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} positional arguments in function call"), + call_pos, + )); + } + for arg in args { + self.compile_expr(arg)?; + } + let arg_count = u8::try_from(args.len()).expect("argument count exceeds u8"); + self.code.set_location(call_pos, None); + self.code.emit_u8(Opcode::CallFunction, arg_count)?; + } + ArgExprs::Kwargs(kwargs) => { + // Check keyword argument count limit + if kwargs.len() > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} keyword arguments in function call"), + call_pos, + )); + } + // Keyword-only call: compile kwarg values and emit CallFunctionKw + let mut kwname_ids = Vec::with_capacity(kwargs.len()); + for kwarg in kwargs { + self.compile_expr(&kwarg.value)?; + kwname_ids.push(check_name_index_u16(kwarg.key.name_id, call_pos)?); + } + self.code.set_location(call_pos, None); + self.code.emit_call_function_kw(0, &kwname_ids)?; + } + ArgExprs::ArgsKargs { + args, + var_args, + kwargs, + var_kwargs, + } => { + // Mixed positional and keyword arguments - may include *args or **kwargs unpacking + if var_args.is_some() || var_kwargs.is_some() { + // Use CallFunctionEx for unpacking - no limit on this path since + // args are built into a tuple dynamically at runtime + self.compile_call_with_unpacking( + callable, + args.as_ref(), + var_args.as_ref(), + kwargs.as_ref(), + var_kwargs.as_ref(), + call_pos, + )?; + } else { + // No unpacking - use CallFunctionKw for efficiency + // Check limits before compiling + let pos_count = args.as_ref().map_or(0, Vec::len); + let kw_count = kwargs.as_ref().map_or(0, Vec::len); + + if pos_count > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} positional arguments in function call"), + call_pos, + )); + } + if kw_count > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} keyword arguments in function call"), + call_pos, + )); + } + + // Compile positional args + if let Some(args) = args { + for arg in args { + self.compile_expr(arg)?; + } + } + + // Compile kwarg values and collect names + let mut kwname_ids = Vec::new(); + if let Some(kwargs) = kwargs { + for kwarg in kwargs { + self.compile_expr(&kwarg.value)?; + kwname_ids.push(check_name_index_u16(kwarg.key.name_id, call_pos)?); + } + } + + self.code.set_location(call_pos, None); + self.code.emit_call_function_kw( + u8::try_from(pos_count).expect("positional arg count exceeds u8"), + &kwname_ids, + )?; + } + } + ArgExprs::GeneralizedCall { args, kwargs } => { + // PEP 448: generalized unpacking — multiple *args or **kwargs. + // Callable was already pushed above this match; delegate to the helper. + let func_name_id = self.get_callable_name_id(callable)?; + self.compile_generalized_call_body(args, kwargs, func_name_id, call_pos)?; + } + } + Ok(()) + } + + /// Compiles function call arguments and emits the call instruction. + /// + /// This is used when the callable is already on the stack (e.g., from compiling an expression). + /// It compiles the arguments, then emits `CallFunction` or `CallFunctionKw` as appropriate. + fn compile_call_args(&mut self, args: &ArgExprs, call_pos: CodeRange) -> Result<(), CompileError> { + match args { + ArgExprs::Empty => { + self.code.set_location(call_pos, None); + self.code.emit_u8(Opcode::CallFunction, 0)?; + } + ArgExprs::One(arg) => { + self.compile_expr(arg)?; + self.code.set_location(call_pos, None); + self.code.emit_u8(Opcode::CallFunction, 1)?; + } + ArgExprs::Two(arg1, arg2) => { + self.compile_expr(arg1)?; + self.compile_expr(arg2)?; + self.code.set_location(call_pos, None); + self.code.emit_u8(Opcode::CallFunction, 2)?; + } + ArgExprs::Args(args) => { + if args.len() > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} positional arguments in function call"), + call_pos, + )); + } + for arg in args { + self.compile_expr(arg)?; + } + let arg_count = u8::try_from(args.len()).expect("argument count exceeds u8"); + self.code.set_location(call_pos, None); + self.code.emit_u8(Opcode::CallFunction, arg_count)?; + } + ArgExprs::Kwargs(kwargs) => { + if kwargs.len() > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} keyword arguments in function call"), + call_pos, + )); + } + let mut kwname_ids = Vec::with_capacity(kwargs.len()); + for kwarg in kwargs { + self.compile_expr(&kwarg.value)?; + kwname_ids.push(check_name_index_u16(kwarg.key.name_id, call_pos)?); + } + self.code.set_location(call_pos, None); + self.code.emit_call_function_kw(0, &kwname_ids)?; + } + ArgExprs::ArgsKargs { + args, + kwargs, + var_args, + var_kwargs, + } => { + // Mixed positional and keyword arguments - may include *args or **kwargs unpacking + if var_args.is_some() || var_kwargs.is_some() { + // Use CallFunctionExtended for unpacking - no limit on this path since + // args are built into a tuple dynamically at runtime. + // Callable is already on stack, so we just need to build args and kwargs. + self.compile_call_args_with_unpacking( + args.as_ref(), + var_args.as_ref(), + kwargs.as_ref(), + var_kwargs.as_ref(), + call_pos, + )?; + } else { + // No unpacking - use CallFunctionKw for efficiency + let pos_args = args.as_deref().unwrap_or(&[]); + let kw_args = kwargs.as_deref().unwrap_or(&[]); + let pos_count = pos_args.len(); + let kw_count = kw_args.len(); + + // Check limits separately (same as direct calls) + if pos_count > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} positional arguments in function call"), + call_pos, + )); + } + if kw_count > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} keyword arguments in function call"), + call_pos, + )); + } + + // Compile positional args + for arg in pos_args { + self.compile_expr(arg)?; + } + + // Compile keyword args + let mut kwname_ids = Vec::with_capacity(kw_count); + for kwarg in kw_args { + self.compile_expr(&kwarg.value)?; + kwname_ids.push(check_name_index_u16(kwarg.key.name_id, call_pos)?); + } + + self.code.set_location(call_pos, None); + self.code.emit_call_function_kw( + u8::try_from(pos_count).expect("positional arg count exceeds u8"), + &kwname_ids, + )?; + } + } + ArgExprs::GeneralizedCall { args, kwargs } => { + // PEP 448: generalized unpacking — callable is already on the stack. + // Use 0xFFFF as func_name_id since we don't know the callee name here. + self.compile_generalized_call_body(args, kwargs, 0xFFFF, call_pos)?; + } + } + Ok(()) + } + + /// Compiles arguments with `*args` and/or `**kwargs` unpacking when callable is already on stack. + /// + /// This is used for expression calls (e.g., `(lambda *a: a)(*xs)`) where the callable + /// is compiled as an expression and is already on the stack. + /// + /// Stack layout: callable (on stack) -> callable, args_tuple, kwargs_dict? + fn compile_call_args_with_unpacking( + &mut self, + args: Option<&Vec>, + var_args: Option<&ExprLoc>, + kwargs: Option<&Vec>, + var_kwargs: Option<&ExprLoc>, + call_pos: CodeRange, + ) -> Result<(), CompileError> { + // 1. Build args tuple + // Push regular positional args and build list + let pos_count = args.map_or(0, Vec::len); + if let Some(args) = args { + for arg in args { + self.compile_expr(arg)?; + } + } + let pos_count_u16 = check_collection_size_u16(pos_count, call_pos)?; + self.code.emit_u16(Opcode::BuildList, pos_count_u16)?; + + // Extend with *args if present + if let Some(var_args_expr) = var_args { + self.compile_expr(var_args_expr)?; + self.code.emit(Opcode::ListExtend)?; + } + + // Convert list to tuple + self.code.emit(Opcode::ListToTuple)?; + + // 2. Build kwargs dict (if we have kwargs or var_kwargs) + let has_kwargs = kwargs.is_some() || var_kwargs.is_some(); + if has_kwargs { + // Build dict from regular kwargs + let kw_count = kwargs.map_or(0, Vec::len); + if let Some(kwargs) = kwargs { + for kwarg in kwargs { + // Push key as interned string constant + let key_const = self.code.add_const(Value::InternString(kwarg.key.name_id))?; + self.code.emit_u16(Opcode::LoadConst, key_const)?; + // Push value + self.compile_expr(&kwarg.value)?; + } + } + let kw_count_u16 = check_collection_size_u16(kw_count, call_pos)?; + self.code.emit_u16(Opcode::BuildDict, kw_count_u16)?; + + // Merge **kwargs if present + // Use 0xFFFF for func_name_id (like builtins) since we don't have a name + if let Some(var_kwargs_expr) = var_kwargs { + self.compile_expr(var_kwargs_expr)?; + self.code.emit_u16(Opcode::DictMerge, 0xFFFF)?; + } + } + + // 3. Call the function + self.code.set_location(call_pos, None); + let flags = u8::from(has_kwargs); + self.code.emit_u8(Opcode::CallFunctionExtended, flags)?; + Ok(()) + } + + /// Compiles arguments for a builtin call and returns the arg count if optimization can be used. + /// + /// Returns `Some(arg_count)` if the call uses positional-only arguments (CallBuiltinFunction applicable). + /// Returns `None` if the call uses kwargs or unpacking (must use standard CallFunction path). + /// + /// When `Some` is returned, arguments have been compiled onto the stack. + fn compile_builtin_call(&mut self, args: &ArgExprs, call_pos: CodeRange) -> Result, CompileError> { + match args { + ArgExprs::Empty => Ok(Some(0)), + ArgExprs::One(arg) => { + self.compile_expr(arg)?; + Ok(Some(1)) + } + ArgExprs::Two(arg1, arg2) => { + self.compile_expr(arg1)?; + self.compile_expr(arg2)?; + Ok(Some(2)) + } + ArgExprs::Args(args) => { + if args.len() > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} positional arguments in function call"), + call_pos, + )); + } + for arg in args { + self.compile_expr(arg)?; + } + Ok(Some(u8::try_from(args.len()).expect("argument count exceeds u8"))) + } + // Kwargs or unpacking - fall back to standard path + ArgExprs::Kwargs(_) | ArgExprs::ArgsKargs { .. } | ArgExprs::GeneralizedCall { .. } => Ok(None), + } + } + + /// Compiles a function call with `*args` and/or `**kwargs` unpacking. + /// + /// This generates bytecode to build an args tuple and kwargs dict dynamically, + /// then calls the function using `CallFunctionEx`. + /// + /// Stack layout for call: + /// - callable (already on stack) + /// - args tuple + /// - kwargs dict (if present) + fn compile_call_with_unpacking( + &mut self, + callable: &Callable, + args: Option<&Vec>, + var_args: Option<&ExprLoc>, + kwargs: Option<&Vec>, + var_kwargs: Option<&ExprLoc>, + call_pos: CodeRange, + ) -> Result<(), CompileError> { + // Get function name for error messages. Builtins use their real interned name + // so duplicate-kwargs errors from **unpacking match CPython. + let func_name_id = self.get_callable_name_id(callable)?; + + // 1. Build args tuple + // Push regular positional args and build list + let pos_count = args.map_or(0, Vec::len); + if let Some(args) = args { + for arg in args { + self.compile_expr(arg)?; + } + } + let pos_count_u16 = check_collection_size_u16(pos_count, call_pos)?; + self.code.emit_u16(Opcode::BuildList, pos_count_u16)?; + + // Extend with *args if present + if let Some(var_args_expr) = var_args { + self.compile_expr(var_args_expr)?; + self.code.emit(Opcode::ListExtend)?; + } + + // Convert list to tuple + self.code.emit(Opcode::ListToTuple)?; + + // 2. Build kwargs dict (if we have kwargs or var_kwargs) + let has_kwargs = kwargs.is_some() || var_kwargs.is_some(); + if has_kwargs { + // Build dict from regular kwargs + let kw_count = kwargs.map_or(0, Vec::len); + if let Some(kwargs) = kwargs { + for kwarg in kwargs { + // Push key as interned string constant + let key_const = self.code.add_const(Value::InternString(kwarg.key.name_id))?; + self.code.emit_u16(Opcode::LoadConst, key_const)?; + // Push value + self.compile_expr(&kwarg.value)?; + } + } + let kw_count_u16 = check_collection_size_u16(kw_count, call_pos)?; + self.code.emit_u16(Opcode::BuildDict, kw_count_u16)?; + + // Merge **kwargs if present + if let Some(var_kwargs_expr) = var_kwargs { + self.compile_expr(var_kwargs_expr)?; + self.code.emit_u16(Opcode::DictMerge, func_name_id)?; + } + } + + // 3. Call the function + self.code.set_location(call_pos, None); + let flags = u8::from(has_kwargs); + self.code.emit_u8(Opcode::CallFunctionExtended, flags)?; + Ok(()) + } + + /// Returns the best available function name id for call-site error messages. + /// + /// This is primarily used by `DictMerge` during `**kwargs` unpacking so + /// duplicate-key and non-mapping errors can mention the actual callee name. + /// When the callable is not a named local/global, we still try to resolve + /// builtin functions, builtin exception constructors, and builtin types to + /// their interned public names. + fn get_callable_name_id(&self, callable: &Callable) -> Result { + match callable { + Callable::Name(ident) => check_name_index_u16(ident.name_id, ident.position), + Callable::Builtin(builtin) => Ok(self.get_builtin_name_id(*builtin).unwrap_or(0xFFFF)), + } + } + + /// Resolves a builtin callable to its interned public name, if available. + /// + /// Returning `None` falls back to `` in the VM, which is still + /// correct but less helpful. In practice these names should already be + /// interned during preparation because builtin names are resolved from source. + fn get_builtin_name_id(&self, builtin: Builtins) -> Option { + let name_id = match builtin { + Builtins::Function(function) => { + let name: &'static str = function.into(); + self.interns.get_string_id_by_name(name)? + } + Builtins::ExcType(exc_type) => self.interns.get_string_id_by_name(&exc_type.to_string())?, + Builtins::Type(type_) => { + let name = type_.builtin_name()?; + self.interns.get_string_id_by_name(name)? + } + }; + + u16::try_from(name_id.index()).ok() + } + + /// Compiles an attribute call on an object. + /// + /// The object should already be on the stack. This compiles the arguments + /// and emits a CallAttr opcode with the attribute name and arg count. + fn compile_method_call( + &mut self, + attr: &EitherStr, + args: &ArgExprs, + call_pos: CodeRange, + ) -> Result<(), CompileError> { + // Get the interned attribute name, converted up-front so the limit check + // happens once per method call rather than at every emit-site below. + let name_id = attr.string_id().expect("CallAttr requires interned attr name"); + let name_idx = check_name_index_u16(name_id, call_pos)?; + + // Compile arguments based on the argument type + match args { + ArgExprs::Empty => { + self.code.set_location(call_pos, None); + self.code.emit_u16_u8(Opcode::CallAttr, name_idx, 0)?; + } + ArgExprs::One(arg) => { + self.compile_expr(arg)?; + self.code.set_location(call_pos, None); + self.code.emit_u16_u8(Opcode::CallAttr, name_idx, 1)?; + } + ArgExprs::Two(arg1, arg2) => { + self.compile_expr(arg1)?; + self.compile_expr(arg2)?; + self.code.set_location(call_pos, None); + self.code.emit_u16_u8(Opcode::CallAttr, name_idx, 2)?; + } + ArgExprs::Args(args) => { + // Check argument count limit + if args.len() > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} arguments in method call"), + call_pos, + )); + } + for arg in args { + self.compile_expr(arg)?; + } + let arg_count = u8::try_from(args.len()).expect("argument count exceeds u8"); + self.code.set_location(call_pos, None); + self.code.emit_u16_u8(Opcode::CallAttr, name_idx, arg_count)?; + } + ArgExprs::Kwargs(kwargs) => { + // Keyword-only method call + if kwargs.len() > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} keyword arguments in method call"), + call_pos, + )); + } + // Compile kwarg values and collect names + let mut kwname_ids = Vec::with_capacity(kwargs.len()); + for kwarg in kwargs { + self.compile_expr(&kwarg.value)?; + kwname_ids.push(check_name_index_u16(kwarg.key.name_id, call_pos)?); + } + self.code.set_location(call_pos, None); + self.code.emit_call_attr_kw(name_idx, 0, &kwname_ids)?; + } + ArgExprs::ArgsKargs { + args, + kwargs, + var_args, + var_kwargs, + } => { + // Check if there's unpacking - use CallAttrExtended + if var_args.is_some() || var_kwargs.is_some() { + return self.compile_method_call_with_unpacking( + name_id, + args.as_ref(), + var_args.as_ref(), + kwargs.as_ref(), + var_kwargs.as_ref(), + call_pos, + ); + } + + // No unpacking - use CallAttrKw for efficiency + let pos_count = args.as_ref().map_or(0, Vec::len); + let kw_count = kwargs.as_ref().map_or(0, Vec::len); + + if pos_count > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} positional arguments in method call"), + call_pos, + )); + } + if kw_count > MAX_CALL_ARGS { + return Err(CompileError::new( + format!("more than {MAX_CALL_ARGS} keyword arguments in method call"), + call_pos, + )); + } + + // Compile positional args + if let Some(args) = args { + for arg in args { + self.compile_expr(arg)?; + } + } + + // Compile kwarg values and collect names + let mut kwname_ids = Vec::new(); + if let Some(kwargs) = kwargs { + for kwarg in kwargs { + self.compile_expr(&kwarg.value)?; + kwname_ids.push(check_name_index_u16(kwarg.key.name_id, call_pos)?); + } + } + + self.code.set_location(call_pos, None); + self.code.emit_call_attr_kw( + name_idx, + u8::try_from(pos_count).expect("positional arg count exceeds u8"), + &kwname_ids, + )?; + } + ArgExprs::GeneralizedCall { args, kwargs } => { + // PEP 448: generalized unpacking on a method call. + // Receiver is already on the stack; build args tuple and kwargs dict, + // then emit CallAttrExtended. + let func_name_id = name_idx; + let has_kwargs = !kwargs.is_empty(); + + // 1. Build args tuple + self.code.emit_u16(Opcode::BuildList, 0)?; + for arg in args { + match arg { + CallArg::Value(e) => { + self.compile_expr(e)?; + self.code.emit_u8(Opcode::ListAppend, 0)?; + } + CallArg::Unpack(e) => { + self.compile_expr(e)?; + self.code.emit(Opcode::ListExtend)?; + } + } + } + self.code.emit(Opcode::ListToTuple)?; + + // 2. Build kwargs dict (if any) + if has_kwargs { + self.code.emit_u16(Opcode::BuildDict, 0)?; + for kwarg in kwargs { + match kwarg { + CallKwarg::Named(kw) => { + let key_const = self.code.add_const(Value::InternString(kw.key.name_id))?; + self.code.emit_u16(Opcode::LoadConst, key_const)?; + self.compile_expr(&kw.value)?; + self.code.emit_u16(Opcode::BuildDict, 1)?; + self.code.emit_u16(Opcode::MethodDictMerge, func_name_id)?; + } + CallKwarg::Unpack(e) => { + self.compile_expr(e)?; + self.code.emit_u16(Opcode::MethodDictMerge, func_name_id)?; + } + } + } + } + + // 3. Emit CallAttrExtended + self.code.set_location(call_pos, None); + let flags = u8::from(has_kwargs); + self.code.emit_u16_u8(Opcode::CallAttrExtended, func_name_id, flags)?; + } + } + Ok(()) + } + + /// Compiles a method call with `*args` and/or `**kwargs` unpacking. + /// + /// The receiver object should already be on the stack. This builds the args tuple + /// and optional kwargs dict, then emits `CallAttrExtended`. + fn compile_method_call_with_unpacking( + &mut self, + name_id: StringId, + args: Option<&Vec>, + var_args: Option<&ExprLoc>, + kwargs: Option<&Vec>, + var_kwargs: Option<&ExprLoc>, + call_pos: CodeRange, + ) -> Result<(), CompileError> { + // Convert the attribute name id up front so the overflow check happens + // once and both `DictMerge` (for error messages) and `CallAttrExtended` + // can reuse the converted value. + let name_idx = check_name_index_u16(name_id, call_pos)?; + // 1. Build args tuple + // Push regular positional args and build list + let pos_count = args.map_or(0, Vec::len); + if let Some(args) = args { + for arg in args { + self.compile_expr(arg)?; + } + } + let pos_count_u16 = check_collection_size_u16(pos_count, call_pos)?; + self.code.emit_u16(Opcode::BuildList, pos_count_u16)?; + + // Extend with *args if present + if let Some(var_args_expr) = var_args { + self.compile_expr(var_args_expr)?; + self.code.emit(Opcode::ListExtend)?; + } + + // Convert list to tuple + self.code.emit(Opcode::ListToTuple)?; + + // 2. Build kwargs dict (if we have kwargs or var_kwargs) + let has_kwargs = kwargs.is_some() || var_kwargs.is_some(); + if has_kwargs { + // Build dict from regular kwargs + let kw_count = kwargs.map_or(0, Vec::len); + if let Some(kwargs) = kwargs { + for kwarg in kwargs { + // Push key as interned string constant + let key_const = self.code.add_const(Value::InternString(kwarg.key.name_id))?; + self.code.emit_u16(Opcode::LoadConst, key_const)?; + // Push value + self.compile_expr(&kwarg.value)?; + } + } + let kw_count_u16 = check_collection_size_u16(kw_count, call_pos)?; + self.code.emit_u16(Opcode::BuildDict, kw_count_u16)?; + + // Merge **kwargs if present + if let Some(var_kwargs_expr) = var_kwargs { + self.compile_expr(var_kwargs_expr)?; + // Method-call form — `MethodDictMerge` qualifies the duplicate- + // kwarg error with the receiver's type (e.g. `list.sort()`). + self.code.emit_u16(Opcode::MethodDictMerge, name_idx)?; + } + } + + // 3. Call the method with CallAttrExtended + self.code.set_location(call_pos, None); + let flags = u8::from(has_kwargs); + self.code.emit_u16_u8(Opcode::CallAttrExtended, name_idx, flags)?; + Ok(()) + } + + /// Shared body for PEP 448 generalized calls with multiple `*args` and/or `**kwargs`. + /// + /// Assumes the callable is already on the stack (pushed by the caller). + /// Emits: + /// 1. `BuildList(0)` + per-item `ListAppend`/`ListExtend` + `ListToTuple` for args. + /// 2. `BuildDict(0)` + per-item `BuildDict(1)+DictMerge`/`DictMerge` for kwargs (if any). + /// 3. `CallFunctionExtended(flags)`. + /// + /// `func_name_id` is used in `DictMerge` error messages; pass `0xFFFF` when unknown. + /// + /// Stack transition (callable already on stack): + /// `[callable]` → `[callable, args_tuple]` → `[callable, args_tuple, kwargs_dict?]` + /// → `[result]` + fn compile_generalized_call_body( + &mut self, + args: &[CallArg], + kwargs: &[CallKwarg], + func_name_id: u16, + call_pos: CodeRange, + ) -> Result<(), CompileError> { + // 1. Build args tuple + self.code.emit_u16(Opcode::BuildList, 0)?; + for arg in args { + match arg { + CallArg::Value(e) => { + self.compile_expr(e)?; + self.code.emit_u8(Opcode::ListAppend, 0)?; + } + CallArg::Unpack(e) => { + self.compile_expr(e)?; + self.code.emit(Opcode::ListExtend)?; + } + } + } + self.code.emit(Opcode::ListToTuple)?; + + // 2. Build kwargs dict (if any) + let has_kwargs = !kwargs.is_empty(); + if has_kwargs { + // Start with an empty dict, then merge each kwarg one at a time via DictMerge + // so that duplicates (including Named+Unpack ordering) raise TypeError correctly. + self.code.emit_u16(Opcode::BuildDict, 0)?; + for kwarg in kwargs { + match kwarg { + CallKwarg::Named(kw) => { + // Wrap key+value in a single-item dict, then merge into kwargs dict. + let key_const = self.code.add_const(Value::InternString(kw.key.name_id))?; + self.code.emit_u16(Opcode::LoadConst, key_const)?; + self.compile_expr(&kw.value)?; + self.code.emit_u16(Opcode::BuildDict, 1)?; + self.code.emit_u16(Opcode::DictMerge, func_name_id)?; + } + CallKwarg::Unpack(e) => { + self.compile_expr(e)?; + self.code.emit_u16(Opcode::DictMerge, func_name_id)?; + } + } + } + } + + // 3. Emit the extended call + self.code.set_location(call_pos, None); + let flags = u8::from(has_kwargs); + self.code.emit_u8(Opcode::CallFunctionExtended, flags)?; + Ok(()) + } + + /// Compiles a for loop. + fn compile_for( + &mut self, + target: &UnpackTarget, + iter: &ExprLoc, + body: &'a [PreparedNode], + or_else: &'a [PreparedNode], + ) -> Result<(), CompileError> { + // Compile iterator expression + self.compile_expr(iter)?; + // Convert to iterator + self.code.emit(Opcode::GetIter)?; + + // Loop start + let loop_start = self.code.current_jump_target(); + + // Push loop block for break/continue + self.fblocks.push(FBlock::ForLoop(LoopInfo { + start: loop_start, + break_jumps: Vec::new(), + })); + + // ForIter: advance iterator or jump to end + let end_jump = self.code.emit_jump(Opcode::ForIter)?; + + // Store current value to target (handles both single identifiers and tuple unpacking) + self.compile_unpack_target(target)?; + + // Compile body + self.compile_block(body)?; + + // Jump back to loop start + self.code.emit_jump_to(Opcode::Jump, loop_start)?; + // End of loop - ForIter jumps here when iterator is exhausted + self.code.patch_jump(end_jump)?; + + // Pop loop block before compiling else block + let loop_info = self + .fblocks + .pop() + .expect("for-loop compilation should retain its frame block") + .expect_for_loop(); + + // Compile else block (runs if loop completed without break) + if !or_else.is_empty() { + self.compile_block(or_else)?; + } + + // Patch break jumps to here - AFTER the else block so break skips else + for break_jump in loop_info.break_jumps { + self.code.patch_jump(break_jump)?; + } + + Ok(()) + } + + /// Compiles a while loop. + /// + /// The bytecode structure: + /// ```text + /// loop_start: + /// [evaluate condition] + /// JumpIfFalse -> end_jump + /// [body] + /// Jump -> loop_start + /// end_jump: + /// [else block] + /// [break patches here] + /// ``` + /// + /// Key differences from `for` loops: + /// - No `GetIter` (no iterator) + /// - No `ForIter` (use `JumpIfFalse` instead) + /// - `continue` jumps to condition evaluation + /// - `break` doesn't need to pop iterator (nothing extra on stack) + fn compile_while( + &mut self, + test: &ExprLoc, + body: &'a [PreparedNode], + or_else: &'a [PreparedNode], + ) -> Result<(), CompileError> { + let loop_start = self.code.current_jump_target(); + + self.fblocks.push(FBlock::WhileLoop(LoopInfo { + start: loop_start, + break_jumps: Vec::new(), + })); + + self.compile_expr(test)?; + let end_jump = self.code.emit_jump(Opcode::JumpIfFalse)?; + + self.compile_block(body)?; + self.code.emit_jump_to(Opcode::Jump, loop_start)?; + + self.code.patch_jump(end_jump)?; + let loop_info = self + .fblocks + .pop() + .expect("while-loop compilation should retain its frame block") + .expect_while_loop(); + + if !or_else.is_empty() { + self.compile_block(or_else)?; + } + + for break_jump in loop_info.break_jumps { + self.code.patch_jump(break_jump)?; + } + + Ok(()) + } + + /// Compiles a break statement. + /// + /// Unwinds every enclosing frame block up to and including the innermost + /// loop — running inline `finally` bodies, calling `__exit__` for `with` + /// blocks, clearing exception state, and popping the for-loop iterator — + /// then jumps to the loop end (past its `else` block). + fn compile_break(&mut self, position: CodeRange) -> Result<(), CompileError> { + let Some(loop_idx) = self.innermost_loop_idx() else { + return Err(CompileError::new("'break' outside loop", position)); + }; + if self.code.is_dead() { + return Ok(()); + } + + // Unwind through the loop itself: the ForLoop arm pops the iterator. + let popped = self.emit_unwind(self.fblocks.len() - loop_idx, false)?; + let jump = self.code.emit_jump(Opcode::Jump)?; + self.restore_fblocks(popped); + + match &mut self.fblocks[loop_idx] { + FBlock::WhileLoop(info) | FBlock::ForLoop(info) => info.break_jumps.push(jump), + _ => unreachable!("innermost_loop_idx returned a non-loop block"), + } + Ok(()) + } + + /// Compiles a continue statement. + /// + /// Unwinds every enclosing frame block up to (but not including) the + /// innermost loop, then jumps to the loop start. The for-loop iterator is + /// left on the stack because `ForIter` expects it. + fn compile_continue(&mut self, position: CodeRange) -> Result<(), CompileError> { + let Some(loop_idx) = self.innermost_loop_idx() else { + return Err(CompileError::new("'continue' not properly in loop", position)); + }; + if self.code.is_dead() { + return Ok(()); + } + + let loop_start = match &self.fblocks[loop_idx] { + FBlock::WhileLoop(info) | FBlock::ForLoop(info) => info.start, + _ => unreachable!("innermost_loop_idx returned a non-loop block"), + }; + let popped = self.emit_unwind(self.fblocks.len() - loop_idx - 1, false)?; + self.code.emit_jump_to(Opcode::Jump, loop_start)?; + self.restore_fblocks(popped); + Ok(()) + } + + /// Index of the innermost enclosing loop block, if any. + fn innermost_loop_idx(&self) -> Option { + self.fblocks + .iter() + .rposition(|b| matches!(b, FBlock::WhileLoop(_) | FBlock::ForLoop(_))) + } + + /// Returns this frame's active exception depth at the compile point. + /// Protected regions record it so propagation can discard exceptions from + /// bypassed handlers. + fn exc_stack_count(&self) -> u16 { + let count = self + .fblocks + .iter() + .filter(|b| matches!(b, FBlock::ExceptHandler { .. } | FBlock::FinallyEnd)) + .count(); + u16::try_from(count).expect("except/finally nesting exceeds u16") + } + + /// Compiles one stack-specific copy of a `finally` body. + fn compile_finally_copy(&mut self, finally: &'a [PreparedNode]) -> Result<(), CompileError> { + if self.code.is_dead() { + return Ok(()); + } + self.finally_copies += 1; + if self.finally_copies > MAX_FINALLY_COPIES { + Err(CompileError::new( + format!("too many inline finally copies; maximum is {MAX_FINALLY_COPIES}"), + self.code.current_position(), + )) + } else { + self.compile_block(finally) + } + } + + /// Clears an `except ... as name` target without failing if it was deleted. + fn compile_clear_handler_name(&mut self, name: Option<&Identifier>) -> Result<(), CompileError> { + if let Some(name) = name { + self.code.emit(Opcode::LoadNone)?; + self.compile_store(name)?; + self.compile_delete(name)?; + } + Ok(()) + } + + /// Temporarily removes `count` blocks and emits their cleanup. + /// `preserve_tos` protects a pending return value; callers restore the + /// returned blocks after emitting the path's terminator. + fn emit_unwind(&mut self, count: usize, preserve_tos: bool) -> Result>, CompileError> { + let mut popped = Vec::with_capacity(count); + for _ in 0..count { + let mut block = self.fblocks.pop().expect("emit_unwind: fblock stack underflow"); + self.emit_block_unwind(&mut block, preserve_tos)?; + popped.push(block); + } + Ok(popped) + } + + /// Emits one block's cleanup while it is absent from the block stack. + /// Thus control flow inside inline cleanup sees only outer blocks. + fn emit_block_unwind(&mut self, block: &mut FBlock<'a>, preserve_tos: bool) -> Result<(), CompileError> { + match block { + FBlock::WhileLoop(_) => Ok(()), + FBlock::ForLoop(_) => { + // Pop the iterator (below the preserved return value, if any). + if preserve_tos { + self.code.emit(Opcode::Rot2)?; + } + self.code.emit(Opcode::Pop) + } + // Exclude cleanup for outer blocks from this exited region. + FBlock::TryExcept { region } => { + region.interrupt(self.code.current_offset()); + Ok(()) + } + FBlock::FinallyTry { region, finally } => { + region.interrupt(self.code.current_offset()); + let finally = *finally; + // Discard a pending return if this `finally` exits early. + if preserve_tos { + self.fblocks.push(FBlock::PopValue); + } + self.compile_finally_copy(finally)?; + if preserve_tos { + self.fblocks + .pop() + .expect("return unwind should retain its pending value block") + .expect_pop_value(); + } + Ok(()) + } + FBlock::ExceptHandler { name, region } => { + region.interrupt(self.code.current_offset()); + self.code.emit(Opcode::ClearException)?; + self.compile_clear_handler_name(*name) + } + // Discard the in-flight exception: break/continue/return in a + // finally body swallows the exception that triggered it. + FBlock::FinallyEnd => self.code.emit(Opcode::ClearException), + FBlock::With { region } => { + // Keep `__exit__` outside its own handler region. + region.interrupt(self.code.current_offset()); + if preserve_tos { + self.code.emit(Opcode::Rot2)?; + } + self.code.emit(Opcode::WithExit)?; + self.code.emit(Opcode::Pop) + } + FBlock::PopValue => { + if preserve_tos { + self.code.emit(Opcode::Rot2)?; + } + self.code.emit(Opcode::Pop) + } + } + } + + /// Restores blocks popped by [`emit_unwind`](Self::emit_unwind) after the + /// unwind path's terminator, re-opening interrupted regions at the + /// current offset: subsequent code belongs to the constructs again. + fn restore_fblocks(&mut self, popped: Vec>) { + let at = self.code.current_offset(); + for mut block in popped.into_iter().rev() { + if let Some(region) = block.region_mut() { + region.resume(at); + } + self.fblocks.push(block); + } + } + + // ======================================================================== + // Comprehension Compilation + // ======================================================================== + + /// Compiles a list comprehension: `[elt for target in iter if cond...]` + /// + /// Bytecode structure: + /// ```text + /// BUILD_LIST 0 + /// + /// GET_ITER + /// loop_start: + /// FOR_ITER end_loop ; pushes the iter's value + /// [UNPACK / LIFT_TO_TOP] ; comp-var leaves end up on operand stack + /// + /// [nested generators...] + /// + /// LIST_APPEND depth ; reaches list by counting items between + /// POP × K_this_generator ; remove this generator's comp vars + /// JUMP loop_start + /// end_loop: ; FOR_ITER popped the iter on exhaustion + /// ; result list on stack + /// ``` + /// + /// Comprehension targets live on the operand stack as the values pushed + /// by `FOR_ITER` (plus unpacked sub-values). Captured targets are copied + /// into stable cells allocated outside the loops. Per-iteration `POP`s + /// clean the raw values before jumping back to the loop head. + fn compile_list_comp( + &mut self, + elt: &ExprLoc, + generators: &[Comprehension], + captured_slots: &[u16], + ) -> Result<(), CompileError> { + if self.code.is_dead() { + return Ok(()); + } + check_comp_generators(generators.len(), elt.position)?; + self.code.emit_u16(Opcode::BuildList, 0)?; + let depth_after_collection = self + .code + .stack_depth() + .expect("list comp: BuildList kept us live, stack_depth must be Some"); + self.enter_captured_comp_cells(captured_slots, elt.position)?; + + self.compile_comprehension_generators(generators, 0, |compiler| { + compiler.compile_expr(elt)?; + if compiler.code.is_dead() { + return Ok(()); + } + let depth = compiler.compute_append_depth(depth_after_collection, 1, elt.position)?; + compiler.code.emit_u8(Opcode::ListAppend, depth) + })?; + self.exit_captured_comp_cells(captured_slots)?; + + Ok(()) + } + + /// Compiles a set comprehension: `{elt for target in iter if cond...}` + fn compile_set_comp( + &mut self, + elt: &ExprLoc, + generators: &[Comprehension], + captured_slots: &[u16], + ) -> Result<(), CompileError> { + if self.code.is_dead() { + return Ok(()); + } + check_comp_generators(generators.len(), elt.position)?; + self.code.emit_u16(Opcode::BuildSet, 0)?; + let depth_after_collection = self + .code + .stack_depth() + .expect("set comp: BuildSet kept us live, stack_depth must be Some"); + self.enter_captured_comp_cells(captured_slots, elt.position)?; + + self.compile_comprehension_generators(generators, 0, |compiler| { + compiler.compile_expr(elt)?; + if compiler.code.is_dead() { + return Ok(()); + } + let depth = compiler.compute_append_depth(depth_after_collection, 1, elt.position)?; + compiler.code.emit_u8(Opcode::SetAdd, depth) + })?; + self.exit_captured_comp_cells(captured_slots)?; + + Ok(()) + } + + /// Compiles a dict comprehension: `{key: value for target in iter if cond...}` + fn compile_dict_comp( + &mut self, + key: &ExprLoc, + value: &ExprLoc, + generators: &[Comprehension], + captured_slots: &[u16], + ) -> Result<(), CompileError> { + if self.code.is_dead() { + return Ok(()); + } + check_comp_generators(generators.len(), key.position)?; + self.code.emit_u16(Opcode::BuildDict, 0)?; + let depth_after_collection = self + .code + .stack_depth() + .expect("dict comp: BuildDict kept us live, stack_depth must be Some"); + self.enter_captured_comp_cells(captured_slots, key.position)?; + + self.compile_comprehension_generators(generators, 0, |compiler| { + compiler.compile_expr(key)?; + compiler.compile_expr(value)?; + if compiler.code.is_dead() { + return Ok(()); + } + // DictSetItem pops 2 (key+value), so the post-pop offset for the + // collection is one deeper than the list/set case. + let depth = compiler.compute_append_depth(depth_after_collection, 2, key.position)?; + compiler.code.emit_u8(Opcode::DictSetItem, depth) + })?; + self.exit_captured_comp_cells(captured_slots)?; + + Ok(()) + } + + /// Allocates stable cells for comprehension targets captured by nested callables. + fn enter_captured_comp_cells(&mut self, captured_slots: &[u16], position: CodeRange) -> Result<(), CompileError> { + for &slot in captured_slots { + self.code.emit(Opcode::BuildCell)?; + let offset = self + .code + .stack_depth() + .expect("BuildCell keeps comprehension code live") + .checked_sub(1) + .and_then(|offset| self.frame_locals.checked_add(offset)) + .ok_or_else(|| CompileError::new("captured comprehension cell exceeds u16 stack offset", position))?; + let slot_index = usize::from(slot); + if slot_index >= self.comp_slots.len() { + self.comp_slots.resize(slot_index + 1, None); + } + self.comp_slots[slot_index] = Some(CompSlot::UnboundCell(offset)); + } + Ok(()) + } + + /// Removes a comprehension's stable cell references while preserving its result. + fn exit_captured_comp_cells(&mut self, captured_slots: &[u16]) -> Result<(), CompileError> { + for &slot in captured_slots.iter().rev() { + self.code.emit(Opcode::Pop)?; + self.comp_slots[usize::from(slot)] = None; + } + Ok(()) + } + + /// Computes the `depth` operand for `ListAppend` / `SetAdd` / `DictSetItem`. + /// + /// All three opcodes pop their value(s) first and then index the + /// collection at `len_post_pop - 1 - depth`. We want the collection at + /// its known position (`depth_after_collection - 1`), so the operand is + /// `current_stack_depth - depth_after_collection - 1` for list/set (pops 1) + /// or `current_stack_depth - depth_after_collection - 2` for dict (pops 2). + /// The caller passes the pop count. + fn compute_append_depth( + &self, + depth_after_collection: u16, + pops: u16, + position: CodeRange, + ) -> Result { + let current = self.code.stack_depth().expect("compute_append_depth in dead code"); + let depth = current + .checked_sub(depth_after_collection) + .and_then(|d| d.checked_sub(pops)) + .ok_or_else(|| CompileError::new("comprehension stack-depth bookkeeping went negative", position))?; + u8::try_from(depth).map_err(|_| { + CompileError::new( + "comprehension target + iterator count exceeds u8 depth operand", + position, + ) + }) + } + + /// Recursively compiles comprehension generators (the for/if clauses). + /// + /// For each generator: + /// 1. Compile the iterator expression and `GET_ITER`. + /// 2. Start loop: `FOR_ITER` pushes the iter's value (or pops iter and + /// jumps to end on exhaustion). + /// 3. Unpack the comp target — `compile_comp_target_unpack` emits any + /// `UNPACK_SEQUENCE` / `UNPACK_EX` / `LIFT_TO_TOP` needed and records + /// each leaf's operand-stack offset. + /// 4. Compile filter conditions; on false, jump back to loop start + /// (skipping per-iter POPs and the body — the per-iter operand-stack + /// items live below the filter result, so this works the same way it + /// did with the dedicated-region scheme). + /// 5. Either recurse for the next generator, or call `body_fn` at the + /// innermost level (which emits the element expression and + /// `LIST_APPEND` / `SET_ADD` / `DICT_SET_ITEM`). + /// 6. Per-iteration `POP` for each comp-var leaf produced by this + /// generator's target, restoring the loop-start stack shape. + /// 7. Jump back to loop start. + fn compile_comprehension_generators( + &mut self, + generators: &[Comprehension], + index: usize, + body_fn: impl FnOnce(&mut Self) -> Result<(), CompileError>, + ) -> Result<(), CompileError> { + let generator = &generators[index]; + + // Compile iterator expression + self.compile_expr(&generator.iter)?; + self.code.emit(Opcode::GetIter)?; + + // Loop start + let loop_start = self.code.current_jump_target(); + + // FOR_ITER: pushes value, or pops iter and jumps to end on exhaustion. + let end_jump = self.code.emit_jump(Opcode::ForIter)?; + + // Unpack target and record each leaf's active storage. + let comp_var_slots = self.compile_comp_target_unpack(&generator.target)?; + + // Filters: any false → forward-jump to the per-iter cleanup block + // below. We can't jump directly to `loop_start`: the comp vars are + // on the operand stack, so we must pop them first to keep the + // loop-start stack shape consistent. `JumpIfFalse` pops `cond`, so + // arrival depth at the cleanup label matches the post-body depth + // (both are `loop_start + K`). + let mut filter_skip_jumps = Vec::with_capacity(generator.ifs.len()); + for cond in &generator.ifs { + self.compile_expr(cond)?; + filter_skip_jumps.push(self.code.emit_jump(Opcode::JumpIfFalse)?); + } + + // Recurse or emit body. + if index + 1 < generators.len() { + self.compile_comprehension_generators(generators, index + 1, body_fn)?; + } else { + body_fn(self)?; + } + + // Per-iteration cleanup block: pop this generator's comp vars so the + // JUMP back to `loop_start` lands at the same stack shape as the + // previous iteration's entry. Filter-failure jumps also land here. + for jmp in filter_skip_jumps { + self.code.patch_jump(jmp)?; + } + for _ in 0..comp_var_slots.len() { + self.code.emit(Opcode::Pop)?; + } + + // Jump back to loop start + self.code.emit_jump_to(Opcode::Jump, loop_start)?; + self.code.patch_jump(end_jump)?; + + // Comp vars are out of scope after the loop body. Sibling + // comprehensions may reuse these slot IDs. + for slot in &comp_var_slots { + self.comp_slots[usize::from(*slot)] = None; + } + + Ok(()) + } + + /// Compiles the unpacking of a comprehension target. + /// + /// At entry, `FOR_ITER` has pushed the iter's value at TOS. This emits + /// `UNPACK_SEQUENCE` / `UNPACK_EX` / `LIFT_TO_TOP` as needed (nested + /// tuples force `LIFT_TO_TOP` to bring sub-iterables to TOS for + /// further unpacking) and records each leaf's active storage. + /// + /// Returns the slot IDs for this target's leaves so the caller can + /// emit a matching `POP` per leaf for per-iteration cleanup. + fn compile_comp_target_unpack(&mut self, target: &UnpackTarget) -> Result, CompileError> { + // `FOR_ITER` just pushed; current depth's TOS index is the value's + // operand-stack offset, which is also the offset of the first leaf + // produced by this unpack. + // + // If we're already in dead-code state (e.g. an earlier generator's + // iter expression contained a `RaiseUnboundLocal` that terminated the + // current code region), no bytecode emission would have any effect. + // Return an empty slot list — `compile_comprehension_generators` then + // emits its `POP`s and `JUMP` in dead state, which are also no-ops. + let Some(stack_depth) = self.code.stack_depth() else { + return Ok(Vec::new()); + }; + let base_offset = stack_depth - 1; + + let mut sim: Vec> = vec![SimItem::Pending(target)]; + self.process_unpack_sim(&mut sim)?; + + // All items should be Leafs now. Record offsets in order. + let mut slot_ids = Vec::with_capacity(sim.len()); + for (i, item) in sim.into_iter().enumerate() { + let SimItem::Leaf(slot) = item else { + unreachable!("process_unpack_sim left a Pending on the sim"); + }; + let i_u16 = u16::try_from(i).expect("comp-var index bounded by u8 unpack count"); + let offset = base_offset.checked_add(i_u16).ok_or_else(|| { + CompileError::new( + "comprehension operand-stack offset exceeds u16", + target_position(target), + ) + })?; + let value_offset = self.frame_locals.checked_add(offset).ok_or_else(|| { + CompileError::new( + "comprehension comp-var slot exceeds u16 (frame_locals + offset)", + target_position(target), + ) + })?; + let slot_idx = usize::from(slot); + if slot_idx >= self.comp_slots.len() { + self.comp_slots.resize(slot_idx + 1, None); + } + self.comp_slots[slot_idx] = match self.comp_slots[slot_idx] { + Some(CompSlot::UnboundCell(cell_offset) | CompSlot::Cell(cell_offset)) => { + self.code.emit_load_local(value_offset)?; + self.code.emit_u16(Opcode::StoreCell, cell_offset)?; + Some(CompSlot::Cell(cell_offset)) + } + Some(CompSlot::Value(_)) | None => Some(CompSlot::Value(value_offset)), + }; + slot_ids.push(slot); + } + + Ok(slot_ids) + } + + /// Drives one step of the unpack simulation: takes the topmost `Pending` + /// off `sim` and either marks it `Leaf` (for `Name`/`Starred`) or emits + /// `UNPACK_SEQUENCE`/`UNPACK_EX` and recursively processes sub-targets, + /// using `LIFT_TO_TOP` to bring each sub-target to TOS before recursion. + /// + /// Precondition: `sim`'s topmost item is `Pending`. + fn process_unpack_sim(&mut self, sim: &mut Vec>) -> Result<(), CompileError> { + let target = match sim.pop() { + Some(SimItem::Pending(t)) => t, + Some(SimItem::Leaf(_)) => unreachable!("process_unpack_sim called with Leaf at TOS"), + None => unreachable!("process_unpack_sim called on empty sim"), + }; + + match target { + UnpackTarget::Name(ident) => { + sim.push(SimItem::Leaf(ident.namespace_id().as_u16())); + } + UnpackTarget::Starred(inner) => { + sim.push(SimItem::Pending(inner)); + self.process_unpack_sim(sim)?; + } + // `prepare` rejects these in a comprehension target, where a leaf + // has to be a comp-var slot rather than a store to an object. + UnpackTarget::Attr { position, .. } | UnpackTarget::Subscript { position, .. } => { + return Err(CompileError::new( + "internal error: comprehension target must be a name", + *position, + )); + } + UnpackTarget::Tuple { targets, position } => { + // Pick UNPACK_EX vs UNPACK_SEQUENCE based on whether a starred + // sub-target is present (same logic as the regular assignment + // path in `compile_unpack_target`). + let star_idx = targets.iter().position(|t| matches!(t, UnpackTarget::Starred(_))); + self.code.set_location(*position, None); + if let Some(star_idx) = star_idx { + let before = check_unpack_targets(star_idx, *position)?; + let after = check_unpack_targets(targets.len() - star_idx - 1, *position)?; + self.code.emit_u8_u8(Opcode::UnpackEx, before, after)?; + } else { + let count = check_unpack_targets(targets.len(), *position)?; + self.code.emit_u8(Opcode::UnpackSequence, count)?; + } + + // UNPACK pushes sub-targets in reverse source order: sub n-1 + // ends up at the bottom of the new region, sub 0 at TOS. + let base = sim.len(); + for sub in targets.iter().rev() { + sim.push(SimItem::Pending(sub)); + } + + // Process sub-targets in source order. Each lift only moves + // items at or above the source-index, so subs we haven't + // processed yet (lower indices, deeper in the sim) keep + // their position. + let n = targets.len(); + for i in 0..n { + let target_idx = base + (n - 1 - i); + let tos_idx = sim.len() - 1; + if tos_idx > target_idx { + let lift_n = tos_idx - target_idx; + let lift_n_u8 = u8::try_from(lift_n).map_err(|_| { + CompileError::new("comprehension nesting requires lift offset > u8", *position) + })?; + self.code.emit_u8(Opcode::LiftToTop, lift_n_u8)?; + let item = sim.remove(target_idx); + sim.push(item); + } + // Now sub i is at TOS. Recurse to either mark Leaf or + // unpack further. + self.process_unpack_sim(sim)?; + } + } + } + Ok(()) + } + + /// Compiles storage of an unpack target - either a single identifier, nested tuple, or starred. + /// + /// For single identifiers: emits a simple store. + /// For nested tuples: emits `UnpackSequence` (or `UnpackEx` with starred) and recursively + /// handles each sub-target. + fn compile_unpack_target(&mut self, target: &UnpackTarget) -> Result<(), CompileError> { + match target { + UnpackTarget::Name(ident) => { + // Single identifier - just store directly + self.compile_store(ident)?; + } + UnpackTarget::Starred(inner) => { + // `UnpackEx` has already built the list for this slot, so the + // captured value is stored like any other target. + self.compile_unpack_target(inner)?; + } + UnpackTarget::Attr { object, attr, position } => self.emit_attr_store(object, attr, *position)?, + UnpackTarget::Subscript { + container, + index, + position, + } => self.emit_subscript_store(container, index, *position)?, + UnpackTarget::Tuple { targets, position } => { + // Check if there's a starred target + let star_idx = targets.iter().position(|t| matches!(t, UnpackTarget::Starred(_))); + + self.code.set_location(*position, None); + + if let Some(star_idx) = star_idx { + // Has starred target - use UnpackEx + let before = check_unpack_targets(star_idx, *position)?; + let after = check_unpack_targets(targets.len() - star_idx - 1, *position)?; + self.code.emit_u8_u8(Opcode::UnpackEx, before, after)?; + } else { + // No starred target - use UnpackSequence + let count = check_unpack_targets(targets.len(), *position)?; + self.code.emit_u8(Opcode::UnpackSequence, count)?; + } + + // After UnpackSequence/UnpackEx, values are on stack with first item on top + // Store them in order, recursively handling further nesting + for target in targets { + self.compile_unpack_target(target)?; + } + } + } + Ok(()) + } + + /// Compiles a single assignment step, assuming the value to assign is on top of stack. + /// + /// Central per-shape dispatch for assignment stores. Called once per step of a chained + /// assignment, and also by the single-target `Node::SubscriptAssign`/`AttrAssign`/ + /// `UnpackAssign`/`Assign` handlers (after they push the RHS). Keeping this dispatch + /// in one place ensures the store sequences stay in sync across single-target and + /// chained forms. + fn compile_assign_target(&mut self, target: &AssignTarget) -> Result<(), CompileError> { + match target { + AssignTarget::Name(ident) => self.compile_store(ident)?, + AssignTarget::Subscript { + target, + index, + target_position, + } => self.emit_subscript_store(target, index, *target_position)?, + AssignTarget::Attr { + object, + attr, + target_position, + } => self.emit_attr_store(object, attr, *target_position)?, + AssignTarget::Unpack { + targets, + targets_position, + } => self.emit_unpack_store(targets, *targets_position)?, + } + Ok(()) + } + + /// Emits the bytecode for `container[index] = value`, assuming `value` is on top of stack. + /// + /// `StoreSubscr` expects the stack to be `[.., value, container, index]` with `index` + /// on top, so this evaluates `target` (container) and then `index` above the incoming + /// value. Used by both `Node::SubscriptAssign` and chained-assignment subscript steps. + fn emit_subscript_store( + &mut self, + target: &ExprLoc, + index: &ExprLoc, + target_position: CodeRange, + ) -> Result<(), CompileError> { + self.compile_expr(target)?; + self.compile_expr(index)?; + self.code.set_location(target_position, None); + self.code.emit(Opcode::StoreSubscr)?; + Ok(()) + } + + /// Emits the bytecode for `object.attr = value`, assuming `value` is on top of stack. + /// + /// `StoreAttr` expects `[.., value, object]` with `object` on top, so this evaluates + /// `object` above the incoming value. Used by both `Node::AttrAssign` and chained- + /// assignment attribute steps. + fn emit_attr_store( + &mut self, + object: &ExprLoc, + attr: &EitherStr, + target_position: CodeRange, + ) -> Result<(), CompileError> { + let name_id = attr.string_id().expect("attribute name in AST must be interned"); + let name_idx = check_name_index_u16(name_id, target_position)?; + self.compile_expr(object)?; + self.code.set_location(target_position, None); + self.code.emit_u16(Opcode::StoreAttr, name_idx)?; + Ok(()) + } + + /// Emits the bytecode for unpacking assignments (`a, b = value`, `[a, *rest] = value`). + /// + /// Assumes the iterable is already on top of stack, chooses between `UnpackSequence` + /// (no starred target) and `UnpackEx` (exactly one starred target), then stores the + /// unpacked values into each sub-target — recursing through nested tuple patterns. + /// Shared between `Node::UnpackAssign` and chained-assignment unpack steps. + fn emit_unpack_store(&mut self, targets: &[UnpackTarget], targets_position: CodeRange) -> Result<(), CompileError> { + let star_idx = targets.iter().position(|t| matches!(t, UnpackTarget::Starred(_))); + self.code.set_location(targets_position, None); + if let Some(star_idx) = star_idx { + let before = check_unpack_targets(star_idx, targets_position)?; + let after = check_unpack_targets(targets.len() - star_idx - 1, targets_position)?; + self.code.emit_u8_u8(Opcode::UnpackEx, before, after)?; + } else { + let count = check_unpack_targets(targets.len(), targets_position)?; + self.code.emit_u8(Opcode::UnpackSequence, count)?; + } + for t in targets { + self.compile_unpack_target(t)?; + } + Ok(()) + } + + // ======================================================================== + // Statement Helpers + // ======================================================================== + + /// Compiles an assert statement. + fn compile_assert(&mut self, test: &ExprLoc, msg: Option<&ExprLoc>) -> Result<(), CompileError> { + if self.flags.assert_message_annotations { + return self.compile_assert_with_message(test, msg); + } + // Without annotations, compile the ordinary `AssertionError` path. + + // Compile test + self.compile_expr(test)?; + // Jump over raise if truthy + let skip_jump = self.code.emit_jump(Opcode::JumpIfTrue)?; + + // Raise AssertionError + let exc_idx = self + .code + .add_const(Value::Builtin(Builtins::ExcType(ExcType::AssertionError)))?; + self.code.emit_u16(Opcode::LoadConst, exc_idx)?; + + if let Some(msg_expr) = msg { + // Call AssertionError(msg) + self.compile_expr(msg_expr)?; + self.code.emit_u8(Opcode::CallFunction, 1)?; + } else { + // Call AssertionError() + self.code.emit_u8(Opcode::CallFunction, 0)?; + } + + self.code.emit(Opcode::Raise)?; + self.code.patch_jump(skip_jump)?; + Ok(()) + } + + /// Compiles an assert with Monty's introspected failure messages. + /// + /// Bare asserts use fused opcodes. Explicit-message comparisons duplicate + /// operands so failures can format them without eagerly evaluating `msg`. + fn compile_assert_with_message(&mut self, test: &ExprLoc, msg: Option<&ExprLoc>) -> Result<(), CompileError> { + if let Expr::CmpOp { left, op, right } = &test.expr { + self.compile_expr(left)?; + self.compile_expr(right)?; + // The caret/traceback range covers the whole comparison. + self.code.set_location(test.position, None); + if let Some(msg_expr) = msg { + self.code.emit(Opcode::Dup2)?; + self.code.emit(cmp_operator_to_opcode(*op))?; + let pass = self.code.emit_jump(Opcode::JumpIfTrue)?; + // Failure: [lhs, rhs] retained for the message. + self.compile_expr(msg_expr)?; + self.code.set_location(test.position, None); + self.code.emit_u8(Opcode::AssertFailed, assert_flags(Some(*op)))?; + // Success: drop the retained operands. + self.code.patch_jump(pass)?; + self.code.emit(Opcode::Pop)?; + self.code.emit(Opcode::Pop)?; + } else { + self.code.emit_u8(Opcode::Assert, assert_flags(Some(*op)))?; + } + } else { + self.compile_expr(test)?; + self.code.set_location(test.position, None); + if let Some(msg_expr) = msg { + // Keep the falsy test value for the failure message. + let fail = self.code.emit_jump(Opcode::JumpIfFalseOrPop)?; + let end = self.code.emit_jump(Opcode::Jump)?; + self.code.patch_jump(fail)?; + self.compile_expr(msg_expr)?; + self.code.set_location(test.position, None); + self.code.emit_u8(Opcode::AssertFailed, assert_flags(None))?; + self.code.patch_jump(end)?; + } else { + self.code.emit_u8(Opcode::Assert, assert_flags(None))?; + } + } + Ok(()) + } + + /// Compiles f-string parts, returning the number of string parts to concatenate. + /// + /// Each part is compiled to leave a string value on the stack: + /// - `Literal(StringId)`: Push the interned string directly + /// - `Interpolation`: Compile expr, emit FormatValue to convert to string + fn compile_fstring_parts(&mut self, parts: &[FStringPart]) -> Result { + let mut count = 0u16; + + for part in parts { + match part { + FStringPart::Literal(string_id) => { + // Push the interned string as a constant + let const_idx = self.code.add_const(Value::InternString(*string_id))?; + self.code.emit_u16(Opcode::LoadConst, const_idx)?; + count += 1; + } + FStringPart::Interpolation { + expr, + conversion, + format_spec, + debug_prefix, + } => { + // If debug prefix present, push it first + if let Some(prefix_id) = debug_prefix { + let const_idx = self.code.add_const(Value::InternString(*prefix_id))?; + self.code.emit_u16(Opcode::LoadConst, const_idx)?; + count += 1; + } + + // Compile the expression + self.compile_expr(expr)?; + + // A debug expression (`{x=}`) defaults to `repr`, but ONLY + // when it has neither an explicit conversion nor a format + // spec. With a spec (`{x=:.3f}`) the spec applies to the + // value directly (not to its repr string), matching CPython. + let effective_conversion = if debug_prefix.is_some() + && matches!(conversion, ConversionFlag::None) + && format_spec.is_none() + { + ConversionFlag::Repr + } else { + *conversion + }; + + // Emit FormatValue with appropriate flags + let flags = self.compile_format_value(effective_conversion, format_spec.as_ref())?; + self.code.emit_u8(Opcode::FormatValue, flags)?; + count += 1; + } + } + } + + Ok(count) + } + + /// Compiles format value flags and optionally pushes format spec to stack. + /// + /// Returns the flags byte encoding conversion, spec presence, and (for + /// static specs) that the on-stack spec is the encoded `Int` form rather + /// than a string. See [`FORMAT_VALUE_HAS_SPEC`]/[`FORMAT_VALUE_STATIC_SPEC`] + /// for the bit layout. If a format spec is present it's pushed to the + /// stack before the value. + fn compile_format_value( + &mut self, + conversion: ConversionFlag, + format_spec: Option<&FormatSpec>, + ) -> Result { + // Conversion flag: bits 0-1 + let conv_bits = match conversion { + ConversionFlag::None => 0, + ConversionFlag::Str => 1, + ConversionFlag::Repr => 2, + ConversionFlag::Ascii => 3, + }; + + match format_spec { + None => Ok(conv_bits), + Some(FormatSpec::Static(encoded)) => { + // Push the raw encoded form; the static-spec flag tells the + // VM to read it back via decode_format_spec without inspecting + // the Value variant. + let const_idx = self.code.add_const(Value::Int(*encoded))?; + self.code.emit_u16(Opcode::LoadConst, const_idx)?; + Ok(conv_bits | FORMAT_VALUE_HAS_SPEC | FORMAT_VALUE_STATIC_SPEC) + } + Some(FormatSpec::Dynamic(dynamic_parts)) => { + // Compile dynamic format spec parts to build a format spec string + // Then parse it at runtime + let part_count = self.compile_fstring_parts(dynamic_parts)?; + if part_count > 1 { + self.code.emit_u16(Opcode::BuildFString, part_count)?; + } + // Format spec string is now on stack + Ok(conv_bits | FORMAT_VALUE_HAS_SPEC) + } + } + } + + // ======================================================================== + // Exception Handling Compilation + // ======================================================================== + + /// Compiles a return and unwinds all enclosing control blocks. + /// Cleanup runs innermost-first with the return value and enclosing + /// exception state preserved as needed. + fn compile_return(&mut self, expr: Option<&ExprLoc>) -> Result<(), CompileError> { + if let Some(expr) = expr { + self.compile_expr(expr)?; + } else { + self.code.emit(Opcode::LoadNone)?; + } + if self.code.is_dead() { + return Ok(()); + } + + // A pushed or suspended call reports an escaping exception at its + // resume offset. Keep that offset inside any region the return exits. + if expr.is_some_and(return_expr_needs_padding) + && self.fblocks.iter_mut().any(|block| block.region_mut().is_some()) + { + self.code.emit(Opcode::Nop)?; + } + + let popped = self.emit_unwind(self.fblocks.len(), true)?; + self.code.emit(Opcode::ReturnValue)?; + self.restore_fblocks(popped); + Ok(()) + } + + /// Compiles a `try` and its `except`, `else`, or `finally` clauses. + /// Combined forms wrap `try/except/else` in `try/finally`; cleanup copies + /// are emitted per exit and bounded by [`MAX_FINALLY_COPIES`]. + fn compile_try(&mut self, try_block: &'a Try) -> Result<(), CompileError> { + if try_block.finally.is_empty() { + self.compile_try_except(try_block) + } else { + self.compile_try_finally(try_block) + } + } + + /// Compiles separate normal and exceptional copies of a `finally` body. + /// Its protected range includes the trailing jump because a terminal + /// pushed call reports failure at its resume offset. + fn compile_try_finally(&mut self, try_block: &'a Try) -> Result<(), CompileError> { + let Some(stack_depth) = self.code.stack_depth() else { + return Ok(()); + }; + + let region = Region::open(self.code.current_offset(), stack_depth, self.exc_stack_count()); + self.fblocks.push(FBlock::FinallyTry { + region, + finally: &try_block.finally, + }); + + if try_block.handlers.is_empty() { + self.compile_block(&try_block.body)?; + } else { + self.compile_try_except(try_block)?; + } + + let region = self + .fblocks + .pop() + .expect("try/finally compilation should retain its frame block") + .expect_finally_try(); + let normal_jump = self.code.emit_jump(Opcode::Jump)?; + let body_end = self.code.current_offset(); + + // === Exception-path copy === + // A `Cleanup` entry leaves the exception only on `exception_stack`, + // where bare `raise` and `Reraise` read it — nothing to pop here. + let cleanup_start = self.code.current_offset(); + self.code.new_code_region(stack_depth); + self.fblocks.push(FBlock::FinallyEnd); + self.compile_finally_copy(&try_block.finally)?; + self.fblocks + .pop() + .expect("exception-path finally should retain its frame block") + .expect_finally_end(); + self.code.emit(Opcode::Reraise)?; + + // === Fall-through copy === + self.code.patch_jump(normal_jump)?; + self.compile_finally_copy(&try_block.finally)?; + + region.add_entries(body_end, &mut self.code, cleanup_start, HandlerKind::Cleanup) + } + + /// Compiles a protected `try` body, handler dispatch, and unprotected `else`. + /// An enclosing `try/finally` also covers handlers so their failures run + /// its cleanup. + fn compile_try_except(&mut self, try_block: &'a Try) -> Result<(), CompileError> { + let Some(stack_depth) = self.code.stack_depth() else { + return Ok(()); + }; + + let region = Region::open(self.code.current_offset(), stack_depth, self.exc_stack_count()); + self.fblocks.push(FBlock::TryExcept { region }); + self.compile_block(&try_block.body)?; + let region = self + .fblocks + .pop() + .expect("try/except compilation should retain its frame block") + .expect_try_except(); + + // Also keeps terminal-call resume points inside the protected range. + let else_jump = self.code.emit_jump(Opcode::Jump)?; + let body_end = self.code.current_offset(); + + let dispatch_start = self.code.current_offset(); + let mut end_jumps: Vec = Vec::new(); + self.compile_exception_handlers(stack_depth, &try_block.handlers, &mut end_jumps)?; + + // === Else block (runs if no exception) === + self.code.patch_jump(else_jump)?; + if !try_block.or_else.is_empty() { + self.compile_block(&try_block.or_else)?; + } + + // Handler exits skip the `else` block. + for jump in end_jumps { + self.code.patch_jump(jump)?; + } + + region.add_entries(body_end, &mut self.code, dispatch_start, HandlerKind::Consuming) + } + + /// Compiles normal and exceptional exits for a `with` statement. + /// Target binding is protected, while `__exit__` runs outside its own + /// handler region; non-local exits use [`FBlock::With`] cleanup. + fn compile_with( + &mut self, + context: &ExprLoc, + target: Option<&UnpackTarget>, + body: &'a [PreparedNode], + ) -> Result<(), CompileError> { + let Some(stack_depth) = self.code.stack_depth() else { + return Ok(()); + }; + + self.compile_expr(context)?; + self.code.emit(Opcode::BeforeWith)?; + // Keep a pushed `__enter__` call's resume offset outside the body region. + self.code.emit(Opcode::Nop)?; + + // === Body (protected region) === + // The context manager remains below the protected body's operands. + let region = Region::open(self.code.current_offset(), stack_depth + 1, self.exc_stack_count()); + self.fblocks.push(FBlock::With { region }); + // Protect target binding so unpack failures invoke `__exit__`. + if let Some(target) = target { + self.compile_unpack_target(target)?; + } else { + self.code.emit(Opcode::Pop)?; + } + self.compile_block(body)?; + let region = self + .fblocks + .pop() + .expect("with compilation should retain its frame block") + .expect_with(); + // Exclude `__exit__` so its failures cannot re-enter this handler. + let body_end = self.code.current_offset(); + + // Normal exit skips the exception handler. + self.code.emit(Opcode::WithExit)?; + self.code.emit(Opcode::Pop)?; + let end_jump = self.code.emit_jump(Opcode::Jump)?; + + // === Exception handler === + let handler_start = self.code.current_offset(); + // Entry stack: [ctx, exc]. + self.code.new_code_region(stack_depth + 2); + + self.code.emit(Opcode::WithExceptStart)?; + // Stack: [ctx, exc, suppress] + let swallow_jump = self.code.emit_jump(Opcode::JumpIfTrue)?; + // Falsy path: stack = [ctx, exc]. Drop both and re-raise. + self.code.emit(Opcode::Pop)?; + self.code.emit(Opcode::Pop)?; + self.code.emit(Opcode::Reraise)?; + + // Swallow path: drop [ctx, exc] and clear the active exception. + self.code.patch_jump(swallow_jump)?; + self.code.emit(Opcode::Pop)?; + self.code.emit(Opcode::Pop)?; + self.code.emit(Opcode::ClearException)?; + + // === Merge point for the normal-exit and swallowed-exception paths === + self.code.patch_jump(end_jump)?; + + region.add_entries(body_end, &mut self.code, handler_start, HandlerKind::Consuming) + } + + /// Compiles the exception handlers for a try block. + /// + /// Each handler checks if the exception matches its type, and if so, + /// executes the handler body. If no handler matches, the exception is re-raised. + /// + /// The caller is responsible for calling this from a dead-code region; otherwise + /// the attempt to create a new code region will panic. + /// + /// The region is closed at the end of this function, so the caller will need + /// to start a new code region for any code that follows the handlers. + fn compile_exception_handlers( + &mut self, + stack_depth: u16, + handlers: &'a [ExceptHandler], + end_jumps: &mut Vec, + ) -> Result<(), CompileError> { + // Start a new code region for the exception handlers, +1 for + // the exception value pushed by the VM on entry to the handler dispatch + self.code.new_code_region(stack_depth + 1); + + for handler in handlers { + let no_match_jump = if let Some(exc_type) = &handler.exc_type { + // Typed handler: `except ExcType:` or `except ExcType as e:`. + // Stack on entry: [exception]. `CheckExcMatch` peeks the + // exception (doesn't pop it), so [exception] stays on the + // stack across the check on both match and no-match paths. + self.compile_expr(exc_type)?; + self.code.emit(Opcode::CheckExcMatch)?; + Some(self.code.emit_jump(Opcode::JumpIfFalse)?) + } else { + // Bare `except:` (must be the last handler per Python rules). + None + }; + + // Match path: consume exception from the stack and store + // to target if present. + if let Some(name) = &handler.name { + self.compile_store(name)?; + } else { + self.code.emit(Opcode::Pop)?; + } + + // Exceptional exits need the same target cleanup as non-local + // control flow, so the handler body owns a cleanup region. + let region = Region::open(self.code.current_offset(), stack_depth, self.exc_stack_count()); + self.fblocks.push(FBlock::ExceptHandler { + name: handler.name.as_ref(), + region, + }); + self.compile_block(&handler.body)?; + let (name, region) = self + .fblocks + .pop() + .expect("except body should retain its frame block") + .expect_except_handler(); + let body_end = self.code.current_offset(); + + self.compile_clear_handler_name(name)?; + self.code.emit(Opcode::ClearException)?; + end_jumps.push(self.code.emit_jump(Opcode::Jump)?); + + // The runtime already discarded the abandoned handler's exception, + // so just clear the `as` target and propagate the replacement. + let cleanup_start = self.code.current_offset(); + self.code.new_code_region(stack_depth); + self.compile_clear_handler_name(name)?; + self.code.emit(Opcode::Reraise)?; + region.add_entries(body_end, &mut self.code, cleanup_start, HandlerKind::Cleanup)?; + + if let Some(no_match_jump) = no_match_jump { + // No-match landing: stack is [exception]. Falls through into + // the next handler's check (or the post-loop `Reraise`). + self.code.patch_jump(no_match_jump)?; + } + } + + // No handler matched - reraise the exception + self.code.emit(Opcode::Reraise)?; + + Ok(()) + } + + /// Compiles deletion of a variable. + /// + /// At module level, `Local` scope emits `DeleteGlobal` + /// because module-level locals live in the globals array. + /// + /// Function-scope `Local` deletes are limited to the first 256 slots + /// because the only available opcode (`DeleteLocal`) takes a `u8` + /// operand; a wide variant has not been added because slot-255 deletes + /// are essentially unreachable in real code (each `except ... as e` + /// implicitly emits a delete on the bound name, but functions with 256+ + /// locals plus an `except as` are exotic enough that we surface a + /// `SyntaxError` rather than introduce a new opcode just for this). + fn compile_delete(&mut self, target: &Identifier) -> Result<(), CompileError> { + let slot = target.namespace_id().as_u16(); + match target.scope { + NameScope::Local => { + if self.is_module_scope { + self.code.emit_u16(Opcode::DeleteGlobal, slot)?; + } else if let Ok(s) = u8::try_from(slot) { + self.code.emit_u8(Opcode::DeleteLocal, s)?; + } else { + return Err(CompileError::new( + format!( + "cannot delete local variable in function with more than {} locals (slot {slot})", + u16::from(u8::MAX) + 1, + ), + target.position, + )); + } + } + NameScope::Global if self.flags.globals_by_name => { + self.code + .emit_name_op(Opcode::DeleteName, slot, target.name_id, NAME_GLOBAL_ONLY)?; + } + NameScope::Global => { + self.code.emit_u16(Opcode::DeleteGlobal, slot)?; + } + NameScope::Name => { + self.code.emit_name_op(Opcode::DeleteName, slot, target.name_id, 0)?; + } + NameScope::Cell => { + // unbind the cell (CPython's DELETE_DEREF) so a captured + // `except ... as` target reads as unbound after cleanup + self.code.emit_u16(Opcode::DeleteCell, slot)?; + } + NameScope::CompVar => unreachable!("no syntax exists to `del` a comprehension variable"), + } + Ok(()) + } +} + +/// Error that can occur during bytecode compilation. +/// +/// These are typically limit violations that can't be represented in the bytecode +/// format (e.g., too many arguments, too many local variables), or import errors +/// detected at compile time. +#[derive(Debug, Clone)] +pub struct CompileError { + /// Error message describing the issue. + message: Cow<'static, str>, + /// Source location where the error occurred. + position: CodeRange, + /// Exception type to use (defaults to SyntaxError). + exc_type: ExcType, +} + +impl CompileError { + /// Creates a new compile error with the given message and position. + /// + /// Defaults to `SyntaxError` exception type. + pub(super) fn new(message: impl Into>, position: CodeRange) -> Self { + Self { + message: message.into(), + position, + exc_type: ExcType::SyntaxError, + } + } + + /// Creates a compile error that surfaces as `NotImplementedError`. + /// + /// Used for Python constructs Monty deliberately rejects rather than + /// supports (e.g. reassigning a reserved module dunder), matching the + /// `NotImplementedError` Monty raises for other unsupported syntax. + pub(super) fn not_implemented(message: impl Into>, position: CodeRange) -> Self { + Self { + message: message.into(), + position, + exc_type: ExcType::NotImplementedError, + } + } + + /// Converts to the exception an `eval()` / `exec()` call raises for its + /// snippet; see `ParseError::into_run_error`. + pub(crate) fn into_run_error(self, source: &str) -> RunError { + match self.exc_type { + ExcType::SyntaxError => syntax_error_in_snippet(&self.message, self.position, source), + exc_type => SimpleException::new_msg(exc_type, self.message) + .with_snippet_position(self.position, source) + .into(), + } + } + + /// Converts this compile error into a Python exception. + /// + /// Syntax errors omit the frame name; unsupported constructs report a + /// runtime-style location with the stored exception type and message. + pub fn into_python_exc(self, filename: &str, source: &str) -> MontyException { + let mut source_map = SourceMap::new(source); + let mut frame = if self.exc_type == ExcType::SyntaxError { + // SyntaxError uses different format: no `, in ` + StackFrame::from_position_syntax_error(self.position, filename, &mut source_map) + } else { + StackFrame::from_position(self.position, filename, &mut source_map) + }; + // CPython doesn't show carets for module not found errors + if self.exc_type == ExcType::ModuleNotFoundError { + frame.hide_caret = true; + } + MontyException::with_traceback(self.exc_type, Some(self.message.into_owned()), vec![frame]) + } +} + +// ============================================================================ +// Operator Mapping Functions +// ============================================================================ + +/// Maps a binary `Operator` to its corresponding `Opcode`. +fn operator_to_opcode(op: &Operator) -> Opcode { + match op { + Operator::Add => Opcode::BinaryAdd, + Operator::Sub => Opcode::BinarySub, + Operator::Mult => Opcode::BinaryMul, + Operator::Div => Opcode::BinaryDiv, + Operator::FloorDiv => Opcode::BinaryFloorDiv, + Operator::Mod => Opcode::BinaryMod, + Operator::Pow => Opcode::BinaryPow, + Operator::MatMult => Opcode::BinaryMatMul, + Operator::LShift => Opcode::BinaryLShift, + Operator::RShift => Opcode::BinaryRShift, + Operator::BitOr => Opcode::BinaryOr, + Operator::BitXor => Opcode::BinaryXor, + Operator::BitAnd => Opcode::BinaryAnd, + // And/Or are handled separately for short-circuit evaluation + Operator::And | Operator::Or => { + unreachable!("And/Or operators handled in compile_binary_op") + } + } +} + +/// Maps an `Operator` to its in-place (augmented assignment) `Opcode`. +/// +/// Returns `None` for `MatMult`: ordinary `@` supports user slots, but `@=` is +/// still rejected. Returns `Some(opcode)` for all other valid augmented assignment operators. +/// +/// # Panics +/// +/// Panics if called with `And` or `Or` operators, which cannot be used in augmented +/// assignments (this would be a parser bug). +fn operator_to_inplace_opcode(op: &Operator) -> Option { + match op { + Operator::Add => Some(Opcode::InplaceAdd), + Operator::Sub => Some(Opcode::InplaceSub), + Operator::Mult => Some(Opcode::InplaceMul), + Operator::Div => Some(Opcode::InplaceDiv), + Operator::FloorDiv => Some(Opcode::InplaceFloorDiv), + Operator::Mod => Some(Opcode::InplaceMod), + Operator::Pow => Some(Opcode::InplacePow), + Operator::BitAnd => Some(Opcode::InplaceAnd), + Operator::BitOr => Some(Opcode::InplaceOr), + Operator::BitXor => Some(Opcode::InplaceXor), + Operator::LShift => Some(Opcode::InplaceLShift), + Operator::RShift => Some(Opcode::InplaceRShift), + Operator::MatMult => None, + Operator::And | Operator::Or => { + unreachable!("And/Or operators cannot be used in augmented assignment") + } + } +} + +/// Maps a `CmpOperator` to its corresponding `Opcode`. +fn cmp_operator_to_opcode(op: CmpOperator) -> Opcode { + match op { + CmpOperator::Eq => Opcode::CompareEq, + CmpOperator::NotEq => Opcode::CompareNe, + CmpOperator::Lt => Opcode::CompareLt, + CmpOperator::LtE => Opcode::CompareLe, + CmpOperator::Gt => Opcode::CompareGt, + CmpOperator::GtE => Opcode::CompareGe, + CmpOperator::Is => Opcode::CompareIs, + CmpOperator::IsNot => Opcode::CompareIsNot, + CmpOperator::In => Opcode::CompareIn, + CmpOperator::NotIn => Opcode::CompareNotIn, + } +} + +/// Returns `true` if any item in the sequence is a PEP 448 unpack (`*expr`). +/// +/// Used to choose between the fast single-`Build*(N)` path and the generalized +/// incremental `Build*(0)` + `ListAppend`/`ListExtend` (or `SetAdd`/`SetExtend`) path. +/// Only the generalized path is needed when at least one `Unpack` variant is present. +fn has_unpack_seq(items: &[SequenceItem]) -> bool { + items.iter().any(|i| matches!(i, SequenceItem::Unpack(_))) +} + +/// Returns `true` if any item in the dict literal is a PEP 448 `**expr` unpack. +/// +/// Used to choose between the fast single-`BuildDict(N)` path and the generalized +/// incremental `BuildDict(0)` + `DictSetItem`/`DictUpdate` path. +fn has_unpack_dict(items: &[DictItem]) -> bool { + items.iter().any(|i| matches!(i, DictItem::Unpack(_))) +} diff --git a/crates/bashkit-monty/src/bytecode/mod.rs b/crates/bashkit-monty/src/bytecode/mod.rs new file mode 100644 index 000000000..502524cf1 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/mod.rs @@ -0,0 +1,51 @@ +//! Bytecode VM module for Monty. +//! +//! This module contains the bytecode representation, compiler, and virtual machine +//! for executing Python code. The bytecode VM replaces the tree-walking interpreter +//! with a stack-based execution model. +//! +//! # Module Structure +//! +//! - `op` - Opcode enum definitions +//! - `code` - Code object containing bytecode and metadata +//! - `builder` - CodeBuilder for emitting bytecode during compilation +//! - `compiler` - AST to bytecode compiler +//! - `vm` - Virtual machine for bytecode execution + +mod builder; +mod code; +mod compiler; +mod op; +mod pattern; +mod vm; + +pub(crate) use builder::CodeBuilder; +pub use code::Code; +pub use compiler::Compiler; +#[cfg(test)] +pub(crate) use op::opcode_fingerprint; +pub(crate) use op::{NAME_CALLABLE, NAME_GLOBAL_ONLY, Opcode}; +pub(crate) use vm::{ + CallResult, ContainsVM, FrameNamespace, PendingLookupEffect, RecursionToken, RunReentryGuard, unpack_exact, +}; +pub use vm::{FrameExit, VM, VMSnapshot}; + +/// Module-level dunder names Monty exposes with fixed values for CPython +/// compatibility (e.g. so `if __name__ == '__main__':` works). +/// +/// Monty has no module object or `globals()` dict, so these are not real +/// namespace entries: they are resolved on *read* when the global slot is +/// `Undefined` (see `VM::module_dunder`, whose match must stay in sync with +/// this list) and are read-only — assigning one at module or global scope is +/// rejected at compile time with a `NotImplementedError` (see +/// `Compiler::compile_store`) rather than being silently ignored. +/// Function-local variables that happen to share these names are unaffected. +pub(crate) const RESERVED_MODULE_DUNDERS: [&str; 7] = [ + "__name__", + "__debug__", + "__doc__", + "__annotations__", + "__spec__", + "__package__", + "__file__", +]; diff --git a/crates/bashkit-monty/src/bytecode/op.rs b/crates/bashkit-monty/src/bytecode/op.rs new file mode 100644 index 000000000..e91dd2afd --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/op.rs @@ -0,0 +1,1117 @@ +//! Opcode definitions for the bytecode VM. +//! +//! Bytecode is stored as raw `Vec` for cache efficiency. The `Opcode` enum is a pure +//! discriminant with no data - operands are fetched separately from the byte stream. +//! +//! # Operand Encoding +//! +//! - No suffix, 0 bytes: `BinaryAdd`, `Pop`, `LoadNone` +//! - No suffix, 1 byte (u8/i8): `LoadLocal`, `StoreLocal`, `LoadSmallInt` +//! - `W` suffix, 2 bytes (u16/i16): `LoadLocalW`, `Jump`, `LoadConst` +//! - Compound (multiple operands): `CallFunctionKw` (u8 + u8), `MakeClosure` (u16 + u8 + u8), +//! `LoadName` (u16 + u16 + u8) + +#[cfg(test)] +use strum::IntoEnumIterator; +use strum::{EnumIter, FromRepr}; + +use crate::{bytecode::builder::RelativeOffset, expressions::CmpOperator}; + +/// `FormatValue` flag: a format spec was pushed onto the stack ahead of the +/// value. When set, the VM pops the spec before the value. See `Opcode::FormatValue`. +pub const FORMAT_VALUE_HAS_SPEC: u8 = 0x04; + +/// `FormatValue` flag: the on-stack format spec is the pre-encoded `Int` form +/// produced by [`crate::fstring::encode_format_spec`], not a string to be +/// parsed at runtime. Only meaningful when [`FORMAT_VALUE_HAS_SPEC`] is also +/// set. The compiler pairs this bit with a `LoadConst` of `Value::Int(encoded)` +/// emitted before the value. +pub const FORMAT_VALUE_STATIC_SPEC: u8 = 0x08; + +/// `Assert`/`AssertFailed` flag: the assert is a fused comparison. When set, +/// the low nibble of the flags operand holds [`CmpOperator::as_operand`] and +/// the opcode pops two comparison operands instead of one test value. +pub const ASSERT_CMP_FLAG: u8 = 0x10; + +/// `MatchShape` flag: test for a mapping (`dict` and its subclasses) rather +/// than a sequence (`list`, `tuple`, `range`, `deque` - never `str`/`bytes`). +pub const MATCH_SHAPE_MAPPING: u8 = 0x01; + +/// `MatchShape` flag: the u16 length operand is a lower bound (a sequence +/// pattern with a star, or a mapping pattern) rather than an exact length. +pub const MATCH_SHAPE_MIN_LEN: u8 = 0x02; + +/// `MatchKeys` mode: look every key up and push the values tuple (or `None`) +/// plus a match flag, leaving the subject and keys tuple in place. +pub const MATCH_KEYS_VALUES: u8 = 0; + +/// `MatchKeys` mode: pop the subject and keys and push a new `dict` of the +/// entries the keys did not consume, for a `**rest` capture. +pub const MATCH_KEYS_REST: u8 = 1; + +/// Encodes an optional fused comparison into the `Assert`/`AssertFailed` +/// flags operand: `ASSERT_CMP_FLAG | as_operand` when present, `0` when not. +pub fn assert_flags(cmp_op: Option) -> u8 { + cmp_op.map_or(0, |op| ASSERT_CMP_FLAG | op.as_operand()) +} + +/// Decodes [`assert_flags`]; `None` for bytes it can never produce (corrupt +/// or hand-built bytecode — callers treat that as an internal error). +#[expect( + clippy::option_option, + reason = "outer = valid encoding, inner = fused comparison present" +)] +pub fn decode_assert_flags(flags: u8) -> Option> { + if flags == 0 { + Some(None) + } else if flags & ASSERT_CMP_FLAG != 0 { + // `!ASSERT_CMP_FLAG` keeps any stray high bits so they fail decoding. + CmpOperator::from_repr(flags & !ASSERT_CMP_FLAG).map(Some) + } else { + None + } +} + +/// Opcode discriminant - just identifies the instruction type. +/// +/// Operands (if any) follow in the bytecode stream and are fetched separately. +/// With `#[repr(u8)]`, each opcode is exactly 1 byte. Uses `strum::FromRepr` for +/// efficient byte-to-opcode conversion (bounds check + transmute). +/// +/// Opcode bytes are part of Monty's serialized `Code` format. Explicit +/// discriminants prevent source reordering or removal from changing that format +/// accidentally; intentional renumbering requires a dump-format version bump. +#[repr(u8)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumIter, FromRepr)] +pub enum Opcode { + // === Stack Operations (no operand) === + /// Discard top of stack. + Pop = 0, + /// Duplicate top of stack. + Dup = 1, + /// Swap top two: [a, b] -> [b, a]. + Rot2 = 2, + /// Rotate top three: [a, b, c] -> [c, a, b]. + Rot3 = 3, + + // === Constants & Literals === + /// Push constant from pool. Operand: u16 const_id. + LoadConst = 4, + /// Push None. + LoadNone = 5, + /// Push True. + LoadTrue = 6, + /// Push False. + LoadFalse = 7, + /// Push small integer (-128 to 127). Operand: i8. + LoadSmallInt = 8, + + // === Variables === + // Specialized no-operand versions for common slots (hot path) + /// Push local slot 0 (often 'self'). + LoadLocal0 = 9, + /// Push local slot 1. + LoadLocal1 = 10, + /// Push local slot 2. + LoadLocal2 = 11, + /// Push local slot 3. + LoadLocal3 = 12, + // General versions with operand + /// Push local variable. Operand: u8 slot. + LoadLocal = 13, + /// Push local (wide, slot > 255). Operand: u16 slot. + LoadLocalW = 14, + /// Pop and store to local. Operand: u8 slot. + StoreLocal = 15, + /// Store local (wide). Operand: u16 slot. + StoreLocalW = 16, + /// Push from global namespace. Operand: u16 slot. + LoadGlobal = 17, + /// Store to global. Operand: u16 slot. + StoreGlobal = 18, + /// Load from closure cell. Operand: u16 slot. + LoadCell = 19, + /// Store to closure cell. Operand: u16 slot. + StoreCell = 20, + /// Delete local variable. Operand: u8 slot. + DeleteLocal = 21, + /// Load global in call context: pushes an external function for undefined names + /// instead of yielding `NameLookup`. Operands: u16 slot, u16 name_id. + /// + /// Used when compiling function calls like `foo()` where `foo` is a global. + /// If the variable is defined, behaves identically to `LoadGlobal`. + /// If undefined, pushes an `ExtFunction` value so execution continues to `CallFunction`, + /// which naturally yields `FunctionCall` instead of `NameLookup`. + /// The name_id is encoded in the operand because global and local slot indices + /// belong to different namespaces — using the current frame's local_names would + /// return the wrong name when called from inside a function. + LoadGlobalCallable = 22, + + // === Binary Operations (no operand) === + /// Add: a + b. + BinaryAdd = 23, + /// Subtract: a - b. + BinarySub = 24, + /// Multiply: a * b. + BinaryMul = 25, + /// Divide: a / b. + BinaryDiv = 26, + /// Floor divide: a // b. + BinaryFloorDiv = 27, + /// Modulo: a % b. + BinaryMod = 28, + /// Power: a ** b. + BinaryPow = 29, + /// Bitwise AND: a & b. + BinaryAnd = 30, + /// Bitwise OR: a | b. + BinaryOr = 31, + /// Bitwise XOR: a ^ b. + BinaryXor = 32, + /// Left shift: a << b. + BinaryLShift = 33, + /// Right shift: a >> b. + BinaryRShift = 34, + /// Matrix multiply: a @ b. + BinaryMatMul = 35, + + // === Comparison Operations (no operand) === + /// Equal: a == b. + CompareEq = 36, + /// Not equal: a != b. + CompareNe = 37, + /// Less than: a < b. + CompareLt = 38, + /// Less than or equal: a <= b. + CompareLe = 39, + /// Greater than: a > b. + CompareGt = 40, + /// Greater than or equal: a >= b. + CompareGe = 41, + /// Identity: a is b. + CompareIs = 42, + /// Not identity: a is not b. + CompareIsNot = 43, + /// Membership: a in b. + CompareIn = 44, + /// Not membership: a not in b. + CompareNotIn = 45, + + // === Unary Operations (no operand) === + /// Logical not: not a. + UnaryNot = 46, + /// Negation: -a. + UnaryNeg = 47, + /// Positive: +a. + UnaryPos = 48, + /// Bitwise invert: ~a. + UnaryInvert = 49, + + // === In-place Operations (no operand) === + /// In-place add: a += b. + InplaceAdd = 50, + /// In-place subtract: a -= b. + InplaceSub = 51, + /// In-place multiply: a *= b. + InplaceMul = 52, + /// In-place divide: a /= b. + InplaceDiv = 53, + /// In-place floor divide: a //= b. + InplaceFloorDiv = 54, + /// In-place modulo: a %= b. + InplaceMod = 55, + /// In-place power: a **= b. + InplacePow = 56, + /// In-place bitwise AND: a &= b. + InplaceAnd = 57, + /// In-place bitwise OR: a |= b. + InplaceOr = 58, + /// In-place bitwise XOR: a ^= b. + InplaceXor = 59, + /// In-place left shift: a <<= b. + InplaceLShift = 60, + /// In-place right shift: a >>= b. + InplaceRShift = 61, + + // === Collection Building === + /// Pop n items, build list. Operand: u16 count. + BuildList = 62, + /// Pop n items, build tuple. Operand: u16 count. + BuildTuple = 63, + /// Pop 2n items (k/v pairs), build dict. Operand: u16 count. + BuildDict = 64, + /// Pop n items, build set. Operand: u16 count. + BuildSet = 65, + /// Format a value for f-string interpolation. Operand: u8 flags. + /// + /// Flags encoding (see [`FORMAT_VALUE_HAS_SPEC`]/[`FORMAT_VALUE_STATIC_SPEC`]): + /// - bits 0-1: conversion (0=none, 1=str, 2=repr, 3=ascii) + /// - bit 2 ([`FORMAT_VALUE_HAS_SPEC`]): a format spec was pushed before + /// the value + /// - bit 3 ([`FORMAT_VALUE_STATIC_SPEC`]): the on-stack spec is the + /// pre-encoded `Int` form rather than a string. Only meaningful when + /// bit 2 is set + /// + /// Pops the value (and optionally format spec), pushes the formatted string. + FormatValue = 66, + /// Pop n parts, concatenate for f-string. Operand: u16 count. + BuildFString = 67, + /// Build a slice object from stack values. No operand. + /// + /// Pops 3 values from stack: step, stop, start (TOS order). + /// Each value can be None (for default) or an integer. + /// Creates a `HeapData::Slice` and pushes a `Value::Ref` to it. + BuildSlice = 68, + /// Pop iterable, pop list, extend list with iterable items. + /// + /// Used for `*args` unpacking: builds a list of positional args, + /// then extends it with unpacked iterables. + ListExtend = 69, + /// Pop TOS (list), push tuple containing the same elements. + /// + /// Used after building the args list to create the final args tuple + /// for `CallFunctionEx`. + ListToTuple = 70, + /// Pop mapping, pop dict, update dict with mapping. Operand: u16 func_name_id. + /// + /// Used for `**kwargs` unpacking. The func_name_id is used for error messages + /// when the mapping contains non-string keys. + DictMerge = 71, + + // === Comprehension Building === + /// Append TOS to list for comprehension. Operand: u8 depth (number of iterators). + /// + /// Stack: [..., list, iter1, ..., iterN, value] -> [..., list, iter1, ..., iterN] + /// Pops value (TOS), appends to list at stack position (len - 2 - depth). + /// Depth equals the number of nested iterators (generators) in the comprehension. + ListAppend = 72, + /// Add TOS to set for comprehension. Operand: u8 depth (number of iterators). + /// + /// Stack: [..., set, iter1, ..., iterN, value] -> [..., set, iter1, ..., iterN] + /// Pops value (TOS), adds to set at stack position (len - 2 - depth). + /// May raise TypeError if value is unhashable. + SetAdd = 73, + /// Set dict[key] = value for comprehension. Operand: u8 depth (number of iterators). + /// + /// Stack: [..., dict, iter1, ..., iterN, key, value] -> [..., dict, iter1, ..., iterN] + /// Pops value (TOS) and key (TOS-1), sets dict[key] = value. + /// Dict is at stack position (len - 3 - depth). + /// May raise TypeError if key is unhashable. + DictSetItem = 74, + + // === Subscript & Attribute === + /// a[b]: pop index, pop obj, push result. + BinarySubscr = 75, + /// a[b] = c: pop value, pop index, pop obj. + StoreSubscr = 76, + // NOTE: DeleteSubscr removed - `del` statement not supported by parser + /// Pop obj, push obj.attr. Operand: u16 name_id. + LoadAttr = 77, + /// Pop module, push module.attr for `from ... import`. Operand: u16 name_id. + /// + /// Missing attributes raise `ImportError` using the frame's `import_from_module`: + /// host-provided values need not be `Module`s. + LoadAttrImport = 78, + /// Pop value, pop obj, set obj.attr. Operand: u16 name_id. + StoreAttr = 79, + // NOTE: DeleteAttr removed - `del` statement not supported by parser + + // === Function Calls === + /// Call TOS with n positional args. Operand: u8 arg_count. + CallFunction = 80, + /// Call a builtin function directly. Operands: u8 builtin_id, u8 arg_count. + /// + /// The builtin_id is the discriminant of `BuiltinsFunctions` (via `FromRepr`). + /// This is an optimization over `LoadConst + CallFunction` that avoids: + /// - Constant pool lookup + /// - Pushing/popping the callable on the stack + /// - Runtime type dispatch in call_function + CallBuiltinFunction = 81, + /// Call a builtin type constructor directly. Operands: u8 type_id, u8 arg_count. + /// + /// The type_id is the discriminant of `BuiltinsTypes` (via `FromRepr`). + /// This is an optimization for type constructors like `list()`, `int()`, `str()`. + CallBuiltinType = 82, + /// Call with positional and keyword args. + /// + /// Operands: u8 pos_count, u8 kw_count, then kw_count u16 name indices. + /// + /// Stack: [callable, pos_args..., kw_values...] + /// After the two count bytes, there are kw_count little-endian u16 values, + /// each being a StringId index for the corresponding keyword argument name. + CallFunctionKw = 83, + /// Call attribute on object. Operands: u16 name_id, u8 arg_count. + /// + /// This is used for both method calls (`obj.method(args)`) and module + /// attribute calls (`module.func(args)`). The attribute is looked up + /// on the object and called with the given arguments. + CallAttr = 84, + /// Call attribute with keyword args. Operands: u16 name_id, u8 pos_count, u8 kw_count, then kw_count u16 name indices. + /// + /// Stack: [obj, pos_args..., kw_values...] + /// After the operands, there are kw_count little-endian u16 values, + /// each being a StringId index for the corresponding keyword argument name. + CallAttrKw = 85, + /// Call a defined function with *args tuple and **kwargs dict. Operand: u8 flags. + /// + /// Flags: + /// - bit 0: has kwargs dict on stack + /// + /// Stack layout (bottom to top): + /// - callable + /// - args tuple + /// - kwargs dict (if flag bit 0 set) + /// + /// Used for calls with `*args` and/or `**kwargs` unpacking. + CallFunctionExtended = 86, + /// Call attribute with *args tuple and **kwargs dict. Operands: u16 name_id, u8 flags. + /// + /// Flags: + /// - bit 0: has kwargs dict on stack + /// + /// Stack layout (bottom to top): + /// - receiver object + /// - args tuple + /// - kwargs dict (if flag bit 0 set) + /// + /// Used for method calls with `*args` and/or `**kwargs` unpacking. + CallAttrExtended = 87, + + // === Control Flow === + /// Unconditional relative jump. Operand: i16 offset. + Jump = 88, + /// Jump if TOS truthy, always pop. Operand: i16 offset. + JumpIfTrue = 89, + /// Jump if TOS falsy, always pop. Operand: i16 offset. + JumpIfFalse = 90, + /// Jump if TOS truthy (keep), else pop. Operand: i16 offset. + JumpIfTrueOrPop = 91, + /// Jump if TOS falsy (keep), else pop. Operand: i16 offset. + JumpIfFalseOrPop = 92, + + // === Iteration === + /// Convert TOS to iterator. + GetIter = 93, + /// Advance iterator or jump to end. Operand: i16 offset. + ForIter = 94, + + // === Function Definition === + /// Create function object. Operand: u16 func_id. + MakeFunction = 95, + /// Create closure. Operands: u16 func_id, u8 cell_count. + MakeClosure = 96, + + // === Exception Handling === + // Note: No SetupTry/PopExceptHandler - we use static exception_table + /// Raise TOS as exception. + Raise = 97, + // NOTE: RaiseFrom removed - `raise ... from ...` not supported by parser + /// Re-raise current exception (bare `raise`). + Reraise = 98, + /// Clear current_exception when exiting except block. + ClearException = 99, + /// Check if exception matches type for except clause. + /// + /// Stack: [..., exception, exc_type] -> [..., exception, bool] + /// Validates that exc_type is a valid exception type (ExcType or tuple of ExcTypes). + /// If invalid, raises TypeError. If valid, pushes True if exception matches, else False. + CheckExcMatch = 100, + + // === Return === + /// Return TOS from function. + ReturnValue = 101, + + // === Async/Await === + /// Await the TOS value. + /// + /// Handles `ExternalFuture`, `Coroutine`, and `GatherFuture` awaitables. + /// For `ExternalFuture`: if resolved, pushes result; if pending, blocks task. + /// For `Coroutine`: validates state is `New`, then starts execution. + /// For `GatherFuture`: spawns all coroutines as tasks and blocks until completion. + /// + /// Raises `TypeError` if TOS is not awaitable. + /// Raises `RuntimeError` if coroutine/future has already been awaited. + Await = 102, + + // === Unpacking === + /// Unpack TOS into n values. Operand: u8 count. + UnpackSequence = 103, + /// Unpack with *rest. Operands: u8 before, u8 after. + UnpackEx = 104, + + // === Special === + /// No operation (for patching/alignment). + Nop = 105, + + // === Module Operations === + /// Load a top-level module. Operand: u16 module-name StringId. + /// Pushes a built-in module or suspends with an import OS call for the host's value. + LoadModule = 106, + /// Pop a module, push its submodule. Operands: u16 attribute ID, u16 dotted-path ID. + /// Missing submodules raise `ModuleNotFoundError`; built-ins add "is not a package". + /// Saves the path as the frame's `import_from_module` for subsequent `LoadAttrImport`s. + LoadSubmodule = 107, + /// Duplicate the top two stack values, preserving order: `[a, b] -> [a, b, a, b]`. + /// + Dup2 = 108, + /// Delete global variable (set to Undefined). Operand: u16 slot. + /// + DeleteGlobal = 109, + + /// Pop a mapping, silently merge into the dict at `depth`. Operand: u8 depth. + /// + /// Used for `**expr` unpack inside dict literals, where later keys overwrite earlier ones + /// (unlike `DictMerge` which raises `TypeError` on duplicate keys). + /// + /// Stack: [..., dict, iter1, ..., iterN, mapping] -> [..., dict, iter1, ..., iterN] + /// Pops mapping (TOS), merges into dict at stack position `len - 2 - depth`. + /// Raises `TypeError` if `mapping` is not a dict. + DictUpdate = 110, + /// Pop an iterable, add all items to set at `depth`. Operand: u8 depth. + /// + /// Used for `*expr` unpack inside set literals (e.g., `{*a, 1}`). + /// Follows the same depth convention as `ListAppend`/`SetAdd`. + /// + /// Stack: [..., set, iter1, ..., iterN, iterable] -> [..., set, iter1, ..., iterN] + /// Pops iterable (TOS), adds each item to set at stack position `len - 2 - depth`. + /// Raises `TypeError` if iterable is not iterable. + SetExtend = 111, + + // === Context Managers === + /// Enter a context manager: call `__enter__` on TOS, push the result, keep + /// the context manager underneath for the eventual `__exit__` call. + /// + /// Stack: [..., ctx] -> [..., ctx, value] + /// + /// Emitted by the compiler at the head of a `with` block. The context + /// manager stays on the stack across the body so the matching `WithExit` + /// or `WithExceptStart` can find it. Calls `py_enter` on the heap object, + /// raising `AttributeError` for objects that don't implement the protocol. + BeforeWith = 112, + /// Normal exit from a `with` block: call `__exit__(None, None, None)` on TOS, + /// pop the context manager, and push the result of the call. + /// + /// Stack: [..., ctx] -> [..., result] + /// + /// The compiler emits a trailing `Pop` to discard the result — splitting the + /// "call + discard" into two opcodes keeps the call shape compatible with + /// `__exit__` implementations that yield `OsCall`/`External`/`MethodCall` + /// (the host's resume push lands as the `result`, which `Pop` then drops). + WithExit = 113, + /// Exception path of a `with` block: call `__exit__(type(exc), exc, None)` + /// and push the truthiness of the result so the compiler can branch on + /// whether to suppress the exception. + /// + /// Stack: [..., ctx, exc] -> [..., ctx, exc, suppress] + /// + /// The exception is the value pushed onto the operand stack on entry to + /// the with-block's exception handler region (analogous to `Try`). The + /// compiler-emitted control flow following this opcode pops both `ctx` and + /// `exc` and either swallows (via `ClearException`) or `Reraise`s based on + /// the `suppress` bool. + WithExceptStart = 114, + + // === Comprehension Helpers === + /// Move the value at `TOS - n` to TOS, shifting items above it down by one. + /// Operand: u8 n. + /// + /// Used by the comprehension compiler to bring a nested-tuple sub-target + /// up to TOS so it can be `UnpackSequence`-d (UnpackSequence only operates + /// on TOS). `n = 0` is a no-op. + /// + /// At runtime, implemented as a single `Vec::rotate_left(1)` over the + /// affected slice, so cost is O(n) shifts but n is bounded by the + /// comprehension's nesting depth (almost always tiny). + LiftToTop = 115, + /// Raise `UnboundLocalError: cannot access local variable 'NAME' where + /// it is not associated with a value`. Operand: u16 name_id. + /// + /// Emitted by the comprehension compiler at sites where static analysis + /// proves a comp-target read happens before the corresponding `for` + /// assigns it — e.g. `[x for x in [1] for _ in [late] for late in [[2]]]` + /// where `late` is read in an earlier generator's iter expression. + /// The opcode carries the target's name inline so sibling comprehensions + /// that reuse comp-var slots still report the right variable name in the + /// error. + RaiseUnboundLocal = 116, + /// Method-call variant of [`Opcode::DictMerge`]: same stack effect, same + /// duplicate-key semantics, but the error wording is qualified with the + /// receiver's Python type — e.g. `list.sort()` instead of bare `sort()`. + /// + /// Emitted by the compiler for `CallAttrExtended` paths where the receiver + /// is at known stack depth 4 below TOS at the time the op runs + /// (`[receiver, args_tuple, kwargs_dict, mapping]`). Matches CPython's + /// `obj.method() got multiple values for keyword argument 'X'` form, + /// which CPython produces because it has the bound method's `__qualname__` + /// available — we synthesise the equivalent by peeking the receiver. + MethodDictMerge = 117, + + // Both assert opcodes use `assert_flags`; `ASSERT_CMP_FLAG` selects the + // fused-comparison form and the low nibble stores the comparison operator. + /// Fused bare `assert`: stack [..., test] -> [...], or with + /// `ASSERT_CMP_FLAG` [..., lhs, rhs] -> [...]. Falls through on success; + /// failures raise `AssertionError` with the operand repr(s), except + /// literal `False` which has no detail. Comparison errors match `Compare*`. + Assert = 118, + /// Raise for failed `assert test, msg`: stack [..., test, msg] -> raises, + /// or with `ASSERT_CMP_FLAG` [..., lhs, rhs, msg] -> raises. The message + /// comes first, with introspected detail appended when available. + AssertFailed = 119, + /// Allocate a closure cell initialized to `Undefined` and push its reference. + /// + /// Used for captured targets in inlined comprehensions. + BuildCell = 120, + /// Unbind a closure cell's contents (CPython's `DELETE_DEREF`): later + /// loads raise the free-variable `NameError`. Emitted by the implicit + /// cleanup of a captured `except ... as` target. Operand: u16 slot. + DeleteCell = 121, + /// Push a name resolved at runtime through the frame's namespace: locals + /// dict → globals (slot array or dict) → builtins → module dunders and + /// host lookup (slot globals only) → `NameError`. Operands: u16 slot, + /// u16 name_id, u8 flags (`NAME_*`). The slot is the session global slot + /// for `name_id`, so with slot globals the tail is exactly `LoadGlobal` / + /// `LoadGlobalCallable`; unused with dict globals. + LoadName = 122, + /// Pop and bind a name through the frame's namespace. Operands as `LoadName`. + StoreName = 123, + /// Unbind a name through the frame's namespace; `NameError` if absent. + /// Operands as `LoadName`. + DeleteName = 124, + + // === Pattern matching (`match` statements) === + /// Shape test for sequence and mapping patterns: `[subject] -> [subject, bool]`. + /// Operands: u16 length, u8 flags (`MATCH_SHAPE_MAPPING`, `MATCH_SHAPE_MIN_LEN`). + MatchShape = 125, + /// Mapping-pattern key lookup. Operand: u8 mode. `MATCH_KEYS_VALUES`: + /// `[subject, keys] -> [subject, keys, values_or_None, bool]`; + /// `MATCH_KEYS_REST`: `[subject, keys] -> [rest_dict]`. + MatchKeys = 126, + /// Class-pattern check: `[subject, cls, kwd_names] -> [subject, cls, names_or_None, bool]`, + /// where `names` are the attributes the sub-patterns read (`None` entries + /// stand for the subject itself). Operand: u8 count of positional + /// sub-patterns, resolved via `__match_args__`. + MatchClass = 127, + /// Reads one class-pattern attribute: `[subject, cls, names] -> [subject, cls, names, value, bool]`. + /// Operand: u8 index into `names`. May suspend for a host lookup. + MatchAttr = 128, + /// Move TOS beneath the `n` items below it: `[a, b, c, v]` with `n = 3` + /// becomes `[v, a, b, c]`. Operand: u8 n. The inverse of `LiftToTop`; the + /// pattern compiler uses it to park a capture under the pattern's temporaries. + SinkTop = 129, +} + +/// `LoadName` flag: the load is in call position, so an unresolved name under +/// slot globals pushes an external function (see `LoadGlobalCallable`) rather +/// than yielding `NameLookup`. Ignored under dict globals. +pub(crate) const NAME_CALLABLE: u8 = 0x01; +/// `*Name` flag: skip the frame's locals dict — a name declared `global` at a +/// snippet's top level, or any global reference from a scope compiled under +/// dict globals. +pub(crate) const NAME_GLOBAL_ONLY: u8 = 0x02; +// Samuel: do not remove this comment! +// NOTE: opcodes serialize as a single byte, hard-capping this enum at 256 +// variants — roughly half are already taken. Spend slots sparingly: prefer a +// flags/operand encoding on one opcode (e.g. `Assert`/`FormatValue`) over a +// family of near-identical opcodes, unless the instruction is hot enough that +// decoding the discriminating operand would cost measurable dispatch time. + +/// Byte layout of an opcode's in-stream operand. +#[repr(u8)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum OperandShape { + None = 0, + U8 = 1, + I8 = 2, + U16 = 3, + Offset = 4, + U8U8 = 5, + U16U8 = 6, + U16U16 = 7, + U16U8U8 = 8, + CallKw = 9, + CallAttrKw = 10, + U16U16U8 = 11, +} + +impl Opcode { + /// Returns this opcode's serialized operand shape. + fn operand_shape(self) -> OperandShape { + match self { + Self::Pop + | Self::Dup + | Self::Dup2 + | Self::Rot2 + | Self::Rot3 + | Self::LoadNone + | Self::LoadTrue + | Self::LoadFalse + | Self::LoadLocal0 + | Self::LoadLocal1 + | Self::LoadLocal2 + | Self::LoadLocal3 + | Self::BinaryAdd + | Self::BinarySub + | Self::BinaryMul + | Self::BinaryDiv + | Self::BinaryFloorDiv + | Self::BinaryMod + | Self::BinaryPow + | Self::BinaryAnd + | Self::BinaryOr + | Self::BinaryXor + | Self::BinaryLShift + | Self::BinaryRShift + | Self::BinaryMatMul + | Self::CompareEq + | Self::CompareNe + | Self::CompareLt + | Self::CompareLe + | Self::CompareGt + | Self::CompareGe + | Self::CompareIs + | Self::CompareIsNot + | Self::CompareIn + | Self::CompareNotIn + | Self::UnaryNot + | Self::UnaryNeg + | Self::UnaryPos + | Self::UnaryInvert + | Self::InplaceAdd + | Self::InplaceSub + | Self::InplaceMul + | Self::InplaceDiv + | Self::InplaceFloorDiv + | Self::InplaceMod + | Self::InplacePow + | Self::InplaceAnd + | Self::InplaceOr + | Self::InplaceXor + | Self::InplaceLShift + | Self::InplaceRShift + | Self::BuildSlice + | Self::ListExtend + | Self::ListToTuple + | Self::BinarySubscr + | Self::StoreSubscr + | Self::GetIter + | Self::Raise + | Self::Reraise + | Self::ClearException + | Self::CheckExcMatch + | Self::ReturnValue + | Self::Await + | Self::Nop + | Self::BeforeWith + | Self::WithExit + | Self::WithExceptStart + | Self::BuildCell => OperandShape::None, + Self::LoadLocal + | Self::StoreLocal + | Self::DeleteLocal + | Self::FormatValue + | Self::ListAppend + | Self::SetAdd + | Self::DictSetItem + | Self::CallFunction + | Self::CallFunctionExtended + | Self::UnpackSequence + | Self::DictUpdate + | Self::SetExtend + | Self::LiftToTop + | Self::Assert + | Self::AssertFailed + | Self::MatchKeys + | Self::MatchClass + | Self::MatchAttr + | Self::SinkTop => OperandShape::U8, + Self::LoadSmallInt => OperandShape::I8, + Self::LoadModule + | Self::LoadConst + | Self::LoadLocalW + | Self::StoreLocalW + | Self::LoadGlobal + | Self::StoreGlobal + | Self::LoadCell + | Self::StoreCell + | Self::DeleteCell + | Self::BuildList + | Self::BuildTuple + | Self::BuildDict + | Self::BuildSet + | Self::BuildFString + | Self::DictMerge + | Self::LoadAttr + | Self::LoadAttrImport + | Self::StoreAttr + | Self::DeleteGlobal + | Self::RaiseUnboundLocal + | Self::MethodDictMerge => OperandShape::U16, + Self::Jump + | Self::JumpIfTrue + | Self::JumpIfFalse + | Self::JumpIfTrueOrPop + | Self::JumpIfFalseOrPop + | Self::ForIter => OperandShape::Offset, + Self::CallBuiltinFunction | Self::CallBuiltinType | Self::UnpackEx => OperandShape::U8U8, + Self::CallAttr | Self::CallAttrExtended | Self::MakeFunction | Self::MatchShape => OperandShape::U16U8, + Self::LoadGlobalCallable | Self::LoadSubmodule => OperandShape::U16U16, + Self::MakeClosure => OperandShape::U16U8U8, + Self::LoadName | Self::StoreName | Self::DeleteName => OperandShape::U16U16U8, + Self::CallFunctionKw => OperandShape::CallKw, + Self::CallAttrKw => OperandShape::CallAttrKw, + } + } +} + +/// Operand bundle, to be paired with an `Opcode` at emit time. +/// +/// `Opcode::stack_effect` consumes this to compute the operand-stack delta in +/// a single exhaustive match. The variants describe the *byte shape* of the +/// in-stream operand — `emit_with_operand` writes the bytes for each variant +/// and the same enum drives stack-effect computation, so byte emission and +/// stack tracking can't drift apart. +/// +/// `Operand` is `Copy` (largest variant is ~24 bytes), so it's passed by value +/// throughout. +#[derive(Debug, Clone, Copy)] +pub enum Operand<'a> { + /// No operand bytes (e.g. `Pop`, `BinaryAdd`). + None, + /// Single u8 operand (e.g. `LoadLocal`, `CallFunction`). + U8(u8), + /// Single i8 operand. + I8(i8), + /// Single u16 operand, little-endian (e.g. `LoadConst`, `BuildList`). + U16(u16), + /// Absolute jump target. `emit_with_operand` computes the signed i16 + /// relative offset (`target - (jump_start + 3)`) and writes it to bytecode + /// as a little-endian i16. Required for jump opcodes: `Jump`, `JumpIfTrue`, + /// `JumpIfFalse`, `JumpIfTrueOrPop`, `JumpIfFalseOrPop`, `ForIter`. + /// + /// Forward jumps pass `current_offset()` as a self-referential placeholder + /// (yielding a -3 relative offset); `patch_jump` overwrites it once the + /// real target is known. The placeholder is harmless because `#[must_use]` + /// on `JumpLabel` catches the "forgot to patch" case at compile time. + Offset(RelativeOffset), + /// Two u8 operands (e.g. `UnpackEx`, `CallBuiltinFunction`). + U8U8(u8, u8), + /// u16 little-endian then u8 (e.g. `MakeFunction`, `CallAttr`). + U16U8(u16, u8), + /// Two u16 little-endian (e.g. `LoadGlobalCallable`). + U16U16(u16, u16), + /// Two u16 little-endian then a u8 (the `*Name` opcodes: slot, name_id, flags). + U16U16U8(u16, u16, u8), + /// u16 then two u8s (e.g. `MakeClosure`). + U16U8U8(u16, u8, u8), + /// `CallFunctionKw` shape: pos_count (u8), kw_count (u8), kw_count * name_id (u16 each). + CallKw { pos_count: u8, kwname_ids: &'a [u16] }, + /// `CallAttrKw` shape: attr_name_id (u16), pos_count (u8), kw_count (u8), kw_count * name_id (u16 each). + CallAttrKw { + attr_name_id: u16, + pos_count: u8, + kwname_ids: &'a [u16], + }, +} + +impl Operand<'_> { + /// Returns this operand's serialized byte shape. + fn shape(self) -> OperandShape { + match self { + Self::None => OperandShape::None, + Self::U8(_) => OperandShape::U8, + Self::I8(_) => OperandShape::I8, + Self::U16(_) => OperandShape::U16, + Self::Offset(_) => OperandShape::Offset, + Self::U8U8(..) => OperandShape::U8U8, + Self::U16U8(..) => OperandShape::U16U8, + Self::U16U16(..) => OperandShape::U16U16, + Self::U16U16U8(..) => OperandShape::U16U16U8, + Self::U16U8U8(..) => OperandShape::U16U8U8, + Self::CallKw { .. } => OperandShape::CallKw, + Self::CallAttrKw { .. } => OperandShape::CallAttrKw, + } + } +} + +impl Opcode { + /// Returns the operand-stack effect of this opcode paired with `operand` + /// (positive = push, negative = pop). + /// + /// Returns `i32` because u16-count opcodes (notably `BuildDict`) + /// can pop up to `2 * u16::MAX` values, which overflows `i16`; the + /// builder's depth tracker accumulates in `i32` anyway. + /// + /// Variable-effect opcodes have explicit `(opcode, operand-variant)` arms; + /// fixed-effect opcodes match on the opcode alone and ignore the operand + /// variant. A variable-effect opcode whose operand variant doesn't match + /// any enumerated arm hits the catch-all panic — this keeps the tracker + /// honest when a new variable-effect opcode is added without a matching + /// arm. + /// + /// `MakeFunction`/`MakeClosure` have explicit variable arms even though + /// the "push the function" effect is +1 — the actual effect is + /// `1 - defaults_count` because defaults are popped from the stack, which + /// only equals +1 when no defaults are present. + /// + /// `emit_jump_to`'s backward-jump path computes its own effect inline + /// because it doesn't have an `Operand` to pass (the operand is a raw + /// i16 offset, not a stack-effect-bearing shape). + #[must_use] + pub fn stack_effect(self, operand: Operand<'_>) -> i32 { + #![expect(clippy::allow_attributes, reason = "expect seems broken with enum_glob_use")] + #[allow(clippy::enum_glob_use, reason = "simplifies churn")] + use Opcode::*; // allow local import + assert_eq!( + self.operand_shape(), + operand.shape(), + "wrong operand shape for {self:?}" + ); + match (self, operand) { + // === Variable-effect: U8 operand === + (CallFunction, Operand::U8(arg_count)) => -i32::from(arg_count), + (CallFunctionExtended, Operand::U8(flags)) => -(1 + i32::from(flags & 0x01)), + (FormatValue, Operand::U8(flags)) => { + // Spec is on the stack iff `FORMAT_VALUE_HAS_SPEC` is set — + // the static/dynamic discriminator (`FORMAT_VALUE_STATIC_SPEC`) + // doesn't change the pop count. + if flags & FORMAT_VALUE_HAS_SPEC != 0 { -1 } else { 0 } + } + (UnpackSequence, Operand::U8(n)) => i32::from(n) - 1, + // Fused forms pop two test operands; `AssertFailed` also pops the + // explicit message before entering dead code. + (Assert, Operand::U8(flags)) => { + if flags & ASSERT_CMP_FLAG != 0 { + -2 + } else { + -1 + } + } + (AssertFailed, Operand::U8(flags)) => { + if flags & ASSERT_CMP_FLAG != 0 { + -3 + } else { + -2 + } + } + + // === Variable-effect: U16 operand === + (BuildList | BuildTuple | BuildSet | BuildFString, Operand::U16(n)) => 1 - i32::from(n), + (BuildDict, Operand::U16(n)) => 1 - 2 * i32::from(n), + + // === Variable-effect: U8U8 operand === + // UnpackEx: pops 1, pushes (before + 1 + after) → before + after. + (UnpackEx, Operand::U8U8(before, after)) => i32::from(before) + i32::from(after), + // Builtin calls: no callable on stack, pops args, pushes result → 1 - arg_count. + (CallBuiltinFunction | CallBuiltinType, Operand::U8U8(_, arg_count)) => 1 - i32::from(arg_count), + + // === Variable-effect: U16U8 operand === + (MakeFunction, Operand::U16U8(_, defaults)) => 1 - i32::from(defaults), + // `MatchShape` pushes the test result above the subject it inspects. + (MatchShape, Operand::U16U8(..)) => 1, + (CallAttr, Operand::U16U8(_, arg_count)) => -i32::from(arg_count), + (CallAttrExtended, Operand::U16U8(_, flags)) => -(1 + i32::from(flags & 0x01)), + + // === Variable-effect: U16U8U8 operand === + // MakeClosure: pops `cell_count` cells AND `defaults_count` defaults, + // pushes the closure → 1 - defaults - cells. + (MakeClosure, Operand::U16U8U8(_, defaults, cells)) => 1 - i32::from(defaults) - i32::from(cells), + + // === Variable-effect: variable-length kw operands === + // pops callable + pos_args + kw_args, pushes result → -(pos_count + kw_count). + (CallFunctionKw, Operand::CallKw { pos_count, kwname_ids }) => { + let kw_count = i32::try_from(kwname_ids.len()).expect("keyword count exceeds i32"); + -(i32::from(pos_count) + kw_count) + } + ( + CallAttrKw, + Operand::CallAttrKw { + pos_count, kwname_ids, .. + }, + ) => { + let kw_count = i32::try_from(kwname_ids.len()).expect("keyword count exceeds i32"); + -(i32::from(pos_count) + kw_count) + } + + // === Fixed-effect, no operand === + (Pop, Operand::None) => -1, + (Dup, Operand::None) => 1, + (Dup2, Operand::None) => 2, + (Rot2 | Rot3, Operand::None) => 0, + (LoadNone | LoadTrue | LoadFalse | BuildCell, Operand::None) => 1, + (LoadLocal0 | LoadLocal1 | LoadLocal2 | LoadLocal3, Operand::None) => 1, + ( + BinaryAdd | BinarySub | BinaryMul | BinaryDiv | BinaryFloorDiv | BinaryMod | BinaryPow | BinaryAnd + | BinaryOr | BinaryXor | BinaryLShift | BinaryRShift | BinaryMatMul, + Operand::None, + ) => -1, + ( + CompareEq | CompareNe | CompareLt | CompareLe | CompareGt | CompareGe | CompareIs | CompareIsNot + | CompareIn | CompareNotIn, + Operand::None, + ) => -1, + (UnaryNot | UnaryNeg | UnaryPos | UnaryInvert, Operand::None) => 0, + ( + InplaceAdd | InplaceSub | InplaceMul | InplaceDiv | InplaceFloorDiv | InplaceMod | InplacePow + | InplaceAnd | InplaceOr | InplaceXor | InplaceLShift | InplaceRShift, + Operand::None, + ) => -1, + (BuildSlice, Operand::None) => -2, + (ListExtend, Operand::None) => -1, + (ListToTuple, Operand::None) => 0, + (BinarySubscr, Operand::None) => -1, + (StoreSubscr, Operand::None) => -3, + (GetIter | Await, Operand::None) => 0, + (Raise, Operand::None) => -1, + (Reraise | ClearException | CheckExcMatch, Operand::None) => 0, + (ReturnValue, Operand::None) => -1, + (Nop, Operand::None) => 0, + + // === Fixed-effect, I8 operand === + (LoadSmallInt, Operand::I8(_)) => 1, + + // === Fixed-effect, U8 operand === + (LoadLocal, Operand::U8(_)) => 1, + (StoreLocal, Operand::U8(_)) => -1, + (DeleteLocal, Operand::U8(_)) => 0, + // `ListAppend`/`SetAdd`/`DictSetItem` carry a u8 stack-depth operand + // that names which collection below TOS to extend; the stack + // effect itself is fixed. + (ListAppend | SetAdd, Operand::U8(_)) => -1, + (DictSetItem, Operand::U8(_)) => -2, + // `DictUpdate`/`SetExtend` also take a u8 stack-depth operand. + (DictUpdate | SetExtend, Operand::U8(_)) => -1, + // `LiftToTop(n)` / `SinkTop(n)` reorder the stack — net effect 0. + (LiftToTop | SinkTop, Operand::U8(_)) => 0, + // `MatchKeys` either pushes `[values_or_None, bool]` above the subject + // and keys, or replaces both with the `**rest` dict. + (MatchKeys, Operand::U8(mode)) => { + if mode == MATCH_KEYS_REST { + -1 + } else { + 2 + } + } + // `MatchClass` pops the keyword names; pushes `[names_or_None, bool]` above subject and class. + (MatchClass, Operand::U8(_)) => 1, + // `MatchAttr` pushes `[value, bool]` above the subject, class and names. + (MatchAttr, Operand::U8(_)) => 2, + + // === Fixed-effect, no operand (context managers) === + // `BeforeWith` pushes the `__enter__` result on top of the existing ctx. + (BeforeWith, Operand::None) => 1, + // `WithExit` pops ctx and pushes the `__exit__` return value; compiler + // emits a trailing `Pop` to discard. + (WithExit, Operand::None) => 0, + // `WithExceptStart` pushes the raw `__exit__` return value above the + // existing [ctx, exc]; compiler uses `JumpIfTrue` to act on its truthiness. + (WithExceptStart, Operand::None) => 1, + + // === Fixed-effect, U16 operand === + (LoadConst | LoadModule, Operand::U16(_)) => 1, + (LoadLocalW | LoadGlobal | LoadCell, Operand::U16(_)) => 1, + (StoreLocalW | StoreGlobal | StoreCell, Operand::U16(_)) => -1, + (DeleteGlobal | DeleteCell, Operand::U16(_)) => 0, + (LoadAttr | LoadAttrImport, Operand::U16(_)) => 0, + (StoreAttr, Operand::U16(_)) => -2, + // `DictMerge` takes a u16 operand carrying the func_name_id for + // the duplicate-key TypeError message. `MethodDictMerge` shares + // the stack effect and additionally peeks the receiver under + // the popped operands to qualify the error wording. + (DictMerge | MethodDictMerge, Operand::U16(_)) => -1, + // `RaiseUnboundLocal(name_id)` always raises — fall-through is dead + // code, but the tracker absorbs the bytes with effect 0 before the + // following region starts. + (RaiseUnboundLocal, Operand::U16(_)) => 0, + // === Fixed-effect, U16U16 operand === + (LoadGlobalCallable, Operand::U16U16(..)) => 1, + (LoadSubmodule, Operand::U16U16(..)) => 0, + + // === Fixed-effect, U16U16U8 operand === + (LoadName, Operand::U16U16U8(..)) => 1, + (StoreName, Operand::U16U16U8(..)) => -1, + (DeleteName, Operand::U16U16U8(..)) => 0, + + // === Jumps: fall-through effect (what the tracker absorbs after the bytes are written). + // Use `Offset` arguments to sanity check that jumps are correctly paired with offsets. === + + // `Jump` is unconditional and makes the code dead; the 0 here is correct for + // the moment before that transition. + (Jump, Operand::Offset(_)) => 0, + // Conditional jumps pop the condition on either path, so the tracker absorbs the pop immediately. + (JumpIfTrue | JumpIfFalse | JumpIfTrueOrPop | JumpIfFalseOrPop, Operand::Offset(_)) => -1, + // `ForIter` adds the value yielded by the iterator to the stack. + (ForIter, Operand::Offset(_)) => 1, + + // Catch-all: opcode emitted with the wrong operand variant, or a + // new opcode added without an arm above. Every opcode has exactly + // one valid operand shape; pairing them up here means the wrong + // emit_* helper for a given opcode is caught at stack-effect time + // rather than producing nonsense bytecode. + (op, _) => panic!( + "Opcode::stack_effect: opcode {op:?} paired with wrong operand variant {operand:?} (or missing arm)" + ), + } + } + + /// Returns the operand-stack delta applied when *this jump opcode is + /// taken*, i.e. the difference between the pre-emit depth and the depth + /// that execution arrives at on the jump-taken path. + /// + /// Panics for non-jump opcodes. + #[must_use] + pub fn jump_taken_stack_effect(self) -> i16 { + match self { + // Unconditional jump: stack unchanged on jump-taken. + Self::Jump => 0, + // Pop condition on either path. + Self::JumpIfTrue | Self::JumpIfFalse => -1, + // Pop condition on fall-through, keep it on jump-taken. + Self::JumpIfTrueOrPop | Self::JumpIfFalseOrPop => 0, + // Pop iterator on jump-taken (no value pushed). + Self::ForIter => -1, + _ => panic!("Opcode::jump_taken_delta: {self:?} is not a jump opcode"), + } + } +} + +/// Computes an FNV-1a hash over the canonical opcode table. +#[cfg(test)] +pub(crate) fn opcode_fingerprint() -> u64 { + const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + const PRIME: u64 = 0x0100_0000_01b3; + + let mut hash = OFFSET_BASIS; + let mut opcodes = Opcode::iter().collect::>(); + opcodes.sort_unstable_by_key(|opcode| *opcode as u8); + for opcode in opcodes { + let byte = opcode as u8; + for value in [byte] + .into_iter() + .chain(format!("{opcode:?}").bytes()) + .chain([0, opcode.operand_shape() as u8]) + { + hash ^= u64::from(value); + hash = hash.wrapping_mul(PRIME); + } + } + hash +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_assert_flags_roundtrip() { + // The bare form and every comparison operator must round-trip. + assert_eq!(decode_assert_flags(assert_flags(None)), Some(None)); + for op in CmpOperator::iter() { + assert_eq!(decode_assert_flags(assert_flags(Some(op))), Some(Some(op))); + } + // Bytes `assert_flags` can't produce are rejected: a cmp nibble + // without the flag, an out-of-range nibble, and stray high bits. + assert_eq!(decode_assert_flags(0x01), None); + assert_eq!(decode_assert_flags(ASSERT_CMP_FLAG | 0x0A), None); + assert_eq!(decode_assert_flags(0x20 | ASSERT_CMP_FLAG), None); + } +} diff --git a/crates/bashkit-monty/src/bytecode/pattern.rs b/crates/bashkit-monty/src/bytecode/pattern.rs new file mode 100644 index 000000000..b6e658e3e --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/pattern.rs @@ -0,0 +1,569 @@ +//! Compilation of `match` statements (PEP 634) to bytecode. +//! +//! The lowering follows CPython's `codegen_pattern_*` family so that capture +//! bindings only happen once the whole pattern has matched: captured values +//! are kept on the operand stack beneath the pattern's temporaries and stored +//! after the pattern succeeds, just before the guard runs. A failing pattern +//! jumps to a per-depth cleanup block that pops its partial state, then falls +//! through to the next `case`. + +use std::mem; + +use super::{ + builder::JumpLabel, + compiler::{CompileError, Compiler}, + op::{MATCH_KEYS_REST, MATCH_KEYS_VALUES, MATCH_SHAPE_MAPPING, MATCH_SHAPE_MIN_LEN, Opcode}, +}; +use crate::{ + expressions::{ExprLoc, Identifier, MatchCase, Pattern, PreparedNode}, + intern::StringId, + parse::CodeRange, + value::Value, +}; + +/// Per-pattern compilation state, mirroring CPython's `pattern_context`. +/// +/// Stack layout while a pattern runs, top last: +/// `[..., newest capture, ..., oldest capture, on_top temporaries]`. +/// A new capture is sunk beneath both regions so the final stores pop the +/// oldest capture first; a failure jumps to `fail_pop[on_top + stores.len()]`. +#[derive(Default)] +struct PatternContext { + /// Names captured so far, in binding order. + stores: Vec, + /// Whether an irrefutable pattern (capture or wildcard) may appear here: + /// only in the last case, in a guarded case, or as a sub-pattern. + allow_irrefutable: bool, + /// Jumps to the failure path, indexed by how many stack items the jump + /// site has above the case's base depth. + fail_pop: Vec>, + /// Temporaries the pattern currently holds above its captures. + on_top: usize, +} + +impl PatternContext { + /// Starts the context for one `case`, or one alternative of an or-pattern. + fn new(allow_irrefutable: bool) -> Self { + Self { + allow_irrefutable, + ..Self::default() + } + } + + /// Records `label` as a jump to the failure path from the current depth. + fn fail_at(&mut self, pops: usize, label: JumpLabel) { + if self.fail_pop.len() <= pops { + self.fail_pop.resize_with(pops + 1, Vec::new); + } + self.fail_pop[pops].push(label); + } + + /// Whether `name` is already captured by this pattern. + fn captures(&self, name: &Identifier) -> bool { + self.stores.iter().any(|stored| stored.name_id == name.name_id) + } +} + +impl<'a> Compiler<'a, '_> { + /// Compiles `match SUBJECT: case ...` (CPython's `codegen_match_inner`). + /// + /// The subject is evaluated once. Every case but the last duplicates it + /// before matching, because a pattern consumes the value it is matched + /// against on both the success and the failure path. A trailing bare `_` + /// case is compiled as plain fall-through code. + pub(super) fn compile_match( + &mut self, + subject: &ExprLoc, + cases: &'a [MatchCase], + position: CodeRange, + ) -> Result<(), CompileError> { + self.compile_expr(subject)?; + let has_default = cases.len() > 1 && cases.last().is_some_and(|case| case.pattern.is_wildcard()); + let tested = cases.len() - usize::from(has_default); + let mut end_jumps = Vec::with_capacity(cases.len()); + for (i, case) in cases[..tested].iter().enumerate() { + let is_last_tested = i == tested - 1; + self.code.set_location(case.position, None); + if !is_last_tested { + self.code.emit(Opcode::Dup)?; + } + let allow_irrefutable = case.guard.is_some() || i == cases.len() - 1; + let mut pc = PatternContext::new(allow_irrefutable); + self.compile_pattern(&case.pattern, &mut pc)?; + debug_assert_eq!(pc.on_top, 0, "pattern left temporaries on the stack"); + // It's a match: bind the captured names (oldest capture is on top). + for name in &pc.stores { + self.compile_store(name)?; + } + if let Some(guard) = &case.guard { + self.compile_expr(guard)?; + let label = self.code.emit_jump(Opcode::JumpIfFalse)?; + pc.fail_at(0, label); + } + if !is_last_tested { + // Done with this case's copy of the subject. + self.code.set_location(case.position, None); + self.code.emit(Opcode::Pop)?; + } + self.compile_block(&case.body)?; + end_jumps.push(self.code.emit_jump(Opcode::Jump)?); + self.code.set_location(case.position, None); + self.emit_fail_pops(&mut pc)?; + } + if has_default { + // The last tested case consumed the subject, so `case _:` is plain code. + let case = &cases[tested]; + self.code.set_location(case.position, None); + if let Some(guard) = &case.guard { + self.compile_expr(guard)?; + end_jumps.push(self.code.emit_jump(Opcode::JumpIfFalse)?); + } + self.compile_block(&case.body)?; + } + self.code.set_location(position, None); + for jump in end_jumps { + self.code.patch_jump(jump)?; + } + Ok(()) + } + + /// Compiles one pattern against the value on top of the stack, consuming + /// it on every path. Dispatches on the pattern shape (`codegen_pattern`). + fn compile_pattern(&mut self, pattern: &Pattern, pc: &mut PatternContext) -> Result<(), CompileError> { + let position = pattern.position(); + self.code.set_location(position, None); + match pattern { + Pattern::Value(value) => { + self.compile_expr(value)?; + self.code.set_location(position, None); + self.code.emit(Opcode::CompareEq)?; + self.jump_to_fail_pop(pc, Opcode::JumpIfFalse) + } + Pattern::Singleton(value) => { + self.compile_expr(value)?; + self.code.set_location(position, None); + self.code.emit(Opcode::CompareIs)?; + self.jump_to_fail_pop(pc, Opcode::JumpIfFalse) + } + Pattern::As { + pattern: None, name, .. + } => { + if !pc.allow_irrefutable { + let message = match name { + Some(name) => format!( + "name capture '{}' makes remaining patterns unreachable", + self.interns.get_str(name.name_id) + ), + None => "wildcard makes remaining patterns unreachable".to_owned(), + }; + return Err(CompileError::new(message, position)); + } + self.pattern_store_name(name.as_ref(), position, pc) + } + Pattern::As { + pattern: Some(inner), + name, + .. + } => { + // Keep a copy to bind once the inner pattern has matched. + pc.on_top += 1; + self.code.emit(Opcode::Dup)?; + self.compile_pattern(inner, pc)?; + pc.on_top -= 1; + self.pattern_store_name(name.as_ref(), position, pc) + } + // Only reached through sequence unpacking, which has already built the list. + Pattern::Star { name, .. } => self.pattern_store_name(name.as_ref(), position, pc), + Pattern::Sequence { patterns, .. } => self.compile_pattern_sequence(patterns, position, pc), + Pattern::Mapping { + keys, patterns, rest, .. + } => self.compile_pattern_mapping(keys, patterns, rest.as_ref(), position, pc), + Pattern::Class { + cls, + patterns, + kwd_attrs, + kwd_patterns, + .. + } => self.compile_pattern_class(cls, patterns, kwd_attrs, kwd_patterns, position, pc), + Pattern::Or { patterns, .. } => self.compile_pattern_or(patterns, position, pc), + } + } + + /// Compiles a nested pattern, where irrefutable shapes are always allowed. + fn compile_subpattern(&mut self, pattern: &Pattern, pc: &mut PatternContext) -> Result<(), CompileError> { + let allow_irrefutable = mem::replace(&mut pc.allow_irrefutable, true); + let result = self.compile_pattern(pattern, pc); + pc.allow_irrefutable = allow_irrefutable; + result + } + + /// `[a, *rest, b]`: shape and length test, then per-item sub-patterns. + fn compile_pattern_sequence( + &mut self, + patterns: &[Pattern], + position: CodeRange, + pc: &mut PatternContext, + ) -> Result<(), CompileError> { + let size = patterns.len(); + let star = patterns.iter().position(|p| matches!(p, Pattern::Star { .. })); + let only_wildcards = patterns.iter().all(|p| p.is_wildcard() || p.is_star_wildcard()); + let star_is_wildcard = star.is_some_and(|i| patterns[i].is_star_wildcard()); + // The subject stays on top during the shape check. + pc.on_top += 1; + let (length, flags) = match star { + Some(_) => (size - 1, MATCH_SHAPE_MIN_LEN), + None => (size, 0), + }; + let length = pattern_count_u16(length, "sequence", position)?; + self.code.emit_u16_u8(Opcode::MatchShape, length, flags)?; + self.jump_to_fail_pop(pc, Opcode::JumpIfFalse)?; + // Whatever comes next consumes the subject. + pc.on_top -= 1; + if only_wildcards { + // `[]`, `[_, _]`, `[_, *_]`: the length check was the whole test. + self.code.emit(Opcode::Pop) + } else if star_is_wildcard { + self.compile_sequence_subscr(patterns, star, position, pc) + } else { + self.compile_sequence_unpack(patterns, star, position, pc) + } + } + + /// Unpacks the whole sequence (`UnpackSequence` / `UnpackEx`) and matches + /// each item, so a named star capture gets its list for free. + fn compile_sequence_unpack( + &mut self, + patterns: &[Pattern], + star: Option, + position: CodeRange, + pc: &mut PatternContext, + ) -> Result<(), CompileError> { + let size = patterns.len(); + if let Some(star) = star { + let before = pattern_count_u8(star, "sequence", position)?; + let after = pattern_count_u8(size - star - 1, "sequence", position)?; + self.code.emit_u8_u8(Opcode::UnpackEx, before, after)?; + } else { + let count = pattern_count_u8(size, "sequence", position)?; + self.code.emit_u8(Opcode::UnpackSequence, count)?; + } + // The first item is on top; each sub-pattern consumes one. + pc.on_top += size; + for pattern in patterns { + pc.on_top -= 1; + self.compile_subpattern(pattern, pc)?; + } + Ok(()) + } + + /// Indexes the items individually when the star is `*_`, so the surplus + /// items are never collected. Items after the star use negative indexes. + fn compile_sequence_subscr( + &mut self, + patterns: &[Pattern], + star: Option, + position: CodeRange, + pc: &mut PatternContext, + ) -> Result<(), CompileError> { + let size = patterns.len(); + // Keep the subject while indexing into it. + pc.on_top += 1; + for (i, pattern) in patterns.iter().enumerate() { + if pattern.is_wildcard() || Some(i) == star { + continue; + } + self.code.set_location(pattern.position(), None); + self.code.emit(Opcode::Dup)?; + let index = if star.is_some_and(|star| i > star) { + i64::try_from(i).map_err(|_| too_many_subpatterns("sequence", position))? + - i64::try_from(size).map_err(|_| too_many_subpatterns("sequence", position))? + } else { + i64::try_from(i).map_err(|_| too_many_subpatterns("sequence", position))? + }; + self.compile_int_constant(index)?; + self.code.emit(Opcode::BinarySubscr)?; + self.compile_subpattern(pattern, pc)?; + } + pc.on_top -= 1; + self.code.set_location(position, None); + self.code.emit(Opcode::Pop) + } + + /// `{'k': v, **rest}`: mapping test, key lookup via `MatchKeys`, then the + /// value sub-patterns and the optional `**rest` dict. + fn compile_pattern_mapping( + &mut self, + keys: &[ExprLoc], + patterns: &[Pattern], + rest: Option<&Identifier>, + position: CodeRange, + pc: &mut PatternContext, + ) -> Result<(), CompileError> { + let size = keys.len(); + pc.on_top += 1; + let length = pattern_count_u16(size, "mapping", position)?; + self.code + .emit_u16_u8(Opcode::MatchShape, length, MATCH_SHAPE_MAPPING | MATCH_SHAPE_MIN_LEN)?; + self.jump_to_fail_pop(pc, Opcode::JumpIfFalse)?; + if size == 0 && rest.is_none() { + // `{}` matches any mapping: done with the subject. + pc.on_top -= 1; + return self.code.emit(Opcode::Pop); + } + for key in keys { + self.compile_expr(key)?; + } + self.code.set_location(position, None); + self.code.emit_u16(Opcode::BuildTuple, length)?; + self.code.emit_u8(Opcode::MatchKeys, MATCH_KEYS_VALUES)?; + // The keys tuple and the values tuple (or None) now sit above the subject. + pc.on_top += 2; + self.jump_to_fail_pop(pc, Opcode::JumpIfFalse)?; + self.unpack_subpattern_values(size, pc)?; + for pattern in patterns { + pc.on_top -= 1; + self.compile_subpattern(pattern, pc)?; + } + // Success: consume the keys tuple and the subject. + pc.on_top -= 2; + self.code.set_location(position, None); + if let Some(rest) = rest { + self.code.emit_u8(Opcode::MatchKeys, MATCH_KEYS_REST)?; + self.pattern_store_name(Some(rest), position, pc) + } else { + self.code.emit(Opcode::Pop)?; + self.code.emit(Opcode::Pop) + } + } + + /// `Point(0, y=1)`: `MatchClass` checks the instance and resolves the + /// attribute names (`__match_args__` then keywords); one `MatchAttr` per + /// sub-pattern then reads its attribute, so a host-side read can suspend. + /// The class stays on the stack so `MatchAttr` can name it in errors. + fn compile_pattern_class( + &mut self, + cls: &ExprLoc, + patterns: &[Pattern], + kwd_attrs: &[StringId], + kwd_patterns: &[Pattern], + position: CodeRange, + pc: &mut PatternContext, + ) -> Result<(), CompileError> { + let nargs = pattern_count_u8(patterns.len(), "class", position)?; + pattern_count_u8(patterns.len() + kwd_patterns.len(), "class", position)?; + let nattrs = pattern_count_u16(kwd_attrs.len(), "class", position)?; + self.compile_expr(cls)?; + for attr in kwd_attrs { + let idx = self.code.add_const(Value::InternString(*attr))?; + self.code.emit_u16(Opcode::LoadConst, idx)?; + } + self.code.set_location(position, None); + self.code.emit_u16(Opcode::BuildTuple, nattrs)?; + self.code.emit_u8(Opcode::MatchClass, nargs)?; + // The subject and class stay, with the names tuple (or None) above them. + pc.on_top += 3; + self.jump_to_fail_pop(pc, Opcode::JumpIfFalse)?; + for (index, pattern) in patterns.iter().chain(kwd_patterns).enumerate() { + self.code.set_location(position, None); + self.code + .emit_u8(Opcode::MatchAttr, pattern_count_u8(index, "class", position)?)?; + pc.on_top += 1; + self.jump_to_fail_pop(pc, Opcode::JumpIfFalse)?; + pc.on_top -= 1; + self.compile_subpattern(pattern, pc)?; + } + // Success: drop the names tuple, the class and the subject. + pc.on_top -= 3; + self.code.set_location(position, None); + self.code.emit(Opcode::Pop)?; + self.code.emit(Opcode::Pop)?; + self.code.emit(Opcode::Pop) + } + + /// Replaces the mapping values tuple on top of the stack with its `count` + /// items, first item on top, adjusting `on_top` so each sub-pattern consumes one. + fn unpack_subpattern_values(&mut self, count: usize, pc: &mut PatternContext) -> Result<(), CompileError> { + if count == 0 { + self.code.emit(Opcode::Pop)?; + } else { + let count_u8 = pattern_count_u8(count, "mapping", self.code.current_position())?; + self.code.emit_u8(Opcode::UnpackSequence, count_u8)?; + } + pc.on_top += count; + pc.on_top -= 1; + Ok(()) + } + + /// `A | B | C`: each alternative runs against a copy of the subject with + /// its own context; all must bind the same names, which are reordered on + /// the stack to the first alternative's order (`codegen_pattern_or`). + fn compile_pattern_or( + &mut self, + patterns: &[Pattern], + position: CodeRange, + pc: &mut PatternContext, + ) -> Result<(), CompileError> { + let outer_stores = mem::take(&mut pc.stores); + let outer_allow_irrefutable = pc.allow_irrefutable; + let outer_fail_pop = mem::take(&mut pc.fail_pop); + let outer_on_top = pc.on_top; + // The names bound by the first alternative, which the others must match. + let mut control: Option> = None; + let mut end_jumps = Vec::with_capacity(patterns.len()); + for (i, alternative) in patterns.iter().enumerate() { + *pc = PatternContext::new(i == patterns.len() - 1 && outer_allow_irrefutable); + self.code.set_location(alternative.position(), None); + self.code.emit(Opcode::Dup)?; + self.compile_pattern(alternative, pc)?; + match &control { + None => control = Some(pc.stores.clone()), + Some(control) => self.reorder_alternative_stores(control, position, pc)?, + } + end_jumps.push(self.code.emit_jump(Opcode::Jump)?); + self.emit_fail_pops(pc)?; + } + pc.stores = outer_stores; + pc.allow_irrefutable = outer_allow_irrefutable; + pc.fail_pop = outer_fail_pop; + pc.on_top = outer_on_top; + // No alternative matched: discard the remaining subject and fail. + self.code.set_location(position, None); + self.code.emit(Opcode::Pop)?; + self.jump_to_fail_pop(pc, Opcode::Jump)?; + for jump in end_jumps { + self.code.patch_jump(jump)?; + } + // Sink the alternative's captures beneath the outer captures, the outer + // temporaries and the subject copy, then drop that copy. + let control = control.unwrap_or_default(); + let depth = control.len() + pc.on_top + pc.stores.len(); + for name in control { + self.emit_sink_top(depth, position)?; + if pc.captures(&name) { + return Err(duplicate_capture(self.interns.get_str(name.name_id), position)); + } + pc.stores.push(name); + } + self.code.emit(Opcode::Pop) + } + + /// Permutes an alternative's captures on the stack into `control`'s order, + /// or reports that the alternatives bind different names. + fn reorder_alternative_stores( + &mut self, + control: &[Identifier], + position: CodeRange, + pc: &mut PatternContext, + ) -> Result<(), CompileError> { + if pc.stores.len() != control.len() { + return Err(CompileError::new("alternative patterns bind different names", position)); + } + // Work from the deepest slot up: once `stores[icontrol..]` agrees with + // `control[icontrol..]`, rotating the top `icontrol + 1` items leaves it alone. + for icontrol in (0..control.len()).rev() { + let Some(istores) = pc.stores.iter().position(|s| s.name_id == control[icontrol].name_id) else { + return Err(CompileError::new("alternative patterns bind different names", position)); + }; + if istores != icontrol { + debug_assert!(istores < icontrol); + let rotations = istores + 1; + let rotated: Vec = pc.stores.drain(..rotations).collect(); + let at = icontrol - istores; + pc.stores.splice(at..at, rotated); + for _ in 0..rotations { + self.emit_sink_top(icontrol, position)?; + } + } + } + Ok(()) + } + + /// Binds (or, for `_`, discards) the value on top of the stack as a capture: + /// it is sunk beneath the pattern's temporaries and earlier captures so the + /// stores can be emitted in order once the whole pattern matches. + fn pattern_store_name( + &mut self, + name: Option<&Identifier>, + position: CodeRange, + pc: &mut PatternContext, + ) -> Result<(), CompileError> { + let Some(name) = name else { + return self.code.emit(Opcode::Pop); + }; + if pc.captures(name) { + return Err(duplicate_capture(self.interns.get_str(name.name_id), position)); + } + self.emit_sink_top(pc.on_top + pc.stores.len(), position)?; + pc.stores.push(*name); + Ok(()) + } + + /// Moves the top of the stack beneath the `depth` items below it. + fn emit_sink_top(&mut self, depth: usize, position: CodeRange) -> Result<(), CompileError> { + let depth_u8 = u8::try_from(depth).map_err(|_| CompileError::new("too many names in pattern", position))?; + if depth == 0 { + Ok(()) + } else { + self.code.emit_u8(Opcode::SinkTop, depth_u8) + } + } + + /// Emits a jump to the failure path from the current pattern depth. + fn jump_to_fail_pop(&mut self, pc: &mut PatternContext, op: Opcode) -> Result<(), CompileError> { + let pops = pc.on_top + pc.stores.len(); + let label = self.code.emit_jump(op)?; + pc.fail_at(pops, label); + Ok(()) + } + + /// Emits the failure path: one landing pad per depth, each popping one + /// item and falling into the next, so every failed jump ends at the case's + /// base depth (`emit_and_reset_fail_pop`). + fn emit_fail_pops(&mut self, pc: &mut PatternContext) -> Result<(), CompileError> { + let fail_pop = mem::take(&mut pc.fail_pop); + let mut levels = fail_pop.into_iter().rev(); + let Some(deepest) = levels.next() else { + return Ok(()); + }; + for label in deepest { + self.code.patch_jump(label)?; + } + for labels in levels { + self.code.emit(Opcode::Pop)?; + for label in labels { + self.code.patch_jump(label)?; + } + } + Ok(()) + } + + /// Pushes an integer constant, using the compact small-int form when it fits. + fn compile_int_constant(&mut self, value: i64) -> Result<(), CompileError> { + if let Ok(small) = i8::try_from(value) { + self.code.emit_i8(Opcode::LoadSmallInt, small) + } else { + let idx = self.code.add_const(Value::Int(value))?; + self.code.emit_u16(Opcode::LoadConst, idx) + } + } +} + +/// `SyntaxError: multiple assignments to name 'x' in pattern`. +fn duplicate_capture(name: &str, position: CodeRange) -> CompileError { + CompileError::new(format!("multiple assignments to name '{name}' in pattern"), position) +} + +/// Fits a sub-pattern count into a `u8` bytecode operand. +fn pattern_count_u8(count: usize, kind: &str, position: CodeRange) -> Result { + u8::try_from(count).map_err(|_| too_many_subpatterns(kind, position)) +} + +/// Fits a sub-pattern count into a `u16` bytecode operand. +fn pattern_count_u16(count: usize, kind: &str, position: CodeRange) -> Result { + u16::try_from(count).map_err(|_| too_many_subpatterns(kind, position)) +} + +/// The pattern has more parts than the bytecode operands can encode. +fn too_many_subpatterns(kind: &str, position: CodeRange) -> CompileError { + CompileError::new(format!("too many sub-patterns in {kind} pattern"), position) +} diff --git a/crates/bashkit-monty/src/bytecode/vm/async_exec.rs b/crates/bashkit-monty/src/bytecode/vm/async_exec.rs new file mode 100644 index 000000000..2823ab6a5 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/async_exec.rs @@ -0,0 +1,1161 @@ +//! Async execution support for the VM. +//! +//! This module contains all async-related methods for the VM including: +//! - Awaiting coroutines, external futures, and gather futures +//! - Task scheduling and context switching +//! - Task completion and failure handling +//! - External future resolution + +use std::{mem, task::Poll}; + +use monty_types::{InvalidInputError, MontyException, ResourceError, ResourceTracker}; +use smallvec::{SmallVec, smallvec}; + +use super::{ + AwaitResult, CallFrame, FrameExit, Opcode, VM, frame_code, function_namespace, recursion::frame_recursion_depth, + stack_index, +}; +use crate::{ + asyncio::{ + AwaitedGather, Awaiter, CallId, Coroutine, CoroutineState, ExternalFuture, ExternalFutureState, GatherFuture, + GatherState, PendingChildren, TaskId, + }, + bytecode::vm::scheduler::SerializedTaskFrame, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{ + ContainsHeap, DropGuard, DropWithContext, HeapData, HeapId, HeapObjectRead, HeapRead, HeapReadMut, + HeapReadOutput, HeapReader, + }, + intern::FunctionId, + object_bridge::MontyObjectExt, + run_progress::{ExtFunctionResult, ExtFunctionResultExt}, + types::List, + value::Value, +}; + +impl<'h> VM<'h> { + /// Allows eager host resolution only for an immediate await with no competing work. + pub(crate) fn allow_eager_await(&self) -> bool { + let next = self.current_frame.bytecode.get(self.current_frame.ip); + next == Some(&(Opcode::Await as u8)) && self.scheduler.can_await_eagerly() + } + + /// Executes the Await opcode. + /// + /// Pops the awaitable from the stack and handles it based on its type: + /// - `Coroutine`: validates state is New, then pushes a frame to execute it + /// - `ExternalFuture`: blocks until resolved or yields if not ready + /// - `GatherFuture`: spawns tasks for coroutines and tracks external futures + /// + /// Returns `AwaitResult` indicating what action the VM should take. + pub(super) fn exec_get_awaitable(&mut self) -> Result { + let this = self; + let awaitable = this.pop(); + defer_drop!(awaitable, this); + + let awaiter = Awaiter::Task( + this.scheduler + .current_task_id() + .expect("exec_get_awaitable called without a current task"), + ); + + match awaitable { + Value::Ref(heap_id) => { + let heap_id = *heap_id; + let poll = match this.heap.read(heap_id) { + HeapReadOutput::Coroutine(coro) => return this.await_coroutine(&coro), + HeapReadOutput::GatherFuture(gather) => this.await_gather_future(gather, awaiter)?, + HeapReadOutput::ExternalFuture(fut) => this.await_external_future(&fut, awaiter)?, + _ => return Err(ExcType::object_not_awaitable(&awaitable.py_type_name(this))), + }; + match poll { + Poll::Ready(value) => Ok(AwaitResult::ValueReady(value)), + Poll::Pending => { + this.scheduler.block_current_on(heap_id, this.heap); + this.switch_or_yield() + } + } + } + _ => Err(ExcType::object_not_awaitable(&awaitable.py_type_name(this))), + } + } + + /// Awaits a coroutine by pushing a frame to execute it. + /// + /// Validates the coroutine is in `New` state, extracts its captured namespace + /// and cells, marks it as `Running`, and pushes a frame to execute the coroutine body. + fn await_coroutine(&mut self, coro: &HeapObjectRead<'h, Coroutine>) -> Result { + // Check if coroutine can be awaited (must be New) + if coro.get(self.heap).state != CoroutineState::New { + return Err(ExcType::cannot_reuse_already_awaited_coroutine()); + } + + // Extract coroutine data before mutating + let func_id = coro.get(self.heap).func_id; + let globals = coro.get(self.heap).globals; + let namespace_values: Vec = coro + .get(self.heap) + .namespace + .iter() + .map(|v| v.clone_with_heap(self)) + .collect(); + + // Mark coroutine as Running + coro.get_mut(self.heap).state = CoroutineState::Running; + + // Create namespace and push frame (guard drops awaitable at scope exit) + self.start_coroutine_frame(func_id, namespace_values, globals)?; + + Ok(AwaitResult::FramePushed) + } + + /// Awaits a gather future from the user's `await gather` site. + /// + /// A settled gather replays its cached result; a `Pending` one is handed to + /// [`Self::commit_gather_tree`], which commits it along with every gather + /// nested inside it. + fn await_gather_future( + &mut self, + gather: HeapObjectRead<'h, GatherFuture>, + awaiter: Awaiter, + ) -> Result, RunError> { + let mut awaiter_guard = DropGuard::new(awaiter, self); + let this = awaiter_guard.ctx(); + if let Some(value) = poll_settled_gather(&gather, this.heap)? { + Ok(Poll::Ready(value)) + } else { + // The walk re-reads each gather by id, so hand the handle back + // before it starts. + let gather_id = gather.id(); + drop(gather); + let (awaiter, this) = awaiter_guard.into_parts(); + this.commit_gather_tree(gather_id, awaiter) + } + } + + /// Commits `root` and every gather nested inside it, reporting whether the + /// root settled synchronously. + /// + /// Nesting a gather costs no Python frames (`g = asyncio.gather(g)` in a + /// loop), so the recursion limit never saw the commit walk that descends + /// through it — a recursive walk turned heap-held nesting back into native + /// frames and aborted the process. The frames it needed now live in + /// `stack`, one [`GatherCommit`] per level, which makes nesting depth a + /// matter of memory rather than of native stack, as it is for CPython's + /// loop-driven futures. + fn commit_gather_tree(&mut self, root: HeapId, awaiter: Awaiter) -> Result, RunError> { + let mut stack = vec![self.open_gather_commit(root, awaiter, None)]; + let mut steps = 0; + let outcome = loop { + // Each level costs a frame on the way down and a result list on the + // way back up, and the whole walk runs no bytecode, so + // `dispatch_checkpoint` never sees how far it has grown. Without + // this check a nest that fits under `max_memory` commits its way + // past the allocator's hard ceiling, taking the worker down instead + // of ending the run. + if let Err(err) = self.heap.tracker.check_memory_time_every(steps) { + break Err(err.into()); + } + steps += 1; + + let frame = stack.last_mut().expect("the commit stack is emptied only by returning"); + match self.step_gather_commit(frame) { + // Descend: the nested gather's own items must be committed + // before the frame that owns its result slot can continue. + Ok(Some(nested)) => { + if let Err(err) = check_commit_stack_growth(stack.len(), stack.capacity(), &self.heap.tracker) { + nested.drop_with(self.heap); + break Err(err.into()); + } + stack.push(nested); + } + Ok(None) => { + let frame = stack.pop().expect("the frame just stepped is still on the stack"); + let (child_id, slot) = (frame.gather, frame.parent_slot); + let poll = self.settle_gather_commit(frame); + match stack.last_mut() { + // The root settled: `poll` is what the `await` site sees. + None => break Ok(poll), + Some(parent) => { + let slot = slot.expect("only the root commit frame has no parent slot"); + parent.resume_after_child(child_id, slot, poll); + } + } + } + Err(err) => break Err(err), + } + }; + + match outcome { + Ok(poll) => Ok(poll), + Err(err) => { + self.unwind_gather_commits(stack, &err); + Err(err) + } + } + } + + /// Opens a commit frame for the `Pending` gather `gather`, sized to its items. + fn open_gather_commit(&mut self, gather: HeapId, awaiter: Awaiter, parent_slot: Option) -> GatherCommit { + let HeapReadOutput::GatherFuture(item_source) = self.heap.read(gather) else { + panic!("gather commit frame id is not a GatherFuture") + }; + let item_count = item_source.get(self.heap).item_count(); + GatherCommit { + gather, + awaiter, + parent_slot, + next: 0, + results: (0..item_count).map(|_| None).collect(), + pending_children: PendingChildren::new(), + } + } + + /// Commits `frame`'s items left-to-right into result slots or pending + /// children, spawning coroutine children and installing awaiters on + /// external futures as it goes. + /// + /// Stops early at a `Pending` nested gather, returning the frame the caller + /// must commit before this one can continue; `Ok(None)` means every item is + /// committed. Any error leaves the items handled so far in `frame`, which + /// [`Self::unwind_gather_commits`] settles. + fn step_gather_commit(&mut self, frame: &mut GatherCommit) -> Result, RunError> { + let HeapReadOutput::GatherFuture(gather) = self.heap.read(frame.gather) else { + panic!("gather commit frame id is not a GatherFuture") + }; + let gather_id = frame.gather; + + while frame.next < frame.results.len() { + let idx = frame.next; + let item_id = gather.get(self.heap).items[idx]; + if let Some(slots) = frame.pending_children.get_mut(&item_id) { + // Dedup: We've already registered this item in this commit pass — + // this is a duplicate item (e.g. `gather(coro, coro)`). Just + // append the new slot index to the existing entry. + slots.push(idx); + frame.next += 1; + continue; + } + + let poll = match self.heap.read(item_id) { + HeapReadOutput::Coroutine(coro) => { + // Reject reuse up-front: either the coroutine is no longer + // `New`, or another gather already spawned it (`spawn` + // returns `Ok(None)`). + if coro.get(self.heap).state != CoroutineState::New + || self.scheduler.spawn(self.heap, item_id, Some(gather_id)).is_none() + { + return Err(ExcType::cannot_reuse_already_awaited_coroutine()); + } + Poll::Pending + } + HeapReadOutput::ExternalFuture(fut) => { + self.heap.inc_ref(gather_id); + let sub_awaiter = Awaiter::GatherSlot { + gather: gather_id, + source: item_id, + }; + self.await_external_future(&fut, sub_awaiter)? + } + HeapReadOutput::GatherFuture(child_gather) => { + if let Some(value) = poll_settled_gather(&child_gather, self.heap)? { + Poll::Ready(value) + } else { + drop(child_gather); + // Both the inc_ref and the awaiter that owns it are + // handed to the nested frame, which releases them when + // it settles; until then nothing is committed for this + // slot, so an error above needs no cleanup here. + self.heap.inc_ref(gather_id); + let sub_awaiter = Awaiter::GatherSlot { + gather: gather_id, + source: item_id, + }; + return Ok(Some(self.open_gather_commit(item_id, sub_awaiter, Some(idx)))); + } + } + _ => panic!("gather item is not a Coroutine, ExternalFuture, or GatherFuture"), + }; + + match poll { + Poll::Ready(value) => frame.results[idx] = Some(value), + Poll::Pending => { + frame.pending_children.insert(item_id, smallvec![idx]); + } + } + frame.next += 1; + } + + Ok(None) + } + + /// Settles a fully-committed frame. + /// + /// With nothing left in flight the gather goes straight to `Completed` with + /// its result list (this covers the empty `gather()` too); otherwise it + /// parks in `Awaited`, taking over the frame's bookkeeping, and later + /// resolutions drive it from there. + fn settle_gather_commit(&mut self, frame: GatherCommit) -> Poll { + let HeapReadOutput::GatherFuture(gather) = self.heap.read(frame.gather) else { + panic!("gather commit frame id is not a GatherFuture") + }; + + if frame.pending_children.is_empty() { + let results: Vec = frame + .results + .into_iter() + .map(|r| r.expect("all results filled for synchronous gather completion")) + .collect(); + let list_id = self.heap.allocate(HeapData::List(List::new(results))); + gather.cache_result(self.heap, list_id); + frame.awaiter.drop_with(self.heap); + Poll::Ready(Value::Ref(list_id)) + } else { + gather.get_mut(self.heap).state = GatherState::Awaited(AwaitedGather { + awaiter: frame.awaiter, + pending_children: frame.pending_children, + results: frame.results, + }); + Poll::Pending + } + } + + /// Fails every frame left on the commit stack with `err`, innermost first. + /// + /// This is the unwind the recursive walk got from `?`: each level caches the + /// error so re-awaits replay it, and drops the result slots and awaiter the + /// frame was holding. The children it had already committed keep running and + /// keep pointing at their now-`Failed` gather, as they do for a failure that + /// arrives after the commit pass (see [`HeapReadMut::fail`]). + fn unwind_gather_commits(&mut self, stack: Vec, err: &RunError) { + for frame in stack.into_iter().rev() { + let HeapReadOutput::GatherFuture(gather) = self.heap.read(frame.gather) else { + panic!("gather commit frame id is not a GatherFuture") + }; + gather.get_mut(self.heap).state = GatherState::Failed(err.clone()); + drop(gather); + + frame.drop_with(self.heap); + } + } + + /// Awaits an external future by inspecting its heap state. + /// + /// - `Resolved(v)` returns a clone of `v` immediately. + /// - `Failed(e)` re-raises a clone of `e`. + /// - `Pending { awaiter: None }` installs the current task as the awaiter, + /// and returns `Poll::Pending`. + /// - `Pending { awaiter: Some(_) }` is rejected as a double-await — a + /// single-awaiter restriction we keep until multi-awaiter wake/raise + /// plumbing lands. + fn await_external_future( + &mut self, + fut: &HeapReadMut<'h, ExternalFuture>, + awaiter: Awaiter, + ) -> Result, RunError> { + let mut awaiter_guard = DropGuard::new(awaiter, self); + let this = awaiter_guard.ctx(); + match &fut.get(this.heap).state { + ExternalFutureState::Resolved(value) => { + let value = value.clone_with_heap(this); + Ok(Poll::Ready(value)) + } + ExternalFutureState::Failed(err) => Err(err.clone()), + ExternalFutureState::Pending { awaiter: Some(_) } => { + Err(SimpleException::new_msg(ExcType::RuntimeError, "cannot reuse already awaited future").into()) + } + ExternalFutureState::Pending { awaiter: None } => { + let awaiter = awaiter_guard.into_inner(); + fut.get_mut(self.heap).state = ExternalFutureState::Pending { awaiter: Some(awaiter) }; + Ok(Poll::Pending) + } + } + } + + /// Starts execution of a coroutine by pushing its locals onto the stack. + /// + /// Extends the VM stack with the coroutine's pre-bound namespace values + /// and pushes a new frame to execute the coroutine's function body. + fn start_coroutine_frame( + &mut self, + func_id: FunctionId, + namespace_values: Vec, + globals: Option, + ) -> Result<(), RunError> { + let call_offset = self.current_offset(); + let code = &self.interns.get_function(func_id).code; + let locals_count = u16::try_from(namespace_values.len()).expect("coroutine namespace size exceeds u16"); + + // Extend the stack with the coroutine's pre-bound locals. + let stack_base = self.stack.len(); + self.stack.extend(namespace_values); + + // Push frame to execute the coroutine + let exc_stack_base = self.exception_stack.len(); + let namespace = function_namespace(globals, &*self.heap); + self.push_frame(CallFrame::new_function( + code, + stack_base, + locals_count, + exc_stack_base, + func_id, + call_offset, + namespace, + ))?; + + Ok(()) + } + + /// Selects another task after blocking, or yields to the host with the current context intact. + fn switch_or_yield(&mut self) -> Result { + if let Some(next_task_id) = self.scheduler.next_ready_task() { + self.activate_task(next_task_id)?; + Ok(AwaitResult::FramePushed) + } else { + Ok(AwaitResult::Yield(self.scheduler.pending_call_ids())) + } + } + + /// Removes a completed child and delivers its result, discarding it if its gather already settled. + /// Resumes the gather's waiter when available, otherwise the next queued task. + pub(super) fn handle_task_completion(&mut self, result: Value) -> Result { + let task_id = self + .scheduler + .current_task_id() + .expect("handle_task_completion called without current task"); + // The awaiter keeps the gather alive across task teardown. + let task = self.scheduler.get_task_mut(task_id); + let awaiter = task.awaiter.take(); + let coroutine_id = task + .coroutine_id + .expect("handle_task_completion: spawned task without a coroutine"); + + // Re-awaiting the coroutine must see that its execution has ended. + let HeapReadOutput::Coroutine(coro) = self.heap.read(coroutine_id) else { + panic!("task coroutine_id doesn't point to a Coroutine") + }; + coro.get_mut(self.heap).state = CoroutineState::Completed; + drop(coro); + + self.scheduler.cancel_task(task_id, self.heap); + + let delivery = if let Some(awaiter) = awaiter { + self.deliver_awaiter_success(awaiter, result) + } else { + result.drop_with(self); + None + }; + + self.cleanup_current_task(); + + if self.resume_after_task_exit(delivery)? { + Ok(AwaitResult::FramePushed) + } else { + Ok(AwaitResult::Yield(self.scheduler.pending_call_ids())) + } + } + + /// Returns true if the current task is a spawned task (not main). + /// + /// Used by exception handling to determine if an unhandled exception + /// should fail the task rather than propagate out. + #[inline] + pub(super) fn is_spawned_task(&self) -> bool { + self.scheduler.current_task_id().is_some_and(|id| !id.is_main()) + } + + /// Removes a child whose exception escaped its frames and notifies its gather. + /// A settled gather discards the error. Any returned error belongs to the newly active task + /// and must go through exception handling before that task executes bytecode. + pub(super) fn handle_task_failure(&mut self, error: RunError) -> Result<(), RunError> { + let task_id = self + .scheduler + .current_task_id() + .expect("handle_task_failure called without current task"); + debug_assert!(!task_id.is_main(), "handle_task_failure called for main task"); + + let awaiter = self.scheduler.get_task_mut(task_id).awaiter.take(); + let delivery = awaiter.and_then(|awaiter| self.deliver_awaiter_failure(awaiter, error)); + self.cleanup_current_task(); + self.scheduler.cancel_task(task_id, self.heap); + self.resume_after_task_exit(delivery)?; + Ok(()) + } + + /// Selects the task awakened by a child's exit, or the next queued task if none was awakened. + /// The exiting task and its VM context must already be discarded. Returns false if all tasks block. + fn resume_after_task_exit(&mut self, waiter: Option) -> RunResult { + let next = if let Some(waiter) = waiter { + self.scheduler.remove_from_ready_queue(waiter); + Some(waiter) + } else { + self.scheduler.next_ready_task() + }; + if let Some(task_id) = next { + self.activate_task(task_id)?; + Ok(true) + } else { + Ok(false) + } + } + + /// Saves the current VM context into the given task in the scheduler. + /// + /// Serializes frames, moves stack/exception_stack, stores instruction_ip, + /// and adjusts the global recursion depth counter. + fn save_task_context(&mut self, task_id: TaskId) { + let mut frames: Vec = self + .suspended_frames + .drain(..) + .map(|f| SerializedTaskFrame { + function_id: f.function_id, + ip: f.ip, + stack_base: f.stack_base(), + locals_count: f.locals_count, + exception_stack_base: f.exception_stack_base(), + call_offset: f.call_offset, + is_initializer: f.is_initializer, + namespace: f.namespace, + import_from_module: f.import_from_module, + }) + .collect(); + // The namespace moves across so the frame left behind releases nothing. + let current = &mut self.current_frame; + frames.push(SerializedTaskFrame { + function_id: current.function_id, + ip: current.ip, + stack_base: current.stack_base(), + locals_count: current.locals_count, + exception_stack_base: current.exception_stack_base(), + call_offset: current.call_offset, + is_initializer: current.is_initializer, + namespace: mem::take(&mut current.namespace), + import_from_module: current.import_from_module, + }); + + // Count this task's recursion depth contribution and subtract it from + // the global counter so the next task gets a clean budget. + let task_depth = frame_recursion_depth(frames.iter().map(|f| f.function_id), self.interns); + self.recursion_depth -= task_depth; + + // Save VM state into the task + let task = self.scheduler.get_task_mut(task_id); + task.frames = frames; + task.stack = mem::take(&mut self.stack); + task.exception_stack = mem::take(&mut self.exception_stack); + task.instruction_ip = self.instruction_ip; + } + + /// Activates a task whose queue entry was removed, taking its resume result exactly once. + /// Any returned error must be raised in the loaded context before executing bytecode. + fn activate_task(&mut self, task_id: TaskId) -> RunResult<()> { + let result = self.scheduler.take_resume_result(task_id); + if self.scheduler.current_task_id() != Some(task_id) { + if let Some(current) = self.scheduler.current_task_id() { + self.save_task_context(current); + } + self.scheduler.set_current_task(Some(task_id)); + self.load_or_init_task(task_id)?; + } + result + } + + /// Restores a task's saved context and recursion depth, or starts its coroutine on first use. + /// Resolved values are already on the saved stack. Pending exceptions are handled by `activate_task`. + fn load_or_init_task(&mut self, task_id: TaskId) -> Result<(), RunError> { + let task = self.scheduler.get_task_mut(task_id); + let frames = mem::take(&mut task.frames); + let stack = mem::take(&mut task.stack); + let exception_stack = mem::take(&mut task.exception_stack); + let instruction_ip = task.instruction_ip; + let coroutine_id = task.coroutine_id; + + // Restore this task's recursion depth contribution to the global counter + let task_depth = frame_recursion_depth(frames.iter().map(|f| f.function_id), self.interns); + self.recursion_depth += task_depth; + + if !frames.is_empty() { + // Task has existing context - restore it + self.stack = stack; + self.exception_stack = exception_stack; + self.instruction_ip = instruction_ip; + + // Reconstruct the suspended callers and current frame. + let mut frames: Vec<_> = frames + .into_iter() + .map(|sf| { + let code = frame_code(self.interns, self.module_code, sf.function_id); + CallFrame { + code, + bytecode: code.bytecode(), + ip: sf.ip, + stack_base: stack_index(sf.stack_base), + locals_count: sf.locals_count, + exception_stack_base: stack_index(sf.exception_stack_base), + function_id: sf.function_id, + call_offset: sf.call_offset, + should_return: false, + is_parked: false, + namespace: sf.namespace, + is_initializer: sf.is_initializer, + import_from_module: sf.import_from_module, + } + }) + .collect(); + self.current_frame = frames.pop().expect("task context contains no active frame"); + self.suspended_frames = frames; + } else if let Some(coro_id) = coroutine_id { + // The previous task's frames are already saved. A reused coroutine + // must fail this new task and select its successor before the + // exception can propagate. + let HeapReadOutput::Coroutine(coro) = self.heap.read(coro_id) else { + panic!("task coroutine_id doesn't point to a Coroutine") + }; + let is_new = coro.get(self.heap).state == CoroutineState::New; + // Release the handle before either branch: both go on to drop + // references to this coroutine, and freeing it under a live + // reader panics. + drop(coro); + if is_new { + self.init_task_from_coroutine(coro_id)?; + } else { + return self.handle_task_failure(ExcType::cannot_reuse_already_awaited_coroutine()); + } + } else { + // This shouldn't happen - task with no frames and no coroutine + panic!("task has no frames and no coroutine_id"); + } + + Ok(()) + } + + /// Initializes the VM state to run a coroutine for a spawned task. + /// + /// Similar to exec_get_awaitable's coroutine handling, but for task initialization. + fn init_task_from_coroutine(&mut self, coroutine_id: HeapId) -> Result<(), RunError> { + let HeapReadOutput::Coroutine(coro) = self.heap.read(coroutine_id) else { + panic!("task coroutine_id doesn't point to a Coroutine") + }; + + // Check state + if coro.get(self.heap).state != CoroutineState::New { + return Err(ExcType::cannot_reuse_already_awaited_coroutine()); + } + + // Extract coroutine data + let func_id = coro.get(self.heap).func_id; + let globals = coro.get(self.heap).globals; + let namespace_values: Vec = coro + .get(self.heap) + .namespace + .iter() + .map(|v| v.clone_with_heap(self)) + .collect(); + + // Mark coroutine as Running + coro.get_mut(self.heap).state = CoroutineState::Running; + + // Push locals onto stack and push frame directly (can't use start_coroutine_frame + // because that needs a current frame for call_offset, but spawned tasks + // don't have a parent frame — the coroutine is the root) + let code = &self.interns.get_function(func_id).code; + let locals_count = u16::try_from(namespace_values.len()).expect("coroutine namespace size exceeds u16"); + + let stack_base = self.stack.len(); + self.stack.extend(namespace_values); + + let exc_stack_base = self.exception_stack.len(); + let namespace = function_namespace(globals, &*self.heap); + self.current_frame = CallFrame::new_function( + code, + stack_base, + locals_count, + exc_stack_base, + func_id, + None, // No call position — this is the root frame for a spawned task + namespace, + ); + self.suspended_frames.clear(); + + Ok(()) + } + + /// Resolves an external future with a value. + /// + /// Called by the host when an async external call completes. Looks up + /// the `ExternalFuture` heap entry for `call_id`, transitions it to + /// `Resolved(value)`, and delivers `value` to the awaiter (if any). + pub fn resolve_future(&mut self, call_id: u32, value: Value) { + let call_id = CallId::new(call_id); + + let Some(future_id) = self.scheduler.take_pending_external(call_id) else { + value.drop_with(self); + return; + }; + + // Ensure future cleaned up on all paths + let fut_val = Value::Ref(future_id); + let this = self; + defer_drop!(fut_val, this); + + let HeapReadOutput::ExternalFuture(fut) = this.heap.read(future_id) else { + panic!("pending_externals entry doesn't point to an ExternalFuture") + }; + + // `asyncio.sleep(delay, result)`: the host's value was only the + // wake-up signal, `result` is what the await produces. + let value = match fut.get_mut(this.heap).sleep_result.take() { + Some(result) => { + value.drop_with(this); + result + } + None => value, + }; + let mut value_guard = DropGuard::new(value, this); + let (value, this) = value_guard.as_parts_mut(); + + let awaiter_and_value = match &mut fut.get_mut(this.heap).state { + ExternalFutureState::Pending { awaiter } => awaiter.take().map(|a| (a, value.clone_with_heap(this.heap))), + ExternalFutureState::Resolved(_) | ExternalFutureState::Failed(_) => { + panic!("resolve_future: future was already resolved") + } + }; + + let (value, this) = value_guard.into_parts(); + fut.get_mut(this.heap).state = ExternalFutureState::Resolved(value); + + if let Some((awaiter, value)) = awaiter_and_value { + this.deliver_awaiter_success(awaiter, value); + } + } + + /// Pushes `value` onto a blocked task's stack and queues it, returning the awakened task. + /// Drops the value if the task is gone or its awaitable has already settled. + fn deliver_value_to_task(&mut self, task_id: TaskId, value: Value) -> Option { + if !self.scheduler.is_blocked(task_id) { + value.drop_with(self); + return None; + } + + let task_is_current = self.scheduler.current_task_id() == Some(task_id) && !self.current_frame.is_parked; + if task_is_current { + self.stack.push(value); + } else { + self.scheduler.get_task_mut(task_id).stack.push(value); + } + self.scheduler.make_ready(task_id, Ok(()), self.heap); + Some(task_id) + } + + /// Delivers a value through nested gathers, queueing the terminal task if the chain completes. + /// Returns the awakened task, or `None` if a gather is pending, a gather already settled, + /// or the terminal task no longer awaits a result. + fn deliver_awaiter_success(&mut self, mut awaiter: Awaiter, mut value: Value) -> Option { + let this = self; + loop { + match awaiter { + Awaiter::Task(t) => return this.deliver_value_to_task(t, value), + Awaiter::GatherSlot { gather, source } => { + let gather_val = Value::Ref(gather); + defer_drop!(gather_val, this); + let HeapReadOutput::GatherFuture(outer) = this.heap.read(gather) else { + panic!("Awaiter::GatherSlot gather id is not a GatherFuture") + }; + let success = outer.resolve_child(this, source, value)?; + awaiter = success.awaiter; + value = Value::Ref(success.list_id); + } + } + } + } + + /// Fails each gather in the awaiter chain and queues its terminal task to raise `error`. + /// Returns that task's ID, or `None` if the task is gone or a gather already settled. + /// The task raises the exception on activation; its own gather is notified only if it escapes. + fn deliver_awaiter_failure(&mut self, awaiter: Awaiter, error: RunError) -> Option { + let this = self; + defer_drop_mut!(awaiter, this); + let target = loop { + let next = match awaiter { + Awaiter::Task(t) => break *t, + Awaiter::GatherSlot { gather, .. } => { + let HeapReadOutput::GatherFuture(gather) = this.heap.read(*gather) else { + panic!("Awaiter::GatherSlot gather id is not a GatherFuture") + }; + // A gather that already settled has handed its waiter on; + // this failure arrives after the fact and stops here. + gather.fail(this.heap, &error)? + } + }; + mem::replace(awaiter, next).drop_with(this); + }; + if !this.scheduler.is_blocked(target) { + return None; + } + this.scheduler.make_ready(target, Err(error), this.heap); + Some(target) + } + + /// Records a host rejection and queues the task that must raise it. + /// Task selection waits until the whole batch has been ingested. + pub fn fail_future(&mut self, call_id: u32, error: RunError) { + let Some(future_id) = self.scheduler.take_pending_external(CallId::new(call_id)) else { + return; + }; + let fut_val = Value::Ref(future_id); + let this = self; + defer_drop!(fut_val, this); + + let HeapReadOutput::ExternalFuture(fut) = this.heap.read(future_id) else { + panic!("pending_externals entry doesn't point to an ExternalFuture") + }; + let awaiter = match mem::replace( + &mut fut.get_mut(this.heap).state, + ExternalFutureState::Failed(error.clone()), + ) { + ExternalFutureState::Pending { awaiter } => awaiter, + ExternalFutureState::Resolved(_) | ExternalFutureState::Failed(_) => { + panic!("fail_future: future was already resolved") + } + }; + // A failed sleep never produces its result. + let sleep_result = fut.get_mut(this.heap).sleep_result.take(); + drop(fut); + sleep_result.drop_with(this); + if let Some(awaiter) = awaiter { + this.deliver_awaiter_failure(awaiter, error); + } + } + + /// Allocates an `ExternalFuture` for `call_id` and pushes a `Value::Ref` + /// to it on the VM stack. + /// + /// The scheduler indexes `call_id -> future_id` (with its own inc_ref) so + /// host resolutions can find the heap entry; the `Value::Ref` pushed onto + /// the stack is the user's reference, which travels with the value until + /// it's awaited or dropped. + pub fn add_pending_call(&mut self, call_id: CallId) { + self.push_pending_future(call_id, None); + } + + /// Like [`Self::add_pending_call`], for a host answering `asyncio.sleep` + /// with a future: the awaitable resolves with `result`, the value the + /// call was given, rather than with whatever the host resolves it with. + pub(crate) fn add_pending_sleep(&mut self, call_id: CallId, result: Value) { + self.push_pending_future(call_id, Some(result)); + } + + /// Allocates the pending `ExternalFuture`, indexes it for the host's + /// resolution and pushes it as the call's value. + fn push_pending_future(&mut self, call_id: CallId, sleep_result: Option) { + let future_id = self + .heap + .allocate(HeapData::ExternalFuture(Box::new(ExternalFuture::new_pending( + call_id, + sleep_result, + )))); + self.scheduler.add_pending_external(call_id, future_id, self.heap); + self.push(Value::Ref(future_id)); + } + + /// Allocates an `ExternalFuture` already resolved with `value`, for an OS + /// call whose result the sandbox awaits (`asyncio.sleep`). + /// + /// The host answered immediately, so nothing is registered with the + /// scheduler — awaiting the future hands the value straight back, and + /// dropping it unawaited releases the value like any other awaitable. The + /// call id is allocated rather than reused so it stays unique if the + /// future is ever inspected. + pub(crate) fn settled_awaitable(&mut self, value: Value) -> Value { + let call_id = self.allocate_call_id(); + let future = ExternalFuture { + call_id, + state: ExternalFutureState::Resolved(value), + sleep_result: None, + }; + Value::Ref(self.heap.allocate(HeapData::ExternalFuture(Box::new(future)))) + } + + /// Raises `exc` uncatchably at the suspension point, for hosts enforcing + /// a limit while execution is suspended. + /// + /// A `ResolveFutures` snapshot is parked when the last runnable task + /// finished with the rest still blocked, so the VM holds a placeholder + /// frame and every real frame lives in the scheduler. Raising there would + /// point the traceback at line 1, so the main task is reloaded first: it + /// is always alive while futures are pending, and its `await` is the + /// suspension the user sees. + pub fn abort(&mut self, exc: MontyException) -> RunResult { + let main = TaskId::default(); + if self.current_frame.is_parked && self.scheduler.main_task().is_some_and(|task| !task.frames.is_empty()) { + self.scheduler.set_current_task(Some(main)); + self.load_or_init_task(main)?; + } + self.resume_with_exception(RunError::uncatchable(exc)) + } + + /// Caches host results and wakes their awaiters without executing bytecode. + /// Eager results have no awaiter yet; their following `await` reads the cached result. + pub fn apply_future_results(&mut self, results: Vec<(u32, ExtFunctionResult)>) -> RunResult<()> { + for (call_id, ext_result) in results { + match ext_result { + ExtFunctionResult::Return(obj) => { + // A resource error is a `MemoryError` here as in `resume`, + // so a large host value is not misreported as a bad type. + let value = obj.to_value(self).map_err(|e| match e { + InvalidInputError::Resource(err) => RunError::from(err), + other @ InvalidInputError::InvalidType(_) => RunError::from(MontyException::runtime_error( + format!("Invalid return value for call {call_id}: {other}"), + )), + })?; + self.resolve_future(call_id, value); + } + ExtFunctionResult::Error(exc) => self.fail_future(call_id, RunError::from(exc)), + ExtFunctionResult::Future(_) => {} + ExtFunctionResult::NotFound(function_name) => { + self.fail_future(call_id, ExtFunctionResult::not_found_exc(&function_name)); + } + } + } + Ok(()) + } + + /// Ingests a host batch, then resumes tasks in resolution order for both values and errors. + /// With no runnable task, yields the remaining pending call IDs to the host. + /// Returns an internal error if neither runnable tasks nor pending calls remain. + pub fn resume_with_resolved_futures(&mut self, results: Vec<(u32, ExtFunctionResult)>) -> RunResult { + self.apply_future_results(results)?; + if let Some(next_task_id) = self.scheduler.next_ready_task() { + if let Err(error) = self.activate_task(next_task_id) { + return self.resume_with_exception(error); + } + return self.run_external(); + } + + let pending_call_ids = self.scheduler.pending_call_ids(); + + if pending_call_ids.is_empty() { + // A stalled turn loses one `feed_run`, aborting loses the session. + Err(RunError::internal( + "asyncio scheduler stalled: no ready tasks and no pending external calls", + )) + } else { + Ok(FrameExit::ResolveFutures(pending_call_ids)) + } + } +} + +/// One gather part-way through being committed — a frame of the walk in +/// [`VM::commit_gather_tree`], and the reason that walk needs no native stack. +/// +/// Everything the recursive commit held in local variables lives here instead: +/// the items handled so far, and where in `items` to resume once the nested +/// gather this frame descended into has settled. +struct GatherCommit { + /// The gather being committed. Borrowed — the reference is owned by the + /// parent gather's `items`, or for the root by the awaited value itself. + gather: HeapId, + /// Owned awaiter, installed on the gather when it parks in `Awaited` and + /// dropped when it settles synchronously. `Awaiter::GatherSlot` carries an + /// inc_ref on the parent gather (see [`Awaiter`]). + awaiter: Awaiter, + /// Slot in the parent frame's `results` that this gather fills; `None` for + /// the root, whose result goes to the `await` site instead. + parent_slot: Option, + /// Next index into the gather's `items` to commit. + next: usize, + /// Result slots, one per item, in `items` order. Owned values. + results: Vec>, + /// Children committed but not yet settled → the slots they fill. + pending_children: PendingChildren, +} + +impl GatherCommit { + /// Records the outcome of the nested gather this frame descended into and + /// resumes at the following item. + /// + /// A nested gather that settled synchronously fills its slot like any other + /// ready item; one that parked joins `pending_children`, so a later + /// resolution reaches this gather through [`HeapReadMut::resolve_child`]. + fn resume_after_child(&mut self, child: HeapId, slot: usize, poll: Poll) { + match poll { + Poll::Ready(value) => self.results[slot] = Some(value), + Poll::Pending => { + self.pending_children.insert(child, smallvec![slot]); + } + } + self.next = slot + 1; + } +} + +impl DropWithContext for GatherCommit { + fn drop_with(self, heap: &mut C) { + self.results.drop_with(heap); + self.awaiter.drop_with(heap); + } +} + +/// Preflights the commit stack's next reallocation against `max_memory`. +/// +/// A `Vec` grows by allocating the new buffer while the old one is still live, +/// so one growth part-way through a deep walk can add several MiB at once — +/// enough to clear the allocator's hard ceiling between two periodic checks, +/// which kills the worker rather than ending the run. +fn check_commit_stack_growth(len: usize, capacity: usize, tracker: &ResourceTracker) -> Result<(), ResourceError> { + if len == capacity { + tracker.check_allocation(2 * capacity * size_of::()) + } else { + Ok(()) + } +} + +/// Polls a gather that may already have settled, returning `None` when it is +/// still `Pending` and so needs committing. +/// +/// Shared by the `await` site and the commit walk, which face the same four +/// states: a cached result to replay, a cached error to re-raise, an in-flight +/// gather someone else owns, or work to do. +fn poll_settled_gather<'h>( + gather: &HeapRead<'h, GatherFuture>, + heap: &HeapReader<'h>, +) -> Result, RunError> { + match &gather.get(heap).state { + GatherState::Pending => Ok(None), + GatherState::Completed(value) => Ok(Some(value.clone_with_heap(heap))), + GatherState::Failed(err) => Err(err.clone()), + // TODO: support concurrent re-await (CPython does). + GatherState::Awaited(_) => Err(SimpleException::new_msg( + ExcType::RuntimeError, + "cannot reuse gather that is currently being awaited", + ) + .into()), + } +} + +/// Outcome of [`HeapReadMut::resolve_child`] when a gather has finished driving +/// its children successfully. +/// +/// `list_id` is the cached result list to hand back; `waiter` is the +/// downstream that should receive it. +pub(crate) struct GatherSuccess { + pub list_id: HeapId, + pub awaiter: Awaiter, +} + +impl<'h> HeapReadMut<'h, GatherFuture> { + /// Caches `list_id` as the gather's successful result. + /// + /// Inc_refs `list_id` so the cached state and the caller both own a ref + /// to the resulting list, then overwrites the state with + /// `GatherState::Completed(list_id)`. Used directly by + /// [`VM::await_gather_future`] for the synchronous-completion paths + /// (empty gather, all externals already resolved); on the async path the + /// transition happens inside [`Self::resolve_child`]. + pub(crate) fn cache_result(&self, heap: &mut HeapReader<'h>, list_id: HeapId) { + heap.inc_ref(list_id); + self.get_mut(heap).state = GatherState::Completed(Value::Ref(list_id)); + } + + /// Records a child's value in its result slots, completing the gather when no children remain. + /// Returns the completed result and awaiter, or `None` while other children are pending. + /// A gather that already failed discards later values while its siblings continue running. + fn resolve_child(&self, vm: &mut VM<'h>, child_id: HeapId, value: Value) -> Option { + // A sibling failed (or the commit pass rolled back) while this child + // was still running: it has a result, and nowhere for it to go. + // `Pending` is not reachable — a child only exists once awaited. + match &self.get(vm.heap).state { + GatherState::Awaited(_) => {} + GatherState::Completed(_) | GatherState::Failed(_) => { + value.drop_with(vm.heap); + return None; + } + GatherState::Pending => panic!("resolve_child called on a gather that was never awaited"), + } + + // Remove this child's slot-index mapping. + let indices: SmallVec<[usize; 1]> = self + .get_mut(vm.heap) + .as_awaited_mut() + .expect("resolve_child called on non-Awaited gather") + .pending_children + .remove(&child_id) + .expect("resolve_child: child not registered with this gather"); + + // Take `results` out so the writes can do their clones (which need + // `&Heap` access) without fighting the `&mut`-chain that + // `as_awaited_mut` requires. We put it back into the gather right + // after, before the completion scan. + let mut results = mem::take( + &mut self + .get_mut(vm.heap) + .as_awaited_mut() + .expect("resolve_child called on non-Awaited gather") + .results, + ); + if let Some((last, init)) = indices.split_last() { + for &idx in init { + results[idx] = Some(value.clone_with_heap(vm.heap)); + } + results[*last] = Some(value); + } else { + value.drop_with(vm.heap); + } + + // Restore results and check completion. + let awaited = self + .get_mut(vm.heap) + .as_awaited_mut() + .expect("gather still Awaited after recording child resolution"); + awaited.results = results; + + if !awaited.pending_children.is_empty() { + return None; + } + + // All children resolved successfully — build the result list. + // Extract this gather's awaiter (transferred into the returned + // `GatherSuccess`); the `Awaited` state remains in place until + // `cache_result` overwrites it, but its `awaiter` field is now the + // placeholder so dropping the `Awaited` payload won't double-drop + // the owned `Awaiter`. + let results = mem::take(&mut awaited.results); + let awaiter = mem::replace(&mut awaited.awaiter, Awaiter::Task(TaskId::default())); + let results: Vec = results + .into_iter() + .map(|r| r.expect("all results filled when gather is complete")) + .collect(); + let list_id = vm.heap.allocate(HeapData::List(List::new(results))); + self.cache_result(vm.heap, list_id); + Some(GatherSuccess { list_id, awaiter }) + } + + /// Caches the first failure and transfers the gather's waiter to the caller. + /// Returns `None` if already settled. Children keep running and retain their references + /// to this gather, so none can free it while the caller holds this heap reader. + pub(crate) fn fail(&self, heap: &mut HeapReader<'h>, error: &RunError) -> Option { + // Take the Awaited bookkeeping. The state stays `Awaited` (with + // placeholder fields) until the state replace below commits the + // transition. The extracted `awaiter` is transferred to the caller + // — it owns any `GatherSlot` inc_ref it carried. Already settled means + // a chain that ends here: an earlier failure cached its error and + // handed the waiter on. + let (waiter, results) = { + let awaited = self.get_mut(heap).as_awaited_mut()?; + ( + mem::replace(&mut awaited.awaiter, Awaiter::Task(TaskId::default())), + mem::take(&mut awaited.results), + ) + }; + + // Cache a clone so re-awaits replay the same exception. + self.get_mut(heap).state = GatherState::Failed(error.clone()); + + // Drop fanned-out result Values that won't reach the waiter. The + // `pending_children` map goes with the `Awaited` payload; its keys are + // borrowed ids, owned by `items`. + results.drop_with(heap); + + Some(waiter) + } +} diff --git a/crates/bashkit-monty/src/bytecode/vm/attr.rs b/crates/bashkit-monty/src/bytecode/vm/attr.rs new file mode 100644 index 000000000..2715dfbc5 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/attr.rs @@ -0,0 +1,195 @@ +//! Attribute access helpers for the VM. + +use super::VM; +use crate::{ + bytecode::{Opcode, vm::CallResult}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError}, + heap::{ContainsHeap, DropWithContext, Heap, HeapData}, + intern::{Interns, StringId}, + value::{EitherStr, Value}, +}; + +/// What a suspended lazy attribute lookup does with the host's answer when it +/// resumes, instead of pushing the value (or raising `AttributeError` on +/// `Undefined`) the way `obj.attr` does. +/// +/// Produced by the `getattr()` / `hasattr()` builtins. It rides on +/// [`CallResult::AttrLookup`] and `FrameExit::AttrLookup`, and is armed on +/// [`VM::pending_lookup_effect`] once the lookup reaches the host, so it +/// survives a dump/restore of the suspended session. A lookup that never +/// reaches a host (no host, or a synchronous nested call) is `Undefined`. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum PendingLookupEffect { + /// `hasattr()`: push `True` for a served value (which is dropped), + /// `False` for `Undefined`. + HasAttr, + /// `getattr(obj, name, default)`: push `default` for `Undefined`. Owns + /// the heap reference until the resume consumes it. + Default(Value), + /// A class-pattern attribute read (`MatchAttr`): pushes the served value + /// (or `None` for `Undefined`) itself and yields the match flag, so the + /// resumed instruction lands the same `[value, bool]` pair it pushes + /// when the attribute is answered synchronously. + MatchAttr, +} + +impl PendingLookupEffect { + /// The value to push for the host's answer: `Some(value)` for a served + /// attribute, `None` for `Undefined`. + pub(crate) fn apply(self, answer: Option, vm: &mut VM<'_>) -> Value { + match (self, answer) { + (Self::HasAttr, Some(value)) => { + value.drop_with(vm); + Value::Bool(true) + } + (Self::HasAttr, None) => Value::Bool(false), + (Self::Default(default), Some(value)) => { + default.drop_with(vm); + value + } + (Self::Default(default), None) => default, + (Self::MatchAttr, Some(value)) => { + vm.push(value); + Value::Bool(true) + } + (Self::MatchAttr, None) => { + vm.push(Value::None); + Value::Bool(false) + } + } + } +} + +impl DropWithContext for PendingLookupEffect { + fn drop_with(self, heap: &mut C) { + if let Self::Default(value) = self { + value.drop_with(heap); + } + } +} + +impl VM<'_> { + /// Loads an attribute from an object and pushes it onto the stack. + /// + /// Returns an AttributeError if the attribute doesn't exist. + pub(super) fn load_attr(&mut self, name_id: StringId) -> Result { + let this = self; + + let obj = this.pop(); + defer_drop!(obj, this); + + let attr = EitherStr::Interned(name_id); + obj.py_getattr(&attr, this) + } + + /// Loads a `from ... import` attribute, raising `ImportError` if missing. + /// `module_id` supplies the error's module name because host values need not be `Module`s. + pub(super) fn load_attr_import(&mut self, name_id: StringId, module_id: StringId) -> Result { + let this = self; + + let obj = this.pop(); + defer_drop!(obj, this); + + let attr = EitherStr::Interned(name_id); + match obj.py_getattr(&attr, this) { + Ok(result) => Ok(result), + Err(RunError::Exc(exc)) if exc.exc.exc_type() == ExcType::AttributeError => { + let name_str = this.interns.get_str(name_id); + Err(ExcType::cannot_import_name(name_str, this.interns.get_str(module_id))) + } + Err(e) => Err(e), + } + } + + /// Replaces the stack top with the next submodule of a dotted import. + /// Missing attributes raise `ModuleNotFoundError` naming `path_id`. Modules also + /// reject non-module attributes (`math.pi`, the host-served `os.environ`); bundled + /// ones add "is not a package" to errors, host modules being packages. + pub(super) fn load_submodule(&mut self, name_id: StringId, path_id: StringId) -> Result { + let this = self; + + let obj = this.pop(); + defer_drop!(obj, this); + + let package = module_package(obj, this.heap); + let is_builtin = package == Some(false); + let attr = EitherStr::Interned(name_id); + match obj.py_getattr(&attr, this) { + Ok(CallResult::Value(value)) if package.is_some() && module_package(&value, this.heap).is_some() => { + Ok(CallResult::Value(value)) + } + // a property's OS call (`os.environ`) is no more a submodule than a value + Ok(result) if package.is_some() => { + result.drop_with(this); + Err(not_a_submodule(this.interns, path_id, is_builtin)) + } + Ok(result) => Ok(result), + Err(RunError::Exc(exc)) if exc.exc.exc_type() == ExcType::AttributeError => { + Err(not_a_submodule(this.interns, path_id, is_builtin)) + } + Err(e) => Err(e), + } + } + + /// Returns the suspended `LoadSubmodule` path for errors from lazy attribute lookups. + pub(crate) fn suspended_submodule(&self) -> Option { + let ip = self.instruction_ip; + let bytecode = self.current_frame.bytecode; + (bytecode.get(ip) == Some(&(Opcode::LoadSubmodule as u8))).then(|| { + // operands: u16 attribute name_id, then u16 path name_id, little-endian + StringId::from_index(u16::from_le_bytes([bytecode[ip + 3], bytecode[ip + 4]])) + }) + } + + /// Returns the suspended `LoadAttrImport` module for errors from lazy attribute lookups. + pub(crate) fn suspended_import_from(&self) -> Option { + let frame = &self.current_frame; + (frame.bytecode.get(self.instruction_ip) == Some(&(Opcode::LoadAttrImport as u8))) + .then_some(frame.import_from_module) + .flatten() + } + + /// Returns the suspended `LoadModule` name, distinguishing imports from calls to `__import__`. + pub(crate) fn suspended_import(&self) -> Option { + let ip = self.instruction_ip; + let bytecode = self.current_frame.bytecode; + (bytecode.get(ip) == Some(&(Opcode::LoadModule as u8))).then(|| { + // operand: u16 module name_id, little-endian + StringId::from_index(u16::from_le_bytes([bytecode[ip + 1], bytecode[ip + 2]])) + }) + } + + /// Stores a value as an attribute on an object. + /// + /// Returns an AttributeError if the attribute cannot be set. + pub(super) fn store_attr(&mut self, name_id: StringId) -> Result<(), RunError> { + let this = self; + + let obj = this.pop(); + defer_drop!(obj, this); + + let value = this.pop(); + // py_set_attr takes ownership of value and drops it on error + obj.py_set_attr(&EitherStr::Interned(name_id), value, this) + } +} + +/// `Some(is_package)` when `value` is a module: a host module is a package +/// (its submodules are module attributes), a bundled one is not. +fn module_package(value: &Value, heap: &Heap) -> Option { + match value { + Value::Ref(id) => match heap.get(*id) { + HeapData::Module(module) => Some(module.id().is_some()), + _ => None, + }, + _ => None, + } +} + +/// Builds a missing-submodule error using the import's spelling of a built-in parent (`os.path`). +fn not_a_submodule(interns: &Interns, path_id: StringId, is_builtin: bool) -> RunError { + let path = interns.get_str(path_id); + let parent = is_builtin.then(|| path.rsplit_once('.').map_or(path, |(parent, _)| parent)); + ExcType::module_not_found_error(path, parent) +} diff --git a/crates/bashkit-monty/src/bytecode/vm/binary.rs b/crates/bashkit-monty/src/bytecode/vm/binary.rs new file mode 100644 index 000000000..f86f729c1 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/binary.rs @@ -0,0 +1,199 @@ +//! Unary, binary and in-place operation helpers for the VM. + +use super::VM; +use crate::{ + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::DropGuard, + types::PyTrait, + value::Value, +}; + +impl VM<'_> { + /// Unary minus (`-x`). + pub(super) fn unary_neg(&mut self) -> Result<(), RunError> { + self.unary_op(PyTrait::py_neg_impl, "-") + } + + /// Unary plus (`+x`) — an identity for numbers, but not for `bool` + /// (`+True` is `1`) or a `Counter` (which drops its non-positive counts). + pub(super) fn unary_pos(&mut self) -> Result<(), RunError> { + self.unary_op(PyTrait::py_pos_impl, "+") + } + + /// Bitwise inversion (`~x`). + pub(super) fn unary_invert(&mut self) -> Result<(), RunError> { + self.unary_op(PyTrait::py_invert_impl, "~") + } + + /// Binary addition. + pub(super) fn binary_add(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_add(rhs, vm)) + } + + /// Binary subtraction. + pub(super) fn binary_sub(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_sub(rhs, vm)) + } + + /// Binary multiplication. + pub(super) fn binary_mult(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_mul(rhs, vm)) + } + + /// Binary division. + pub(super) fn binary_div(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_truediv(rhs, vm)) + } + + /// Binary floor division. + pub(super) fn binary_floordiv(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_floordiv(rhs, vm)) + } + + /// Binary modulo. + pub(super) fn binary_mod(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_mod(rhs, vm)) + } + + /// Binary power. + #[inline(never)] + pub(super) fn binary_pow(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_pow(rhs, None, vm)) + } + + /// Binary `&`. + pub(super) fn binary_and(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_and(rhs, vm)) + } + + /// Binary `|`. + pub(super) fn binary_or(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_or(rhs, vm)) + } + + /// Binary `^`. + pub(super) fn binary_xor(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_xor(rhs, vm)) + } + + /// Binary left shift. + pub(super) fn binary_lshift(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_lshift(rhs, vm)) + } + + /// Binary right shift. + pub(super) fn binary_rshift(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_rshift(rhs, vm)) + } + + /// In-place addition. + /// + /// Mutable types (a list, a `Counter`, a `deque` whose `+=` is `extend`) + /// mutate through `py_iadd_impl` and keep their identity, so an alias sees + /// the update; immutable ones fall back to ordinary addition. Uses lazy type + /// capture: only calls `py_type()` in error paths. + pub(super) fn inplace_add(&mut self) -> Result<(), RunError> { + self.inplace_op(PyTrait::py_iadd_impl, |lhs, rhs, vm| { + if let Some(value) = lhs.py_add_result(rhs, vm)? { + Ok(value) + } else { + let lhs_type = lhs.py_type(vm); + Err(ExcType::binary_type_error( + "+=", + lhs_type, + lhs.py_type_name(vm), + rhs.py_type_name(vm), + )) + } + }) + } + + /// `-=` — an in-place mutation (a `Counter` subtracts counts), or binary `-`. + pub(super) fn inplace_sub(&mut self) -> Result<(), RunError> { + self.inplace_op(PyTrait::py_isub_impl, |lhs, rhs, vm| lhs.py_sub(rhs, vm)) + } + + /// `&=` — an in-place mutation (a `Counter` intersects counts), or binary `&`. + pub(super) fn inplace_and(&mut self) -> Result<(), RunError> { + self.inplace_op(PyTrait::py_iand_impl, |lhs, rhs, vm| lhs.py_and(rhs, vm)) + } + + /// `|=` — an in-place mutation (a `Counter` unions counts), or binary `|`. + pub(super) fn inplace_or(&mut self) -> Result<(), RunError> { + self.inplace_op(PyTrait::py_ior_impl, |lhs, rhs, vm| lhs.py_or(rhs, vm)) + } + + /// Binary matrix multiplication (`@` operator). + pub(super) fn binary_matmul(&mut self) -> Result<(), RunError> { + self.binary_op(|lhs, rhs, vm| lhs.py_matmul(rhs, vm)) + } + + /// Applies a unary operation while owning stack-value cleanup, raising + /// CPython's `TypeError` (naming `symbol`) when the type has no such form. + fn unary_op( + &mut self, + operation: impl FnOnce(&Value, &mut Self) -> RunResult>, + symbol: &str, + ) -> Result<(), RunError> { + let this = self; + + let value = this.pop(); + defer_drop!(value, this); + + if let Some(result) = operation(value, this)? { + this.push(result); + Ok(()) + } else { + Err(ExcType::unary_type_error(symbol, &value.py_type_name(this))) + } + } + + /// Applies a binary operation while owning stack-value cleanup. + fn binary_op( + &mut self, + operation: impl FnOnce(&Value, &Value, &mut Self) -> RunResult, + ) -> Result<(), RunError> { + let this = self; + + let rhs = this.pop(); + defer_drop!(rhs, this); + let lhs = this.pop(); + defer_drop!(lhs, this); + + let result = operation(lhs, rhs, this)?; + this.push(result); + Ok(()) + } + + /// Applies an in-place operation, offering the left operand `inplace` (its + /// `py_i*_impl` hook) first and otherwise falling back to `binary`. + /// + /// A hook reporting `true` has mutated the left operand, which is pushed + /// back so it keeps its identity; `false` means the type has no in-place + /// form and the ordinary binary operator produces a fresh value. + fn inplace_op( + &mut self, + inplace: impl FnOnce(&mut Value, &Value, &mut Self) -> RunResult, + binary: impl FnOnce(&Value, &Value, &mut Self) -> RunResult, + ) -> Result<(), RunError> { + let this = self; + + let rhs = this.pop(); + defer_drop!(rhs, this); + // A `DropGuard` rather than `defer_drop!`: a successful in-place operation + // reclaims the left operand to push it back onto the stack. + let mut lhs_guard = DropGuard::new(this.pop(), this); + let (lhs, this) = lhs_guard.as_parts_mut(); + + if inplace(lhs, rhs, this)? { + let (lhs, this) = lhs_guard.into_parts(); + this.push(lhs); + Ok(()) + } else { + let result = binary(lhs, rhs, this)?; + this.push(result); + Ok(()) + } + } +} diff --git a/crates/bashkit-monty/src/bytecode/vm/call.rs b/crates/bashkit-monty/src/bytecode/vm/call.rs new file mode 100644 index 000000000..03fc31fa9 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/call.rs @@ -0,0 +1,1283 @@ +//! Function call helpers for the VM. +//! +//! This module contains the implementation of call-related opcodes and helper +//! functions for executing function calls. The main entry points are the `exec_*` +//! methods which are called from the VM's main dispatch loop. + +use std::mem; + +use monty_types::{MontyUuid, OsFunctionCall}; + +use super::{CallFrame, VM, attr::PendingLookupEffect, function_namespace, recursion::RunReentryGuard}; +use crate::{ + args::{ArgValues, KwargsValues}, + asyncio::Coroutine, + builtins::{BuiltinsFunctions, BuiltinsFunctionsExt}, + bytecode::FrameExit, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + frozen::FrozenFunction, + function::{ExactPositionalCall, Function}, + heap::{ContainsHeap, DropGuard, DropWithContext, HeapData, HeapId}, + heap_data::CellValue, + intern::{FunctionId, StaticStrings, StringId}, + modules::dataclasses, + os_dispatch::{PendingEffect, release_pending_effect}, + resource_checks::check_estimated_size, + types::{Dict, Instance, PyTrait, Type, instance::class_name}, + value::{EitherStr, VALUE_SIZE, Value}, +}; + +/// Result of executing a call or attribute method. +/// +/// Used by the `exec_*` methods and `py_call_attr` implementations to communicate +/// what action the VM's main loop should take after the call completes. +/// +/// For attribute methods that complete synchronously, use `CallResult::Value`. +/// For operations requiring host involvement (OS calls, external functions, etc.), +/// use the appropriate variant to signal the VM to yield. +pub(crate) enum CallResult { + /// Call completed synchronously with a return value. + Value(Value), + /// A defined function became the VM's current frame. + /// Propagate or require synchronous completion; dropping this result does not pop the frame. + FramePushed, + /// External function call requested - VM should pause and return to caller. + /// The `EitherStr` is the name of the external function (interned or heap-owned). + External(EitherStr, ArgValues), + /// OS operation call requested - VM should yield `FrameExit::OsCall` to host. + /// + /// The host executes the OS operation and resumes the VM with the result. + /// The [`OsFunctionCall`] is a tagged enum whose variants carry their own + /// typed args, so no separate `ArgValues` is needed at this layer. + OsCall(OsFunctionCall), + /// Host-routed call requested - VM should yield `FrameExit::MethodCall` + /// to host: a method call on a host-backed instance, or on a host class + /// type — a classmethod, or construction, which is spelled `__call__`. + /// + /// The receiver is NOT included in `args`: the host routes the call by + /// `object_id`, the receiver's uuid (stored on the [`HostClass`] / + /// [`HostClassType`]). Unlike `External`, `name` is an `EitherStr` + /// because method names are only known at runtime. + /// + /// [`HostClass`]: crate::types::HostClass + /// [`HostClassType`]: crate::types::HostClassType + MethodCall { + name: EitherStr, + args: ArgValues, + object_id: MontyUuid, + }, + /// Lazy attribute lookup on a host-backed object - VM should yield + /// `FrameExit::AttrLookup` to host. + /// + /// Produced by `obj.attr` (or `Type.attr` when `type_object` is true) + /// and by `getattr()` / `hasattr()` when `attr` is public and missing + /// from the eager attrs. `class_name` is captured at suspension so the + /// resume-undefined AttributeError names the real class without touching + /// the heap. + AttrLookup { + name: EitherStr, + class_name: String, + object_id: MontyUuid, + /// True for a lookup on a class type object — selects CPython's + /// `type object '...' has no attribute ...` message on failure. + type_object: bool, + /// How `getattr()` / `hasattr()` consume the answer; `None` for + /// `obj.attr`. The only heap reference this variant can carry. + effect: Option, + }, + /// The call returned a value that should be implicitly awaited. + /// + /// Used by `asyncio.run()` to execute a coroutine without an explicit `await`. + /// The VM will push the value onto the stack and execute `exec_get_awaitable`. + AwaitValue(Value), + /// OS call whose result must be post-processed on resume via a + /// [`PendingEffect`] instead of being pushed onto the operand stack raw. + /// + /// Used by buffered file reads (`BufferStore`), buffered writes + /// (`WritePosition`), and `os.listdir` (`ListdirNames`). The effect stays + /// *in* the value, handed on to `FrameExit::OsCall`, so a call rejected on + /// the way out cannot corrupt the next OS call's resume. + OsCallWithEffect { + call: OsFunctionCall, + effect: PendingEffect, + }, +} + +impl CallResult { + /// Completes a call at a Rust boundary that cannot yield to the host. + /// Python frames still run; unsupported suspensions are raised inside them and cleaned up. + /// Consume immediately after dispatch, before running any of the installed frame's bytecode. + pub(crate) fn require_synchronous(self, vm: &mut VM<'_>) -> RunResult { + if matches!(self, Self::FramePushed) { + if let Err(error) = vm.enter_run_reentry() { + // Dispatch already installed this frame, but it has not executed an instruction. + let instruction_ip = vm.instruction_ip; + vm.pop_frame(); + vm.instruction_ip = instruction_ip; + return Err(error.into()); + } + let mut guard = RunReentryGuard::new(vm); + self.finish_synchronously(&mut guard) + } else { + self.finish_synchronously(vm) + } + } + + /// Runs under the caller's native re-entry reservation when a frame needs execution. + fn finish_synchronously(self, vm: &mut VM<'_>) -> RunResult { + match self { + Self::Value(value) => Ok(value), + // With no host to answer, `hasattr` and `getattr` see an undefined attribute. + Self::AttrLookup { + effect: Some(effect), .. + } => Ok(effect.apply(None, vm)), + Self::FramePushed => { + // Stop both normal returns and exception unwinding before the Rust caller's frame. + vm.current_frame_mut().should_return = true; + loop { + match vm.run()? { + FrameExit::Return(value) => return Ok(value), + FrameExit::AttrLookup { + effect: Some(effect), .. + } => { + let value = effect.apply(None, vm); + vm.push(value); + } + exit => { + let error = vm.unsupported_frame_exit(exit); + if let Some(error) = vm.handle_exception(error) { + return Err(error); + } + } + } + } + } + unsupported => Err(vm.unsupported_call_result(unsupported)), + } + } +} + +impl DropWithContext for CallResult { + fn drop_with(self, heap: &mut C) { + match self { + Self::Value(value) | Self::AwaitValue(value) => value.drop_with(heap), + Self::External(_, args) | Self::MethodCall { args, .. } => { + args.drop_with(heap); + } + Self::OsCall(call) => call.drop_with(heap), + Self::AttrLookup { effect, .. } => effect.drop_with(heap), + Self::FramePushed => {} + Self::OsCallWithEffect { call, effect } => { + call.drop_with(heap); + // Discarded before it ever became a `FrameExit`. + release_pending_effect(Some(effect), heap); + } + } + } +} + +impl<'h> VM<'h> { + // ======================================================================== + // Call Opcode Executors + // ======================================================================== + // These methods are called from the VM's main dispatch loop to execute + // call-related opcodes. They handle stack operations and return a result + // indicating what the VM should do next. + + /// Executes `CallFunction` opcode. + /// + /// Pops the callable and arguments from the stack, calls the function, + /// and returns the result. + pub(super) fn exec_call_function(&mut self, arg_count: usize) -> Result { + let callable_index = self.stack.len() - arg_count - 1; + if let Value::DefFunction(func_id) = self.stack[callable_index] + && let Some(result) = self.try_call_exact_def_function(func_id, callable_index, arg_count) + { + result + } else { + let args = self.pop_n_args(arg_count); + let callable = self.pop(); + let this = self; + defer_drop!(callable, this); + this.call_function(callable, args) + } + } + + /// Executes `CallBuiltinFunction` opcode. + /// + /// Calls a builtin function directly without stack manipulation for the callable. + /// This is an optimization that avoids constant pool lookup and stack manipulation. + pub(super) fn exec_call_builtin_function( + &mut self, + builtin_id: u8, + arg_count: usize, + ) -> Result { + // Convert u8 to BuiltinsFunctions via FromRepr + if let Some(builtin) = BuiltinsFunctions::from_repr(builtin_id) { + let args = self.pop_n_args(arg_count); + builtin.call(self, args) + } else { + Err(RunError::internal("CallBuiltinFunction: invalid builtin_id")) + } + } + + /// Executes `CallBuiltinType` opcode. + /// + /// Calls a builtin type constructor directly without stack manipulation for the callable. + /// This is an optimization for type constructors like `list()`, `int()`, `str()`. + pub(super) fn exec_call_builtin_type(&mut self, type_id: u8, arg_count: usize) -> Result { + // Convert u8 to Type via callable_from_u8 + if let Some(t) = Type::callable_from_u8(type_id) { + let args = self.pop_n_args(arg_count); + t.call(self, args) + } else { + Err(RunError::internal("CallBuiltinType: invalid type_id")) + } + } + + /// Executes `CallFunctionKw` opcode. + /// + /// Reads `kw_count` keyword name operands from the instruction stream, + /// pops the keyword values, positional args, and callable from the stack, + /// builds the appropriate `ArgValues`, and calls the function. + pub(super) fn exec_call_function_kw(&mut self, pos_count: usize, kw_count: usize) -> Result { + // Pop keyword values (TOS is last kwarg value) + let kw_values = self.pop_n(kw_count); + + // Pop positional arguments + let pos_args = self.pop_n(pos_count); + + // Pop the callable + let callable = self.pop(); + let this = self; + defer_drop!(callable, this); + + // Build kwargs directly as Vec<(StringId, Value)> + let mut kwargs_inline = Vec::with_capacity(kw_count); + for value in kw_values { + let name_id = StringId::from_index(this.current_frame.fetch_u16()); + kwargs_inline.push((name_id, value)); + } + + // Build ArgValues with both positional and keyword args + let args = if pos_args.is_empty() && kwargs_inline.is_empty() { + ArgValues::Empty + } else if pos_args.is_empty() { + ArgValues::Kwargs(KwargsValues::Inline(kwargs_inline)) + } else { + ArgValues::ArgsKargs { + args: pos_args, + kwargs: KwargsValues::Inline(kwargs_inline), + } + }; + + this.call_function(callable, args) + } + + /// Executes `CallAttr` opcode. + /// + /// Pops the object and arguments from the stack, calls the attribute, + /// and returns a `CallResult` which may indicate an OS or external call. + pub(super) fn exec_call_attr(&mut self, name_id: StringId, arg_count: usize) -> Result { + let args = self.pop_n_args(arg_count); + let obj = self.pop(); + self.call_attr(obj, name_id, args) + } + + /// Executes `CallAttrKw` opcode. + /// + /// Reads `kw_count` keyword name operands from the instruction stream, + /// pops the keyword values, positional args, and object from the stack, + /// builds the appropriate `ArgValues`, and calls the attribute. + /// Returns a `CallResult` which may indicate an OS or external call. + pub(super) fn exec_call_attr_kw( + &mut self, + name_id: StringId, + pos_count: usize, + kw_count: usize, + ) -> Result { + // Pop keyword values (TOS is last kwarg value) + let kw_values = self.pop_n(kw_count); + + // Pop positional arguments + let pos_args = self.pop_n(pos_count); + + // Pop the object + let obj = self.pop(); + + // Build kwargs directly as Vec<(StringId, Value)> + let mut kwargs_inline = Vec::with_capacity(kw_count); + for value in kw_values { + let kw_name_id = StringId::from_index(self.current_frame.fetch_u16()); + kwargs_inline.push((kw_name_id, value)); + } + + // Build ArgValues with both positional and keyword args + let args = if pos_args.is_empty() && kwargs_inline.is_empty() { + ArgValues::Empty + } else if pos_args.is_empty() { + ArgValues::Kwargs(KwargsValues::Inline(kwargs_inline)) + } else { + ArgValues::ArgsKargs { + args: pos_args, + kwargs: KwargsValues::Inline(kwargs_inline), + } + }; + + self.call_attr(obj, name_id, args) + } + + /// Executes `CallFunctionExtended` opcode. + /// + /// Handles calls with `*args` and/or `**kwargs` unpacking. + pub(super) fn exec_call_function_extended(&mut self, has_kwargs: bool) -> Result { + // Pop kwargs dict if present + let kwargs = if has_kwargs { Some(self.pop()) } else { None }; + + // Pop args tuple + let args_tuple = self.pop(); + + // Pop callable + let callable = self.pop(); + + // Unpack and call + self.call_function_extended(callable, args_tuple, kwargs) + } + + /// Executes `CallAttrExtended` opcode. + /// + /// Handles method calls with `*args` and/or `**kwargs` unpacking. + pub(super) fn exec_call_attr_extended( + &mut self, + name_id: StringId, + has_kwargs: bool, + ) -> Result { + // Pop kwargs dict if present + let kwargs = if has_kwargs { Some(self.pop()) } else { None }; + + // Pop args tuple + let args_tuple = self.pop(); + + // Pop the receiver object + let obj = self.pop(); + + // Unpack and call + self.call_attr_extended(obj, name_id, args_tuple, kwargs) + } + + // ======================================================================== + // Internal Call Helpers + // ======================================================================== + + /// Pops n arguments from the stack and wraps them in `ArgValues`. + fn pop_n_args(&mut self, n: usize) -> ArgValues { + match n { + 0 => ArgValues::Empty, + 1 => ArgValues::One(self.pop()), + 2 => { + let b = self.pop(); + let a = self.pop(); + ArgValues::Two(a, b) + } + _ => ArgValues::ArgsKargs { + args: self.pop_n(n), + kwargs: KwargsValues::Empty, + }, + } + } + + /// Calls an attribute on an object. + /// + /// Logical dispatch hides interned versus heap storage and preserves suspendable + /// results for methods requiring host involvement. + /// + /// **Dunder dispatch**: before reaching the type-specific dispatcher, this + /// method intercepts known dunder names (`__enter__`, `__exit__`, …) and + /// routes them to the corresponding [`PyTrait`] method + /// (`py_enter` / `py_exit` / …). The default trait impls return + /// `AttributeError`, so types that don't override the dunder behave + /// identically to a generic "no such method" lookup; types that *do* + /// override only need a single trait impl, not parallel `StaticStrings::Foo` + /// arms in their `py_call_attr` body. New dunder methods plug into the + /// dispatch table here without touching individual types. + pub(crate) fn call_attr(&mut self, obj: Value, name_id: StringId, args: ArgValues) -> Result { + let this = self; + let attr = EitherStr::Interned(name_id); + + // Centralised dunder dispatch — see `dispatch_dunder`. Wrap `args` + // in an `Option` so the helper can `take()` it only when it + // actually matches a dunder; on the fall-through path the + // original `args` is still owned here and goes into `py_call_attr`. + let mut args_slot = Some(args); + if let Value::Ref(heap_id) = obj + && let Some(result) = dispatch_dunder(name_id, heap_id, this, &mut args_slot) + { + defer_drop!(obj, this); + return result; + } + let args = args_slot.expect("dispatch_dunder returned None without taking args"); + + defer_drop!(obj, this); + obj.py_value(this).py_call_attr(this, &attr, args) + } + + /// Evaluates a function in a synchronous position that cannot suspend to the host. + /// + /// User-defined functions run until their frame returns. An unresolved name raises + /// `NameError`; external, OS, method, and future suspensions raise a variant-specific + /// `NotImplementedError` because this context cannot preserve and resume its state. + /// These are raised at the suspension point inside the callee's frames, so the + /// callee can catch them with an ordinary `try`/`except` like any other exception. + /// + /// The nested `self.run()` below recurses on the native Rust stack, so + /// re-entry is bounded via [`enter_run_reentry`](Self::enter_run_reentry) + /// at entry — before `call_function`, since a class-valued `__init__` can + /// recurse back in without ever pushing a frame. + pub(crate) fn evaluate_function(&mut self, callable: &Value, args: ArgValues) -> Result { + if let Err(e) = self.enter_run_reentry() { + // Bailing before `call_function` takes ownership of `args`, so + // reclaim its refcounts here. + args.drop_with(self); + return Err(e.into()); + } + let mut guard = RunReentryGuard::new(self); + let this = &mut *guard; + + this.call_function(callable, args)?.finish_synchronously(this) + } + + /// Converts a direct call suspension into a specific synchronous-context error. + #[cold] + fn unsupported_call_result(&mut self, result: CallResult) -> RunError { + let error = match &result { + CallResult::External(function_name, _) => { + ExcType::not_implemented_synchronous_call("external function", function_name.as_str(self.interns)) + } + CallResult::OsCall(call) | CallResult::OsCallWithEffect { call, .. } => { + ExcType::not_implemented_synchronous_call("OS function", call.name()) + } + CallResult::MethodCall { name, .. } => { + ExcType::not_implemented_synchronous_call("method call", name.as_str(self.interns)) + } + // A lazy attribute lookup cannot suspend in a synchronous nested + // context; report the attribute as missing rather than a + // NotImplementedError, matching what an unanswered lookup raises + // (an `effect` was consumed by the caller before reaching here). + CallResult::AttrLookup { + name, + class_name, + type_object, + .. + } => { + let error = if *type_object { + ExcType::attribute_error_type(class_name, name.as_str(self.interns)) + } else { + ExcType::attribute_error(class_name, name.as_str(self.interns)) + }; + result.drop_with(self); + return error; + } + CallResult::AwaitValue(_) => ExcType::not_implemented("cannot await a value in this synchronous context"), + CallResult::Value(_) | CallResult::FramePushed => unreachable!("completed calls are handled above"), + }; + result.drop_with(self); + error.into() + } + + /// Converts a nested VM suspension into a specific synchronous-context error. + #[cold] + pub(crate) fn unsupported_frame_exit(&mut self, exit: FrameExit) -> RunError { + let error = match &exit { + FrameExit::Return(_) => unreachable!("return exits are handled above"), + FrameExit::ExternalCall { function_name, .. } => { + ExcType::not_implemented_synchronous_call("external function", function_name.as_str(self.interns)) + } + FrameExit::OsCall { function_call, .. } => { + ExcType::not_implemented_synchronous_call("OS function", function_call.name()) + } + FrameExit::MethodCall { method_name, .. } => { + ExcType::not_implemented_synchronous_call("method call", method_name.as_str(self.interns)) + } + // Same as the `CallResult::AttrLookup` arm above. + FrameExit::AttrLookup { + name, + class_name, + type_object, + .. + } => { + let error = if *type_object { + ExcType::attribute_error_type(class_name, name.as_str(self.interns)) + } else { + ExcType::attribute_error(class_name, name.as_str(self.interns)) + }; + exit.drop_with(self); + return error; + } + FrameExit::ResolveFutures(_) => { + ExcType::not_implemented("cannot resolve async futures in this synchronous context") + } + FrameExit::NameLookup { name_id, .. } => ExcType::name_error(self.interns.get_str(*name_id)), + }; + exit.drop_with(self); + error.into() + } + + /// Calls a callable value with the given arguments. + /// + /// Dispatches based on the callable type: + /// - `Value::Builtin`: calls builtin directly, returns `Push` + /// - `Value::ModuleFunction`: calls module function directly, returns `Push` + /// - `Value::DefFunction`: pushes a new frame, returns `FramePushed` + /// - `Value::Ref`: checks for closure/function on heap + pub(crate) fn call_function(&mut self, callable: &Value, args: ArgValues) -> Result { + match callable { + Value::Builtin(builtin) => builtin.call(self, args), + Value::ModuleFunction(mf) => mf.call(self, args), + Value::DefFunction(func_id) => { + // Defined function without defaults, captured variables or a globals dict + self.call_def_function(*func_id, &[], &[], None, args) + } + Value::Ref(heap_id) => { + // Could be a closure or function with defaults - check heap + self.call_heap_callable(*heap_id, args) + } + _ => { + // Coupling check: reaching here means dispatch rejected the value, + // so `Value::is_callable` must agree it is not callable. + debug_assert!( + !callable.is_callable(self), + "Value::is_callable accepts a value call_function rejects — the two drifted" + ); + args.drop_with(self); + let ty = callable.py_type_name(self); + Err(ExcType::type_error(format!("'{ty}' object is not callable"))) + } + } + } + + /// Calls a heap value, delegating to the type's own [`PyTrait::py_call`]. + /// + /// Each callable type owns its dispatch, so this only reads the value and + /// hands the arguments over — a new callable type is added by implementing + /// `py_call`, not by extending anything here. The default `py_call` raises + /// the same `TypeError` the rejected arm used to, so a value that is not + /// callable is refused without a branch of its own. + fn call_heap_callable(&mut self, heap_id: HeapId, args: ArgValues) -> Result { + self.heap.read(heap_id).py_call(args, self) + } + + /// Calls a function with unpacked args tuple and optional kwargs dict. + /// + /// Used for `f(*args)` and `f(**kwargs)` style calls. + fn call_function_extended( + &mut self, + callable: Value, + args_tuple: Value, + kwargs: Option, + ) -> Result { + let this = self; + defer_drop!(args_tuple, this); + defer_drop!(callable, this); + // Building the argument pack is fallible (a refused `*args` clone) and the + // kwargs are handed on only once it succeeds, so the guard releases them on + // the error paths in between. + let mut pending_kwargs = DropGuard::new(kwargs, this); + let (pending, this) = pending_kwargs.as_parts_mut(); + + // Extract positional args from tuple + let copied_args = this.extract_args_tuple(args_tuple)?; + + // Build ArgValues from positional args and optional kwargs + let args = if let Some(kwargs_ref) = pending.take() { + this.build_args_with_kwargs(copied_args, kwargs_ref)? + } else { + Self::build_args_positional_only(copied_args) + }; + + // Call the function (args_tuple guard drops at scope exit) + this.call_function(callable, args) + } + + /// Calls a method with unpacked args tuple and optional kwargs dict. + /// + /// Used for `obj.method(*args)` and `obj.method(**kwargs)` style calls. + fn call_attr_extended( + &mut self, + obj: Value, + name_id: StringId, + args_tuple: Value, + kwargs: Option, + ) -> Result { + let this = self; + defer_drop!(args_tuple, this); + // Building the argument pack is fallible (a refused `*args` clone, a kwargs + // dict that cannot grow) and the receiver and kwargs are handed on only once + // it succeeds, so the guard releases them on the error paths in between. + let mut pending = DropGuard::new((obj, kwargs), this); + let (pending_values, this) = pending.as_parts_mut(); + + // Extract positional args from tuple + let copied_args = this.extract_args_tuple_for_attr(args_tuple)?; + + // Build ArgValues from positional args and optional kwargs + let args = if let Some(kwargs_ref) = pending_values.1.take() { + this.build_args_with_kwargs_for_attr(copied_args, kwargs_ref)? + } else { + Self::build_args_positional_only(copied_args) + }; + + // Call the method (args_tuple guard drops at scope exit) + let ((obj, _), this) = pending.into_parts(); + this.call_attr(obj, name_id, args) + } + + /// Extracts arguments from a tuple for `CallFunctionExtended`. + /// + /// # Panics + /// Panics if `args_tuple` is not a tuple. This indicates a compiler bug since + /// the compiler always emits `ListToTuple` before `CallFunctionExtended`. + fn extract_args_tuple(&mut self, args_tuple: &Value) -> RunResult> { + let Value::Ref(id) = args_tuple else { + unreachable!("CallFunctionExtended: args_tuple must be a Ref") + }; + let HeapData::Tuple(tuple) = self.heap.get(*id) else { + unreachable!("CallFunctionExtended: args_tuple must be a Tuple") + }; + clone_args_from_tuple(tuple.as_slice(), self) + } + + /// Builds `ArgValues` with kwargs for `CallFunctionExtended`. + /// + /// # Panics + /// Panics if `kwargs_ref` is not a dict. This indicates a compiler bug since + /// the compiler always emits `BuildDict` before `CallFunctionExtended` with kwargs. + fn build_args_with_kwargs(&mut self, copied_args: Vec, kwargs_ref: Value) -> Result { + let this = self; + defer_drop!(kwargs_ref, this); + + // Extract kwargs dict items + let Value::Ref(id) = kwargs_ref else { + unreachable!("CallFunctionExtended: kwargs must be a Ref") + }; + let HeapData::Dict(dict) = this.heap.get(*id) else { + unreachable!("CallFunctionExtended: kwargs must be a Dict") + }; + let copied_kwargs: Vec<(Value, Value)> = dict + .iter() + .map(|(k, v)| (k.clone_with_heap(this), v.clone_with_heap(this))) + .collect(); + + // `copied_args` travels unguarded through this `?`, which is sound only + // because `from_pairs` cannot fail here: it sizes both dict buffers to the + // pair count up front so the growth preflight is a no-op, and keys taken out + // of a dict are already known hashable. Size that dict lazily and this leaks + // the args. + let kwargs_values = if copied_kwargs.is_empty() { + KwargsValues::Empty + } else { + let kwargs_dict = Dict::from_pairs(copied_kwargs, this)?; + KwargsValues::Dict(kwargs_dict) + }; + + Ok(ArgValues::from_parts(copied_args, kwargs_values)) + } + + /// Builds `ArgValues` from positional args only. + fn build_args_positional_only(copied_args: Vec) -> ArgValues { + match copied_args.len() { + 0 => ArgValues::Empty, + 1 => ArgValues::One(copied_args.into_iter().next().unwrap()), + 2 => { + let mut iter = copied_args.into_iter(); + ArgValues::Two(iter.next().unwrap(), iter.next().unwrap()) + } + _ => ArgValues::ArgsKargs { + args: copied_args, + kwargs: KwargsValues::Empty, + }, + } + } + + /// Extracts arguments from a tuple for `CallAttrExtended`. + /// + /// # Panics + /// Panics if `args_tuple` is not a tuple. This indicates a compiler bug since + /// the compiler always emits `ListToTuple` before `CallAttrExtended`. + fn extract_args_tuple_for_attr(&mut self, args_tuple: &Value) -> RunResult> { + let Value::Ref(id) = args_tuple else { + unreachable!("CallAttrExtended: args_tuple must be a Ref") + }; + let HeapData::Tuple(tuple) = self.heap.get(*id) else { + unreachable!("CallAttrExtended: args_tuple must be a Tuple") + }; + clone_args_from_tuple(tuple.as_slice(), self) + } + + /// Builds `ArgValues` with kwargs for `CallAttrExtended`. + /// + /// # Panics + /// Panics if `kwargs_ref` is not a dict. This indicates a compiler bug since + /// the compiler always emits `BuildDict` before `CallAttrExtended` with kwargs. + fn build_args_with_kwargs_for_attr( + &mut self, + copied_args: Vec, + kwargs_ref: Value, + ) -> Result { + let this = self; + defer_drop!(kwargs_ref, this); + + // Extract kwargs dict items + let Value::Ref(id) = kwargs_ref else { + unreachable!("CallAttrExtended: kwargs must be a Ref") + }; + let HeapData::Dict(dict) = this.heap.get(*id) else { + unreachable!("CallAttrExtended: kwargs must be a Dict") + }; + let copied_kwargs: Vec<(Value, Value)> = dict + .iter() + .map(|(k, v)| (k.clone_with_heap(this), v.clone_with_heap(this))) + .collect(); + + // `copied_args` travels unguarded through this `?`, which is sound only + // because `from_pairs` cannot fail here: it sizes both dict buffers to the + // pair count up front so the growth preflight is a no-op, and keys taken out + // of a dict are already known hashable. Size that dict lazily and this leaks + // the args. + let kwargs_values = if copied_kwargs.is_empty() { + KwargsValues::Empty + } else { + let kwargs_dict = Dict::from_pairs(copied_kwargs, this)?; + KwargsValues::Dict(kwargs_dict) + }; + + Ok(ArgValues::from_parts(copied_args, kwargs_values)) + } + + // ======================================================================== + // Frame Setup + // ======================================================================== + + /// Bypasses argument binding when a direct call matches its cached call plan. + fn try_call_exact_def_function( + &mut self, + func_id: FunctionId, + callable_index: usize, + arg_count: usize, + ) -> Option> { + let func = self.interns.get_function(func_id); + match func.exact_positional_call() { + Some(ExactPositionalCall::Sync(count)) if count == arg_count => { + Some(self.call_exact_sync_function(func_id, func, callable_index)) + } + Some(ExactPositionalCall::Async(count)) if count == arg_count => { + Some(Ok(self.create_exact_coroutine(func_id, func, callable_index))) + } + _ => None, + } + } + + /// Pushes a simple function frame using arguments already present on the VM stack. + /// + /// Removing the immediate callable shifts its arguments into the parameter + /// slots, avoiding argument wrappers, binding, scratch storage, and a copy. + fn call_exact_sync_function( + &mut self, + func_id: FunctionId, + func: &'h Function, + callable_index: usize, + ) -> Result { + let call_offset = self.current_offset(); + let namespace_size = func.namespace_size; + let locals_count = u16::try_from(namespace_size).expect("function namespace size exceeds u16"); + let code = &func.code; + + let callable = self.stack.remove(callable_index); + debug_assert_exact_callable(&callable, func_id); + self.stack + .resize_with(callable_index + namespace_size, || Value::Undefined); + + let exc_stack_base = self.exception_stack.len(); + self.push_frame(CallFrame::new_function( + code, + callable_index, + locals_count, + exc_stack_base, + func_id, + call_offset, + None, + ))?; + + Ok(CallResult::FramePushed) + } + + /// Creates a coroutine by moving exact positional arguments into its namespace. + fn create_exact_coroutine(&mut self, func_id: FunctionId, func: &Function, callable_index: usize) -> CallResult { + let mut namespace = self.stack.split_off(callable_index + 1); + namespace.reserve(func.namespace_size - namespace.len()); + self.install_closure_cells(func, &[], &mut namespace); + + let callable = self.pop(); + debug_assert_exact_callable(&callable, func_id); + + let coroutine = Coroutine::new(func_id, namespace, None); + let coroutine_id = self.heap.allocate(HeapData::Coroutine(coroutine)); + CallResult::Value(Value::Ref(coroutine_id)) + } + + /// Calls an internal function, compiling it on first use. + /// Arguments transfer into ordinary frame locals; implementation frames do not charge recursion depth. + pub(crate) fn call_frozen_exact( + &mut self, + function: FrozenFunction, + args: [Value; N], + ) -> Result { + let mut args_guard = DropGuard::new(args, self); + let (_, vm) = args_guard.as_parts_mut(); + let interns = vm.interns; + let (function_id, overlay) = if let Some(id) = interns.frozen_function(function) { + (id, None) + } else { + let (id, overlay) = function.compile(interns)?; + (id, Some(overlay)) + }; + // No fallible operation or Python execution may intervene between publication and frame installation. + if let Some(overlay) = overlay { + overlay.commit(); + interns.set_frozen_function(function, function_id); + } + let (args, vm) = args_guard.into_parts(); + let func = interns.get_function(function_id); + assert_eq!(func.signature.exact_positional_count(), Some(N)); + assert!(func.cell_var_slots.is_empty() && func.free_var_slots.is_empty()); + let namespace_size = func.namespace_size; + let locals_count = u16::try_from(namespace_size).expect("frozen function namespace exceeds u16"); + assert!(namespace_size >= N, "frozen function has too few local slots"); + let stack_base = vm.stack.len(); + vm.stack.extend(args); + vm.stack.resize_with(stack_base + namespace_size, || Value::Undefined); + let frame = CallFrame::new_function( + &func.code, + stack_base, + locals_count, + vm.exception_stack.len(), + function_id, + vm.current_offset(), + None, + ); + vm.push_admitted_frame(frame); + + Ok(CallResult::FramePushed) + } + + /// Calls a defined function by pushing a new frame or creating a coroutine. + /// + /// For sync functions: sets up the function's namespace with bound arguments, + /// cell variables, and free variables, then pushes a new frame. + /// + /// For async functions: binds arguments immediately but returns a Coroutine + /// instead of pushing a frame. The coroutine stores the pre-bound namespace + /// and will be executed when awaited. + pub(crate) fn call_def_function( + &mut self, + func_id: FunctionId, + cells: &[HeapId], + defaults: &[Value], + globals: Option, + args: ArgValues, + ) -> Result { + let func = self.interns.get_function(func_id); + + if func.is_async { + self.create_coroutine(func_id, func, cells, defaults, globals, args) + } else { + self.call_sync_function(func_id, func, cells, defaults, globals, args) + } + } + + /// Creates a Coroutine for an async function call. + /// + /// The coroutine is executed when awaited via Await. + fn create_coroutine( + &mut self, + func_id: FunctionId, + func: &Function, + cells: &[HeapId], + defaults: &[Value], + globals: Option, + args: ArgValues, + ) -> Result { + // 1. Create namespace for the coroutine with bound arguments and captured cells. + let namespace = Vec::with_capacity(func.namespace_size); + let mut namespace_guard = DropGuard::new(namespace, self); + let (namespace, this) = namespace_guard.as_parts_mut(); + + // 2. Bind arguments to parameters + func.signature.bind(args, defaults, this, func.name, namespace)?; + + // 3. Install owned cells and captured free-var cells at their slots. + this.install_closure_cells(func, cells, namespace); + + // 4. Create Coroutine on heap; it carries its own reference to the globals dict. + let (namespace, this) = namespace_guard.into_parts(); + if let Some(globals) = globals { + this.heap.inc_ref(globals); + } + let coroutine = Coroutine::new(func_id, namespace, globals); + let coroutine_id = this.heap.allocate(HeapData::Coroutine(coroutine)); + + Ok(CallResult::Value(Value::Ref(coroutine_id))) + } + + /// Installs owned cell variables and captured free-var cells into a frame's + /// `namespace` at their explicit slots, then fills any remaining slots with + /// `Undefined`. + /// + /// `namespace` enters holding only the bound parameters and leaves with + /// length `func.namespace_size`. Each owned cell (`cell_var_slots[i]`) is a + /// freshly allocated `Cell`, seeded from parameter `cell_param_indices[i]` + /// when that cell is for a captured parameter. Each captured cell + /// (`cells[i]`, gathered by the caller from the enclosing frame) is inc-ref'd + /// and installed at `free_var_slots[i]`. + /// + /// Slots are addressed explicitly rather than pushed sequentially because a + /// transitively captured (pass-through) variable is allocated a slot late + /// during preparation, outside the contiguous param/cell/free region — so a + /// positional `push` would place it wrong. Shared by sync calls and + /// coroutine creation, including the exact-positional-call fast path + /// (which always passes an empty `cells` slice, since it only applies when + /// `cell_var_slots`/`free_var_slots` are both empty). + fn install_closure_cells(&mut self, func: &Function, cells: &[HeapId], namespace: &mut Vec) { + namespace.resize_with(func.namespace_size, || Value::Undefined); + + for (i, &slot) in func.cell_var_slots.iter().enumerate() { + let cell_value = match func.cell_param_indices[i] { + Some(param_idx) => namespace[param_idx].clone_with_heap(self), + None => Value::Undefined, + }; + let cell_id = self.heap.allocate(HeapData::Cell(CellValue(cell_value))); + namespace[slot.index()] = Value::Ref(cell_id); + } + + for (i, &cell_id) in cells.iter().enumerate() { + self.heap.inc_ref(cell_id); + namespace[func.free_var_slots[i].index()] = Value::Ref(cell_id); + } + } + + /// Calls a sync function by pushing a new frame. + /// + /// Sets up the function's namespace with bound arguments, cell variables, + /// and free variables (captured from enclosing scope for closures). + /// + /// Locals are built in the reusable `namespace_scratch` buffer (under a + /// [`DropGuard`] for cleanup on error) and moved onto the VM stack, where + /// `stack_base` points to the start of the locals region. + fn call_sync_function( + &mut self, + func_id: FunctionId, + func: &'h Function, + cells: &[HeapId], + defaults: &[Value], + globals: Option, + args: ArgValues, + ) -> Result { + let call_offset = self.current_offset(); + let stack_base = self.stack.len(); + + let namespace_size = func.namespace_size; + let locals_count = u16::try_from(namespace_size).expect("function namespace size exceeds u16"); + + // 1. Build the namespace in the reusable scratch buffer to avoid a + // per-call allocation. On error `DropGuard` drops the buffer, so the + // pool just restarts empty next call. + let mut namespace = mem::take(&mut self.namespace_scratch); + namespace.reserve(namespace_size); + let mut namespace_guard = DropGuard::new(namespace, self); + let (namespace, this) = namespace_guard.as_parts_mut(); + + // 2. Bind arguments to parameters + { + let bind_result = func.signature.bind(args, defaults, this, func.name, namespace); + + bind_result?; + } + + // 3. Install owned cells and captured free-var cells at their slots. + this.install_closure_cells(func, cells, namespace); + + // 6. Commit the guard (no rollback) and push the frame. The operand + // stack starts immediately above the locals region — comprehensions + // emit their own push/pop bytecode, so no frame-level region is + // reserved here. `append` empties the buffer (keeping its allocation) + // so it can return to the pool. + let (mut namespace, this) = namespace_guard.into_parts(); + this.stack.append(&mut namespace); + this.namespace_scratch = namespace; + + let exc_stack_base = this.exception_stack.len(); + let namespace = function_namespace(globals, &*this.heap); + this.push_frame(CallFrame::new_function( + &func.code, + stack_base, + locals_count, + exc_stack_base, + func_id, + call_offset, + namespace, + ))?; + + Ok(CallResult::FramePushed) + } + + /// Constructs an instance of a user-defined class — the `Foo(...)` path. + /// + /// Allocates the instance with an empty `__dict__`, then: + /// - **No `__init__`:** rejects any arguments (like `object()`), returns the + /// instance directly. + /// - **`__init__` is a plain sync function** (the normal case): pushes the + /// instance onto the operand stack as the pending result, runs + /// `__init__(self, *args)` as a real (suspendable) frame, and marks that + /// frame `is_initializer`. When the initializer frame returns, the + /// [`ReturnValue`](crate::bytecode::Opcode::ReturnValue) handler enforces the + /// `None` return and leaves the already-pushed instance as the result — so + /// `Foo(a)` evaluates to the new instance, not `__init__`'s return. + /// - **Any other `__init__`** (builtin, class, `async def`, non-callable, ...): + /// runs it to completion synchronously via + /// [`evaluate_function`](Self::evaluate_function) and enforces CPython's + /// contract that it returns `None`. This path cannot suspend, and must NOT + /// go through the frame-marking path: a class-valued `__init__` recurses + /// into `instantiate_class`, which pushes its own pending instance — + /// blindly marking the resulting frame would corrupt the operand stack. + /// + /// Because a plain-function `__init__` runs as a normal frame, it may suspend + /// on external/OS calls; the `is_initializer` flag is threaded through frame + /// serialization so a suspended initializer resumes correctly. + pub(crate) fn instantiate_class(&mut self, class_id: HeapId, args: ArgValues) -> Result { + let instance_id = self + .heap + .allocate(HeapData::Instance(Box::new(Instance::new(class_id, Dict::new())))); + // The instance now owns a reference to its class object. + self.heap.inc_ref(class_id); + + // Look up `__init__` in the class namespace (cloned out to release the borrow). + let init = match self.heap.get(class_id) { + HeapData::Class(class) => class + .namespace() + .get_by_str("__init__", self.heap, self.interns) + .map(|v| v.clone_with_heap(self)), + _ => None, + }; + + match init { + None if matches!(args, ArgValues::Empty) => Ok(CallResult::Value(Value::Ref(instance_id))), + None => { + args.drop_with(self); + let name = class_name(class_id, self.heap, self.interns); + Value::Ref(instance_id).drop_with(self); + Err(ExcType::type_error(format!("{name}() takes no arguments"))) + } + // A `@dataclass`-generated `__init__` binds its fields natively, + // with no generated bytecode; holding `init_func` keeps its plan + // alive while factories run. + Some(init_func) if dataclasses::is_generated_init(&init_func, self) => { + let this = self; + defer_drop!(init_func, this); + dataclasses::run_init(this, init_func, Value::Ref(instance_id), args).map(CallResult::Value) + } + Some(init_func) => { + let this = self; + defer_drop!(init_func, this); + // CPython's `type.__call__` looks up `__init__` with descriptor + // binding: only plain functions bind the new instance as `self`. + // Bound methods already carry their own receiver, and builtins, + // classes and other values are called with the constructor + // arguments unchanged. + let init_args = if this.is_function_value(init_func) { + this.heap.inc_ref(instance_id); + args.prepend(Value::Ref(instance_id)) + } else { + args + }; + if this.is_plain_sync_function(init_func) { + // Push the instance as the pending result (transferring the + // allocation's reference), then run __init__ as a real + // (suspendable) frame. + this.push(Value::Ref(instance_id)); + match this.call_function(init_func, init_args)? { + CallResult::FramePushed => { + // Mark the just-pushed frame so its return value is + // discarded (after the `None` check in the ReturnValue + // handler) and the pending instance becomes the result. + this.current_frame_mut().is_initializer = true; + Ok(CallResult::FramePushed) + } + other => { + // Defensive: `is_plain_sync_function` guarantees a frame push. + other.drop_with(this); + this.pop().drop_with(this); + Err(ExcType::type_error("__init__() must be a regular function")) + } + } + } else { + // Exotic `__init__` (builtin, class, `async def`, non-callable, + // ...): run to completion synchronously — no pending instance is + // pushed — and enforce CPython's `None`-return contract. + match this.evaluate_function(init_func, init_args) { + Ok(Value::None) => Ok(CallResult::Value(Value::Ref(instance_id))), + Ok(result) => { + let type_name = result.py_type_name(this); + result.drop_with(this); + Value::Ref(instance_id).drop_with(this); + Err(ExcType::type_error_init_return(type_name)) + } + Err(e) => { + Value::Ref(instance_id).drop_with(this); + Err(e) + } + } + } + } + } + } + + /// Whether `value` is a plain Python function object (`def`, closure, or + /// function-with-defaults — sync or async): the kinds that act as descriptors + /// in CPython and therefore bind an instance when looked up as a class member. + fn is_function_value(&self, value: &Value) -> bool { + match value { + Value::DefFunction(_) => true, + Value::Ref(id) => matches!( + self.heap.get(*id), + HeapData::Closure(_) | HeapData::FunctionDefaults(_) | HeapData::DataclassMethod(_) + ), + _ => false, + } + } + + /// Whether calling `value` would push a regular synchronous frame + /// (`CallResult::FramePushed`): a plain `def`, closure, function-with-defaults, + /// or a bound method wrapping one — but not an `async def`, whose call creates + /// a coroutine instead. Used by [`instantiate_class`](Self::instantiate_class) + /// to decide whether `__init__` can run as a suspendable initializer frame. + fn is_plain_sync_function(&self, value: &Value) -> bool { + match value { + Value::DefFunction(func_id) => !self.interns.get_function(*func_id).is_async, + Value::Ref(id) => match self.heap.get(*id) { + HeapData::Closure(closure) => !self.interns.get_function(closure.func_id).is_async, + HeapData::FunctionDefaults(fd) => !self.interns.get_function(fd.func_id).is_async, + // Bound methods never wrap another bound method, so this + // recursion is at most one level deep. + HeapData::BoundMethod(bm) => self.is_plain_sync_function(&bm.func), + _ => false, + }, + _ => false, + } + } +} + +/// Clones a `*args` tuple's contents into the owned buffer a call needs. +/// +/// The clone is one allocation the size of the whole tuple, so it is preflighted: +/// past the allocator's hard-limit headroom that single allocation kills the worker +/// rather than raising `MemoryError`. +fn clone_args_from_tuple(items: &[Value], vm: &impl ContainsHeap) -> RunResult> { + // One spare slot so `ArgValues::prepend` can put `self` in front of a bound + // method's arguments without reallocating; that insert has no preflight of its own. + let slots = items.len().saturating_add(1); + check_estimated_size(slots.saturating_mul(VALUE_SIZE), &vm.heap().tracker)?; + let mut args = Vec::with_capacity(slots); + args.extend(items.iter().map(|v| v.clone_with_heap(vm))); + Ok(args) +} + +/// Asserts a callable popped off the stack by an exact-positional-call fast +/// path is the function that fast path was chosen for. +/// +/// Shared by [`VM::call_exact_sync_function`] and [`VM::create_exact_coroutine`], +/// which both remove their callable from the stack after already having +/// dispatched on its `FunctionId` in [`VM::try_call_exact_def_function`]. +fn debug_assert_exact_callable(callable: &Value, func_id: FunctionId) { + debug_assert!(matches!(callable, Value::DefFunction(id) if *id == func_id)); +} + +/// Centralised dunder dispatch for `__enter__` / `__exit__` (and, when added, +/// any other dunder that maps to a [`PyTrait`] method). +/// +/// Returns `Some(result)` when `name_id` names a recognised dunder — `args` +/// is taken out of the slot and consumed. Returns `None` when it isn't — +/// `args` is left untouched in the slot so the caller can hand it off to +/// the regular `py_call_attr` dispatch. +/// +/// The `&mut Option` shape is what keeps "all the recognition +/// and dispatch logic in one function" honest: `args` is non-`Copy` and +/// has a `Drop` impl that panics on stray `Ref` values, so it can only be +/// passed by value once we know we'll consume it. +/// +/// Adding a new dunder is just a new arm in the inner `match`; type +/// implementations only need to override the corresponding `PyTrait` +/// method, never a `StaticStrings::Foo` arm in their `py_call_attr`. +fn dispatch_dunder( + name_id: StringId, + heap_id: HeapId, + vm: &mut VM<'_>, + args: &mut Option, +) -> Option> { + let static_str = vm.interns.static_string(name_id)?; + // User-defined instances are never intercepted: an explicit + // `obj.__enter__()` / `obj.__exit__(a, b, c)` on an instance is an + // ordinary method call in CPython — the instance `__dict__` can shadow + // the class method and the arguments must reach the user function + // verbatim (the trait hooks reduce them to an `Option`, which + // is lossy). The `with` statement still uses the trait hooks via the + // `BeforeWith`/`WithExit`/`WithExceptStart` opcodes, which perform the + // CPython type-level (class-only) lookup. + if matches!(vm.heap.get(heap_id), HeapData::Instance(_)) { + return None; + } + Some(match static_str { + StaticStrings::Enter => { + let args = args.take().expect("dispatch_dunder called with empty args slot"); + args.check_zero_args("__enter__", vm.heap) + .and_then(|()| vm.heap.read(heap_id).py_enter(vm)) + } + StaticStrings::Exit => { + let args = args.take().expect("dispatch_dunder called with empty args slot"); + dispatch_exit(heap_id, vm, args) + } + _ => return None, + }) +} + +/// Direct `obj.__exit__(typ, val, tb)` invocation. +/// +/// Validates that exactly three positional arguments are passed (CPython +/// raises `TypeError` for any other arity) and forwards `val` to +/// [`PyTrait::py_exit`] as `Option`: +/// +/// - `val is None` → `None`, treated as the "normal exit" path. +/// - `val is a heap-allocated value` → `Some(heap_id)`. For built-in context +/// managers this is the exception instance, matching the `with`-statement +/// call shape. +/// - `val is a scalar (Int, Bool, …)` → `None`. The trait abstraction can +/// only carry `HeapId`s, so non-Ref values cannot be forwarded; in +/// practice no supported context manager inspects a non-exception `val`, +/// and CPython's behavior for such calls is implementation-defined per +/// the user-provided `__exit__`. +/// +/// `typ` and `tb` are discarded: every implementation we have re-derives the +/// type from `val` and Monty has no traceback objects (see +/// `limitations/with.md`). +fn dispatch_exit(heap_id: HeapId, vm: &mut VM<'_>, args: ArgValues) -> Result { + let positional = args.into_pos_only("__exit__", vm.heap)?; + defer_drop!(positional, vm); + let [typ, val, tb] = positional.as_slice() else { + return Err(ExcType::type_error_arg_count("__exit__", 3, positional.len())); + }; + let _ = (typ, tb); + let exc = match val { + Value::Ref(id) => Some(*id), + _ => None, + }; + vm.heap.read(heap_id).py_exit(vm, exc) +} diff --git a/crates/bashkit-monty/src/bytecode/vm/collections.rs b/crates/bashkit-monty/src/bytecode/vm/collections.rs new file mode 100644 index 000000000..572f297f5 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/collections.rs @@ -0,0 +1,694 @@ +//! Collection building and unpacking helpers for the VM. + +use super::VM; +use crate::{ + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{DropGuard, DropWithContext, Heap, HeapData, HeapReadOutput}, + intern::StringId, + types::{ + Dict, List, PyTrait, Set, Slice, allocate_tuple, collect_iterable, collect_iterable_bounded, + instance::instance_defines_iter, slice::value_to_option_i64, + }, + value::{VALUE_SIZE, Value}, +}; + +impl VM<'_> { + /// Builds a list from the top n stack values. + pub(super) fn build_list(&mut self, count: usize) { + let items = self.pop_n(count); + let list = List::new(items); + let heap_id = self.heap.allocate(HeapData::List(list)); + self.push(Value::Ref(heap_id)); + } + + /// Builds a tuple from the top n stack values. + /// + /// Uses the empty tuple singleton when count is 0, and SmallVec + /// optimization for small tuples (≤2 elements). + pub(super) fn build_tuple(&mut self, count: usize) { + let items = self.pop_n(count); + let value = allocate_tuple(items.into(), self.heap); + self.push(value); + } + + /// Builds a dict from the top 2n stack values (key/value pairs). + /// + /// An insertion can raise — the key may be unhashable, or a colliding + /// `__eq__` may raise — so both the pairs still on the way in and the + /// half-built dict ride in guards until the dict reaches the heap. + pub(super) fn build_dict(&mut self, count: usize) -> Result<(), RunError> { + let this = self; + let items = this.pop_n(count * 2).into_iter(); + defer_drop_mut!(items, this); + let mut dict_guard = DropGuard::new(Dict::new(), this); + loop { + let (dict, this) = dict_guard.as_parts_mut(); + let (Some(key), Some(value)) = (items.next(), items.next()) else { + break; + }; + // A duplicate literal key (`{k: 1, k: 2}`) replaces the earlier + // value, which must be dropped or its refcount leaks. + if let Some(old_value) = dict.set(key, value, this)? { + old_value.drop_with(this); + } + } + let (dict, this) = dict_guard.into_parts(); + let heap_id = this.heap.allocate(HeapData::Dict(dict)); + this.push(Value::Ref(heap_id)); + Ok(()) + } + + /// Builds a set from the top n stack values. + /// + /// An insertion can raise — the item may be unhashable, or a colliding + /// `__eq__` may raise — so both the items still on the way in and the + /// half-built set ride in guards until the set reaches the heap. + pub(super) fn build_set(&mut self, count: usize) -> Result<(), RunError> { + let this = self; + let items = this.pop_n(count).into_iter(); + defer_drop_mut!(items, this); + let mut set_guard = DropGuard::new(Set::new(), this); + loop { + let (set, this) = set_guard.as_parts_mut(); + let Some(item) = items.next() else { + break; + }; + set.add(item, this)?; + } + let (set, this) = set_guard.into_parts(); + let heap_id = this.heap.allocate(HeapData::Set(set)); + this.push(Value::Ref(heap_id)); + Ok(()) + } + + /// Builds a slice object from the top 3 stack values. + /// + /// Stack: [start, stop, step] -> [slice] + /// Each value can be None (for default) or an integer. + pub(super) fn build_slice(&mut self) -> Result<(), RunError> { + let this = self; + + let step_val = this.pop(); + defer_drop!(step_val, this); + let stop_val = this.pop(); + defer_drop!(stop_val, this); + let start_val = this.pop(); + defer_drop!(start_val, this); + + let start = value_to_option_i64(start_val, this)?; + let stop = value_to_option_i64(stop_val, this)?; + let step = value_to_option_i64(step_val, this)?; + + let slice = Slice::new(start, stop, step); + let heap_id = this.heap.allocate(HeapData::Slice(slice)); + this.push(Value::Ref(heap_id)); + Ok(()) + } + + /// Extends a list with items from an iterable, for PEP 448 `*expr` literal unpacking. + /// + /// Stack: [list, iterable] -> [list] + /// Pops the iterable, extends the list in place, leaves list on stack. + /// + /// Raises `TypeError("Value after * must be an iterable, not {type}")` for non-iterables, + /// matching CPython's message for list/tuple literal unpacking (`[*x]`, `(*x,)`). + /// + /// Uses `DropGuard` for `list_ref` because it is pushed back on success, + /// and `defer_drop!` for `iterable` because it is always dropped. + pub(super) fn list_extend(&mut self) -> Result<(), RunError> { + let this = self; + + let iterable = this.pop(); + defer_drop!(iterable, this); + // DropGuard for list_ref: pushed back on success via into_parts, dropped on error + let mut list_ref_guard = DropGuard::new(this.pop(), this); + let (list_ref, this) = list_ref_guard.as_parts(); + + if !iterable.py_is_iterable(this) { + let type_ = iterable.py_type_name(this); + return Err(if opts_out_of_iter(iterable, this) { + ExcType::type_error_not_iterable(&type_) + } else { + ExcType::type_error_value_after_star(&type_) + }); + } + + { + let copied_items: Vec = collect_iterable(iterable, this)?; + defer_drop_mut!(copied_items, this); + + // Check if any copied items are refs (for updating contains_refs) + let has_refs = copied_items.iter().any(|v| matches!(v, Value::Ref(_))); + + // Extend the list + if let Value::Ref(id) = list_ref { + let HeapReadOutput::List(list) = this.heap.read(*id) else { + panic!("list_extend: expected List on heap"); + }; + let list = list.get_mut(this.heap); + // Update contains_refs before extending + if has_refs { + list.set_contains_refs(); + } + list.as_vec_mut().append(copied_items); + } + } + + // Push list_ref back on the stack (don't drop it) + let (list_ref, this) = list_ref_guard.into_parts(); + this.push(list_ref); + Ok(()) + } + + /// Converts a list to a tuple. + /// + /// Stack: [list] -> [tuple] + pub(super) fn list_to_tuple(&mut self) -> Result<(), RunError> { + let this = self; + + let list_ref = this.pop(); + defer_drop!(list_ref, this); + + let Value::Ref(id) = list_ref else { + return Err(RunError::internal("ListToTuple: expected list ref")); + }; + let HeapData::List(list) = this.heap.get(*id) else { + return Err(RunError::internal("ListToTuple: expected list")); + }; + let items = list.as_slice().iter().map(|v| v.clone_with_heap(this.heap)).collect(); + let value = allocate_tuple(items, this.heap); + this.push(value); + Ok(()) + } + + /// Merges a mapping into a dict for **kwargs unpacking. + /// + /// Stack: [dict, mapping] -> [dict] + /// Validates that mapping is a dict and that keys are strings. + /// + /// Uses `defer_drop!` for `mapping` (always dropped) and `DropGuard` for + /// `dict_ref` (pushed back on success, dropped on error). + pub(super) fn dict_merge(&mut self, func_name_id: u16) -> Result<(), RunError> { + let func_name = func_name_for_dict_merge(func_name_id, self); + self.dict_merge_inner(&func_name) + } + + /// Method-call variant of [`Self::dict_merge`]. Qualifies the error wording + /// with the receiver's Python type by peeking the stack — when this op + /// runs the receiver sits 4 slots below TOS (`[receiver, args_tuple, + /// kwargs_dict, mapping]`), since the call body hasn't issued any pops + /// yet. Produces e.g. `list.sort() got multiple values for keyword + /// argument 'key'` to match CPython. + pub(super) fn method_dict_merge(&mut self, func_name_id: u16) -> Result<(), RunError> { + let func_name = if func_name_id == 0xFFFF { + "".to_string() + } else { + let method = self.interns.get_str(StringId::from_index(func_name_id)).to_string(); + let recv_type = self.stack[self.stack.len() - 4].py_type_name(self); + format!("{recv_type}.{method}") + }; + self.dict_merge_inner(&func_name) + } + + /// Shared body of [`Self::dict_merge`] and [`Self::method_dict_merge`] — + /// only the `func_name` used in error wording differs between them. + fn dict_merge_inner(&mut self, func_name: &str) -> Result<(), RunError> { + let this = self; + + let mapping = this.pop(); + defer_drop!(mapping, this); + // DropGuard for dict_ref: pushed back on success via into_parts, dropped on error + let mut dict_ref_guard = DropGuard::new(this.pop(), this); + let (dict_ref, this) = dict_ref_guard.as_parts(); + + // Check that mapping is a dict (Ref pointing to Dict) and clone key-value pairs + let copied_items: Vec<(Value, Value)> = if let Value::Ref(id) = mapping { + if let HeapData::Dict(dict) = this.heap.get(*id) { + dict.iter() + .map(|(k, v)| (k.clone_with_heap(this), v.clone_with_heap(this))) + .collect() + } else { + let type_name = mapping.py_type_name(this).to_string(); + return Err(ExcType::type_error_kwargs_not_mapping(func_name, &type_name)); + } + } else { + let type_name = mapping.py_type_name(this).to_string(); + return Err(ExcType::type_error_kwargs_not_mapping(func_name, &type_name)); + }; + + // Merge into the dict, validating string keys + let dict_id = if let Value::Ref(id) = dict_ref { + *id + } else { + return Err(RunError::internal("DictMerge: expected dict ref")); + }; + + { + let copied_items = copied_items.into_iter(); + defer_drop_mut!(copied_items, this); + for (key, value) in copied_items { + // Validate key is a string (InternString or heap-allocated Str) + let is_string = match &key { + Value::InternString(_) => true, + Value::Ref(id) => matches!(this.heap.get(*id), HeapData::Str(_)), + _ => false, + }; + if !is_string { + key.drop_with(this); + value.drop_with(this); + return Err(ExcType::type_error_kwargs_nonstring_key()); + } + + // Get the string key for error messages (needed before moving key into closure) + let key_str = match &key { + Value::InternString(id) => this.interns.get_str(*id).to_string(), + Value::Ref(id) => { + if let HeapData::Str(s) = this.heap.get(*id) { + s.as_str().to_string() + } else { + "".to_string() + } + } + _ => "".to_string(), + }; + + let HeapReadOutput::Dict(dict) = this.heap.read(dict_id) else { + unreachable!("DictMerge: entry is not a Dict") + }; + + if let Some(old_value) = dict.set(key, value, this)? { + old_value.drop_with(this); + return Err(ExcType::type_error_multiple_values(func_name, &key_str)); + } + } + } + + // Push dict_ref back on the stack (don't drop it) + let (dict_ref, this) = dict_ref_guard.into_parts(); + this.push(dict_ref); + Ok(()) + } + + // ======================================================================== + // PEP 448 Literal Building + // ======================================================================== + + /// Silently merges a mapping into the dict literal at `depth` on the stack. + /// + /// Used for `{**x, ...}` dict literals where later keys silently overwrite + /// earlier ones (unlike [`dict_merge`] which raises `TypeError` on duplicate keys + /// and is used for function-call `**kwargs`). + /// + /// Stack (depth = 0): `[..., dict, mapping]` → `[..., dict]` + /// + /// # Errors + /// + /// Returns `TypeError: '{type}' object is not a mapping` if the TOS is not a dict. + pub(super) fn dict_update(&mut self, depth: usize) -> Result<(), RunError> { + let this = self; + + let mapping = this.pop(); + defer_drop!(mapping, this); + + // Clone all key/value pairs out of the mapping before mutating the target dict + let copied_items: Vec<(Value, Value)> = if let Value::Ref(id) = mapping { + if let HeapData::Dict(dict) = this.heap.get(*id) { + dict.iter() + .map(|(k, v)| (k.clone_with_heap(this), v.clone_with_heap(this))) + .collect() + } else { + let type_ = mapping.py_type_name(this); + return Err(ExcType::type_error_not_mapping(&type_)); + } + } else { + let type_ = mapping.py_type_name(this); + return Err(ExcType::type_error_not_mapping(&type_)); + }; + + // The target dict sits at `depth` positions below TOS (which is now gone after pop) + let stack_len = this.stack.len(); + let dict_pos = stack_len - 1 - depth; + // SAFETY: the compiler always emits BuildDict before DictUpdate, so the + // target is always a Value::Ref. This is a VM invariant: reaching this else + // arm means a compiler bug. + let Value::Ref(dict_id) = this.stack[dict_pos] else { + unreachable!("DictUpdate: target is always a Ref — compiler invariant") + }; + + let copied_items = copied_items.into_iter(); + defer_drop_mut!(copied_items, this); + for (key, value) in copied_items { + let HeapReadOutput::Dict(dict) = this.heap.read(dict_id) else { + unreachable!("DictUpdate: heap entry is always a Dict — compiler invariant") + }; + let old = dict.set(key, value, this)?; + // Silently drop any old value — PEP 448 dict literals allow duplicate keys + if let Some(old_val) = old { + old_val.drop_with(this); + } + } + + Ok(()) + } + + /// Extends a set literal with all items from an iterable. + /// + /// Used for `{*x, ...}` set literals (PEP 448). Follows the same item-copying + /// pattern as [`list_extend`]; raises `TypeError` for non-iterable sources. + /// + /// Stack (depth = 0): `[..., set, iterable]` → `[..., set]` + /// + /// # Errors + /// + /// Returns `TypeError: '{type}' object is not iterable` if TOS is not iterable. + pub(super) fn set_extend(&mut self, depth: usize) -> Result<(), RunError> { + let this = self; + + let iterable = this.pop(); + defer_drop!(iterable, this); + + // See `list_extend`: drained generically, with only the message differing. + if !iterable.py_is_iterable(this) { + let type_ = iterable.py_type_name(this); + return Err(ExcType::type_error_not_iterable(&type_)); + } + let copied_items: Vec = collect_iterable(iterable, this)?; + + // The target set sits at `depth` positions below TOS (which is now gone after pop) + let stack_len = this.stack.len(); + let set_pos = stack_len - 1 - depth; + // SAFETY: the compiler always emits BuildSet before SetExtend, so the + // target is always a Value::Ref. This is a VM invariant: reaching this else + // arm means a compiler bug. + let Value::Ref(set_id) = this.stack[set_pos] else { + unreachable!("SetExtend: target is always a Ref — compiler invariant") + }; + + let copied_items = copied_items.into_iter(); + defer_drop_mut!(copied_items, this); + for item in copied_items { + let HeapReadOutput::Set(set) = this.heap.read(set_id) else { + unreachable!("SetExtend: heap entry is always a Set — compiler invariant") + }; + set.add(item, this)?; + } + + Ok(()) + } + + // ======================================================================== + // Comprehension Building + // ======================================================================== + + /// Appends TOS to list for comprehension. + /// + /// Stack: [..., list, iter1, ..., iterN, value] -> [..., list, iter1, ..., iterN] + /// The `depth` parameter is the number of iterators between the list and the value. + /// List is at stack position: len - 2 - depth (0-indexed from bottom). + pub(super) fn list_append(&mut self, depth: usize) -> Result<(), RunError> { + let value = self.pop(); + let stack_len = self.stack.len(); + let list_pos = stack_len - 1 - depth; + + // Get the list reference + let Value::Ref(list_id) = self.stack[list_pos] else { + value.drop_with(self); + return Err(RunError::internal("ListAppend: expected list ref on stack")); + }; + + let HeapReadOutput::List(list) = self.heap.read(list_id) else { + value.drop_with(self); + return Err(RunError::internal("ListAppend: expected list on heap")); + }; + list.append(self, value) + } + + /// Adds TOS to set for comprehension. + /// + /// Stack: [..., set, iter1, ..., iterN, value] -> [..., set, iter1, ..., iterN] + /// The `depth` parameter is the number of iterators between the set and the value. + /// May raise TypeError if value is unhashable. + pub(super) fn set_add(&mut self, depth: usize) -> Result<(), RunError> { + let value = self.pop(); + let stack_len = self.stack.len(); + let set_pos = stack_len - 1 - depth; + + // Get the set reference + let Value::Ref(set_id) = self.stack[set_pos] else { + value.drop_with(self); + return Err(RunError::internal("SetAdd: expected set ref on stack")); + }; + + let HeapReadOutput::Set(set) = self.heap.read(set_id) else { + value.drop_with(self); + return Err(RunError::internal("SetAdd: expected set on heap")); + }; + set.add(value, self)?; + + Ok(()) + } + + /// Sets dict[key] = value for comprehension. + /// + /// Stack: [..., dict, iter1, ..., iterN, key, value] -> [..., dict, iter1, ..., iterN] + /// The `depth` parameter is the number of iterators between the dict and the key-value pair. + /// May raise TypeError if key is unhashable. + pub(super) fn dict_set_item(&mut self, depth: usize) -> Result<(), RunError> { + let value = self.pop(); + let key = self.pop(); + let stack_len = self.stack.len(); + let dict_pos = stack_len - 1 - depth; + + // Get the dict reference + let Value::Ref(dict_id) = self.stack[dict_pos] else { + key.drop_with(self); + value.drop_with(self); + return Err(RunError::internal("DictSetItem: expected dict ref on stack")); + }; + + let HeapReadOutput::Dict(dict) = self.heap.read(dict_id) else { + key.drop_with(self); + value.drop_with(self); + return Err(RunError::internal("DictSetItem: expected dict on heap")); + }; + let old_value = dict.set(key, value, self)?; + + // Drop old value if key already existed + if let Some(old) = old_value { + old.drop_with(self); + } + + Ok(()) + } + + // ======================================================================== + // Unpacking + // ======================================================================== + + /// Unpacks an iterable into exactly `count` values on the stack. + /// + /// Accepts anything iterable, not a fixed set of sequence types — a `str` + /// unpacks to its characters, a `dict` to its keys. + pub(super) fn unpack_sequence(&mut self, count: usize) -> Result<(), RunError> { + let this = self; + + let value = this.pop(); + defer_drop!(value, this); + + // Fast path: tuple, list, push onto stack without a temporary vector. + if let Some(items) = exact_sequence_items(value, this.heap) { + if items.len() != count { + return Err(ExcType::unpack_size_error(count, items.len())); + } + if count > this.stack.capacity() - this.stack.len() { + let capacity = this.stack.len().saturating_add(count); + this.heap + .tracker + .check_allocation(capacity.saturating_mul(VALUE_SIZE))?; + this.stack.reserve_exact(count); + } + this.stack + .extend(items.iter().rev().map(|item| item.clone_with_heap(this.heap))); + return Ok(()); + } + let items = unpack_exact(value, count, this)?; + // Push items in reverse order so first item is on top + for item in items.into_iter().rev() { + this.push(item); + } + Ok(()) + } + + /// Unpacks a sequence with a starred target. + /// + /// `before` is the number of targets before the star, `after` is the number after. + /// The starred target collects all middle items into a list. + /// + /// For example, `first, *rest, last = [1, 2, 3, 4, 5]` has before=1, after=1. + /// After execution, the stack has: first (top), rest_list, last. + pub(super) fn unpack_ex(&mut self, before: usize, after: usize) -> Result<(), RunError> { + let this = self; + + let value = this.pop(); + defer_drop_mut!(value, this); + + let min_items = before + after; + + if !value.py_is_iterable(this) { + return Err(unpack_type_error(value, this)); + } + // Drained in full: a starred target consumes everything, so unlike + // `unpack_sequence` there is no bound to stop at — and therefore always + // a true total to report when there are too few values. + let mut items_guard = DropGuard::new(collect_iterable(value, this)?, this); + let (items, _) = items_guard.as_parts(); + if items.len() < min_items { + return Err(unpack_ex_too_few_error(min_items, items.len())); + } + + let (items, this) = items_guard.into_parts(); + this.push_unpack_ex_results(items, before, after); + Ok(()) + } + + /// Helper to push unpacked items with starred target onto the stack. + /// + /// Takes a slice of items and creates the middle list. + fn push_unpack_ex_results(&mut self, items: Vec, before: usize, after: usize) { + let this = self; + + defer_drop_mut!(items, this); + + // Items get pushed onto the stack backwards, so a lot of .rev() calls + + for item in items.drain(items.len() - after..).rev() { + this.push(item); + } + + // Middle items as a list (starred target) + let middle_list: Vec = items.drain(before..).collect(); + let list_id = this.heap.allocate(HeapData::List(List::new(middle_list))); + this.push(Value::Ref(list_id)); + + // Before items + for item in items.drain(..).rev() { + this.push(item); + } + } +} + +/// Resolves the function-name string used by `DictMerge` error wording. +/// `0xFFFF` is the compiler sentinel for "unknown caller". +fn func_name_for_dict_merge(func_name_id: u16, vm: &VM<'_>) -> String { + if func_name_id == 0xFFFF { + "".to_string() + } else { + vm.interns.get_str(StringId::from_index(func_name_id)).to_string() + } +} + +/// Creates the ValueError for star unpacking when there are too few values. +fn unpack_ex_too_few_error(min_needed: usize, actual: usize) -> RunError { + let message = format!("not enough values to unpack (expected at least {min_needed}, got {actual})"); + SimpleException::new_msg(ExcType::ValueError, message).into() +} + +/// `a, b, c = value` as owned items: exactly `count` of them, with CPython's +/// unpack errors. Shared by `UNPACK_SEQUENCE` and native code that mirrors a +/// Python unpack (`random.setstate`). Consumes at most `count + 1` items, so an +/// endless iterable still fails. +pub(crate) fn unpack_exact(value: &Value, count: usize, vm: &mut VM<'_>) -> RunResult> { + // Fast path: tuple, list; unpack without iterator. + if let Some(items) = exact_sequence_items(value, vm.heap) { + if items.len() != count { + return Err(ExcType::unpack_size_error(count, items.len())); + } + vm.heap.tracker.check_allocation(count.saturating_mul(VALUE_SIZE))?; + return Ok(items.iter().map(|item| item.clone_with_heap(vm.heap)).collect()); + } + if !value.py_is_iterable(vm) { + return Err(unpack_type_error(value, vm)); + } + // Dicts also report their total size in the "too many" error; other + // iterables stop at the first surplus item without reporting a total. + let total = match value { + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Dict(dict) => Some(dict.len()), + _ => None, + }, + _ => None, + }; + // Pull one past `count` so a too-long iterable is detected without + // draining it — CPython stops consuming there too, which is why every + // other type has no total to report. + let items = collect_iterable_bounded(value, count + 1, vm)?; + if items.len() == count { + Ok(items) + } else { + let err = if items.len() > count { + match total { + Some(total) => ExcType::unpack_size_error(count, total), + None => unpack_too_many_unknown_error(count), + } + } else { + // Short of `count`, so the iterable was drained and its true + // length is known whether or not the type could report one. + ExcType::unpack_size_error(count, items.len()) + }; + items.drop_with(vm); + Err(err) + } +} + +/// Returns borrowed items for built-in tuples and lists so unpacking can bypass the iterator protocol. +fn exact_sequence_items<'a>(value: &Value, heap: &'a Heap) -> Option<&'a [Value]> { + let Value::Ref(id) = value else { + return None; + }; + match heap.get(*id) { + HeapData::Tuple(tuple) => Some(tuple.as_slice()), + HeapData::List(list) => Some(list.as_slice()), + _ => None, + } +} + +/// Creates the "too many values" ValueError when the total is unknown. +/// +/// Unpacking an iterator stops at the first surplus item, so unlike +/// [`ExcTypeExt::unpack_size_error`] there is no total to report — matching CPython. +fn unpack_too_many_unknown_error(expected: usize) -> RunError { + SimpleException::new_msg( + ExcType::ValueError, + format!("too many values to unpack (expected {expected})"), + ) + .into() +} + +/// Creates a TypeError for attempting to unpack a non-iterable value. +/// +/// Takes the value rather than its name because the wording depends on *why* it +/// is not iterable — see [`opts_out_of_iter`]. +fn unpack_type_error(value: &Value, vm: &VM<'_>) -> RunError { + let type_name = value.py_type_name(vm); + if opts_out_of_iter(value, vm) { + ExcType::type_error_not_iterable(&type_name) + } else { + SimpleException::new_msg( + ExcType::TypeError, + format!("cannot unpack non-iterable {type_name} object"), + ) + .into() + } +} + +/// Whether a value already known to be non-iterable owes that to `__iter__ = +/// None`, and so keeps the plain "not iterable" message at an unpacking site. +/// +/// CPython substitutes site-specific wording ("cannot unpack non-iterable ...", +/// "Value after * must be an iterable ...") only when the type has no `tp_iter` +/// slot at all; a class opting out with `__iter__ = None` still fills the slot, +/// so `slot_tp_iter`'s own error survives. +fn opts_out_of_iter(value: &Value, vm: &VM<'_>) -> bool { + matches!(value, Value::Ref(id) if instance_defines_iter(*id, vm)) +} diff --git a/crates/bashkit-monty/src/bytecode/vm/compare.rs b/crates/bashkit-monty/src/bytecode/vm/compare.rs new file mode 100644 index 000000000..539669349 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/compare.rs @@ -0,0 +1,148 @@ +//! Comparison operation helpers for the VM. + +use super::VM; +use crate::{ + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + expressions::CmpOperator, + types::{CmpOrder, PyTrait}, + value::Value, +}; + +impl VM<'_> { + /// Evaluates a comparison as a boolean without consuming its operands. + /// + /// Shared by fused asserts and comparison helpers that need truth rather + /// than the arbitrary value a direct `==` expression may produce. + #[inline] + pub(crate) fn cmp_values(&mut self, op: CmpOperator, lhs: &Value, rhs: &Value) -> RunResult { + match op { + CmpOperator::Eq | CmpOperator::NotEq => { + let result = lhs.py_rich_eq(rhs, self)?; + let is_equal = result.py_bool(self); + result.drop_with(self); + let is_equal = is_equal?; + Ok(if op == CmpOperator::NotEq { !is_equal } else { is_equal }) + } + CmpOperator::Is => Ok(lhs.is(rhs)), + CmpOperator::IsNot => Ok(!lhs.is(rhs)), + // `in` tests membership of the *left* operand in the right one. + CmpOperator::In => rhs.py_contains(lhs, self), + CmpOperator::NotIn => Ok(!rhs.py_contains(lhs, self)?), + CmpOperator::Lt | CmpOperator::LtE | CmpOperator::Gt | CmpOperator::GtE => self.cmp_ordering(op, lhs, rhs), + } + } + + /// Executes direct `==`, preserving an arbitrary value returned by `__eq__`. + pub(super) fn compare_eq(&mut self) -> Result<(), RunError> { + let this = self; + let rhs = this.pop(); + defer_drop!(rhs, this); + let lhs = this.pop(); + defer_drop!(lhs, this); + + let result = lhs.py_rich_eq(rhs, this)?; + this.push(result); + Ok(()) + } + + /// Executes direct `!=`; user `__ne__` dispatch is not yet supported. + pub(super) fn compare_ne(&mut self) -> Result<(), RunError> { + let this = self; + let rhs = this.pop(); + defer_drop!(rhs, this); + let lhs = this.pop(); + defer_drop!(lhs, this); + + let result = lhs.py_rich_eq(rhs, this)?; + defer_drop!(result, this); + let is_not_equal = !result.py_bool(this)?; + this.push(Value::Bool(is_not_equal)); + Ok(()) + } + + /// Evaluates an ordering comparison, preserving CPython's behavior for + /// unordered values such as `NaN` and incomparable operand types. + #[inline] + fn cmp_ordering(&mut self, op: CmpOperator, lhs: &Value, rhs: &Value) -> RunResult { + // A type whose ordering no `CmpOrder` describes (a `Counter` compares as + // a multiset) answers the operator itself. Hooked in here rather than at + // the opcode so the fused-assert path, which calls `cmp_values` directly, + // gets the same semantics. + if let Some(result) = lhs.py_cmp_op(rhs, op, self)? { + return Ok(result); + } + + // The right operand may handle a comparison the left declines: + // dict_keys <= set is answered by set >= dict_keys. + let reflected_op = match op { + CmpOperator::Lt => CmpOperator::Gt, + CmpOperator::LtE => CmpOperator::GtE, + CmpOperator::Gt => CmpOperator::Lt, + CmpOperator::GtE => CmpOperator::LtE, + _ => unreachable!("cmp_ordering reached with a non-ordering operator"), + }; + if let Some(result) = rhs.py_cmp_op(lhs, reflected_op, self)? { + return Ok(result); + } + + match lhs.py_cmp(rhs, self)? { + CmpOrder::Ordered(ordering) => Ok(match op { + CmpOperator::Lt => ordering.is_lt(), + CmpOperator::LtE => ordering.is_le(), + CmpOperator::Gt => ordering.is_gt(), + CmpOperator::GtE => ordering.is_ge(), + // `cmp_values` calls this only for ordering operators. + _ => unreachable!("cmp_ordering reached with a non-ordering operator"), + }), + CmpOrder::Unordered => Ok(false), + CmpOrder::Incomparable => { + let left_type = lhs.py_type_name(self); + let right_type = rhs.py_type_name(self); + Err(ExcType::type_error_ordering(op.as_str(), &left_type, &right_type)) + } + } + } + + /// Pops both operands and pushes a boolean comparison result. + /// The const operator lets dispatch specialize the implementation per opcode. + fn compare_op(&mut self) -> Result<(), RunError> { + // Rejects a bad `OP` at compile time, which makes the `else` dead. + const { assert!(CmpOperator::from_repr(OP).is_some(), "invalid CmpOperator operand") }; + let op = CmpOperator::from_repr(OP).expect("invalid CmpOperator operand"); + let this = self; + + let rhs = this.pop(); + defer_drop!(rhs, this); + let lhs = this.pop(); + defer_drop!(lhs, this); + + let result = this.cmp_values(op, lhs, rhs)?; + this.push(Value::Bool(result)); + Ok(()) + } +} + +/// Defines a specialized entry point for each boolean comparison opcode. +macro_rules! compare_opcodes { + ($($name:ident => $op:ident,)*) => { + impl VM<'_> { + $( + pub(super) fn $name(&mut self) -> Result<(), RunError> { + self.compare_op::<{ CmpOperator::$op.as_operand() }>() + } + )* + } + }; +} + +compare_opcodes! { + compare_lt => Lt, + compare_le => LtE, + compare_gt => Gt, + compare_ge => GtE, + compare_is => Is, + compare_is_not => IsNot, + compare_in => In, + compare_not_in => NotIn, +} diff --git a/crates/bashkit-monty/src/bytecode/vm/context_manager.rs b/crates/bashkit-monty/src/bytecode/vm/context_manager.rs new file mode 100644 index 000000000..c3eedf715 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/context_manager.rs @@ -0,0 +1,89 @@ +//! Context-manager opcode helpers (`BeforeWith`, `WithExit`, `WithExceptStart`). +//! +//! These three opcodes dispatch directly to `PyTrait::py_enter` / `PyTrait::py_exit` +//! rather than the generic `CallAttr` machinery — explicit invocation is cheaper +//! (no attribute lookup) and matches CPython's `BEFORE_WITH` / `WITH_EXCEPT_START` +//! shape. Each helper returns a `CallResult` so the host can suspend during the +//! call (e.g. `OpenFile.__exit__` issues an `OsCall` to close the file); the +//! caller routes the result through `handle_call_result!`. + +use super::{CallResult, VM}; +use crate::{ + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + types::PyTrait, + value::Value, +}; + +impl VM<'_> { + /// `BeforeWith`: peek the context manager at TOS, call `__enter__`, and push + /// the result. The context manager stays on the stack across the body so the + /// matching `WithExit` / `WithExceptStart` can find it. + /// + /// The CPython "object does not support the context manager protocol" + /// `TypeError` is gated on [`PyTrait::py_is_context_manager`] so we never + /// have to sniff exception messages — a real context manager whose + /// `__enter__` itself raises `AttributeError` propagates unchanged. + pub(super) fn exec_before_with(&mut self) -> RunResult { + // Pattern-matching `*self.peek()` is a place expression so it doesn't + // move the whole Value — Rust only copies the HeapId out. Non-Ref + // values (Int, Bool, None, …) never implement the protocol. + let Value::Ref(ctx_id) = *self.peek() else { + return Err(not_a_context_manager(self)); + }; + let mut ctx = self.heap.read(ctx_id); + if ctx.py_is_context_manager(self) { + ctx.py_enter(self) + } else { + Err(not_a_context_manager(self)) + } + } + + /// `WithExit`: pop the context manager, call `__exit__(None, None, None)`, + /// and push the result. The compiler emits a trailing `Pop` to discard the + /// result; splitting "call + discard" lets the call yield to the host while + /// the discard happens once the host has resumed with the return value. + pub(super) fn exec_with_exit(&mut self) -> RunResult { + let this = self; + let ctx = this.pop(); + let Value::Ref(ctx_id) = ctx else { + unreachable!("WithExit: expected context-manager ref on stack"); + }; + // Drop the ctx reference on every exit path of this function — whether + // py_exit returns a value, yields, or errors. This matches the ref-count + // balance from BeforeWith's push. + defer_drop!(ctx, this); + this.heap.read(ctx_id).py_exit(this, None) + } + + /// `WithExceptStart`: peek at `[..., ctx, exc]`, call + /// `__exit__(type(exc), exc, None)`, and push the raw return value. The + /// compiler-emitted `JumpIfTrue` then branches on its truthiness to either + /// suppress (Pop ctx, Pop exc, ClearException) or re-raise (Pop ctx, Pop exc, + /// Reraise). + pub(super) fn exec_with_except_start(&mut self) -> RunResult { + let len = self.stack.len(); + // Pattern-match via place expressions so neither stack slot is moved. + let Value::Ref(exc_id) = self.stack[len - 1] else { + unreachable!("WithExceptStart: expected exception ref on stack"); + }; + let Value::Ref(ctx_id) = self.stack[len - 2] else { + unreachable!("WithExceptStart: expected context-manager ref on stack"); + }; + self.heap.read(ctx_id).py_exit(self, Some(exc_id)) + } +} + +/// Builds the CPython-equivalent `TypeError` raised when a value used in a +/// `with` statement does not implement the context-manager protocol. +/// +/// CPython's message names the missing dunder, and it checks `__exit__` +/// first — [`PyTrait::py_is_context_manager`] mirrors that (user classes +/// check their namespace for `__exit__`; builtin types answer per-type), so +/// this gate failure always reports `__exit__`. A user class that defines +/// `__exit__` but not `__enter__` passes the gate and gets the +/// "missed __enter__ method" variant from `Instance::py_enter` instead. +fn not_a_context_manager(vm: &VM<'_>) -> RunError { + let ty = vm.peek().py_type_name(vm); + ExcType::type_error_not_context_manager(ty, "__exit__") +} diff --git a/crates/bashkit-monty/src/bytecode/vm/exceptions.rs b/crates/bashkit-monty/src/bytecode/vm/exceptions.rs new file mode 100644 index 000000000..b655aa6b6 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/exceptions.rs @@ -0,0 +1,638 @@ +//! Exception handling helpers for the VM. + +use std::fmt::{self, Write}; + +use super::VM; +use crate::{ + builtins::Builtins, + defer_drop, + exception_private::{ExcType, ExcTypeExt, ExceptionRaise, RawStackFrame, RunError, RunResult, SimpleException}, + expressions::CmpOperator, + heap::{ContainsHeap, DropGuard, DropWithContext, HeapData}, + intern::{StaticStrings, StringId}, + types::{LazyHeapSet, PyTrait, Type}, + value::Value, +}; + +/// An active exception, preserving its traceback across invisible implementation handlers. +/// Ordinary entries keep the existing serialized `Value` shape for upstream dump compatibility. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub(super) enum CaughtException { + /// An exception handled by user code, retaining its existing dump representation. + Value(Value), + /// An internal handler must not replace the original traceback when its match fails. + Frozen { value: Value, error: Box }, +} + +impl CaughtException { + /// Borrows the exception object without exposing its internal traceback metadata. + fn value(&self) -> &Value { + match self { + Self::Value(value) | Self::Frozen { value, .. } => value, + } + } +} + +impl DropWithContext for CaughtException { + fn drop_with(self, ctx: &mut C) { + match self { + Self::Value(value) | Self::Frozen { value, .. } => value.drop_with(ctx), + } + } +} + +/// Whether exception handling finished or must continue in a newly activated task. +enum ExceptionHandlingResult { + /// Execution can resume without propagating an error to the caller. + Caught, + /// The error should be returned to the VM caller. + Unhandled(RunError), + /// The newly activated task has an exception to handle before running bytecode. + NextTask(RunError), +} + +impl VM<'_> { + /// Returns the current function name, or `` outside a function. + fn current_frame_name(&self) -> StringId { + match self.current_frame().function_id { + Some(func_id) => self.interns.get_function(func_id).name.name_id, + None => self.interns.intern_static(StaticStrings::Module), + } + } + + /// Creates a `RawStackFrame` for the current execution point. + /// + /// Used when raising exceptions to capture traceback information. + fn make_stack_frame(&self) -> RawStackFrame { + RawStackFrame::new(self.current_position(), self.current_frame_name(), None) + } + + /// Returns whether the active frame implements a builtin in frozen Python. + pub(super) fn current_frame_is_frozen(&self) -> bool { + self.current_frame() + .function_id + .is_some_and(|id| self.interns.is_internal_function(id)) + } + + /// Attaches initial frame information to an error if it doesn't have any. + /// + /// Only sets the innermost frame if the exception doesn't already have one. + /// Caller frames are added separately during exception propagation. + /// + /// Uses the `hide_caret` flag from `ExceptionRaise` to determine whether to show + /// the caret marker in the traceback. This flag is set by error creators that know + /// whether CPython would show a caret for this specific error type. + fn attach_frame_to_error(&self, error: RunError) -> RunError { + match error { + RunError::Exc(mut exc) => { + if exc.frame.is_none() && !self.current_frame_is_frozen() { + let mut frame = self.make_stack_frame(); + // Use the hide_caret flag from the error (set by error creators) + frame.hide_caret = exc.hide_caret; + exc.frame = Some(frame); + } + RunError::Exc(exc) + } + RunError::UncatchableExc(mut exc) => { + if exc.frame.is_none() && !self.current_frame_is_frozen() { + let mut frame = self.make_stack_frame(); + frame.hide_caret = exc.hide_caret; + exc.frame = Some(frame); + } + RunError::UncatchableExc(exc) + } + RunError::Internal(_) => error, + } + } + + /// Creates a RunError from a Value that should be an exception. + /// + /// Borrows the value so callers that already own one can keep it — the + /// `raise`/`Reraise` paths reuse it as the raised object itself. + /// The `is_raise` flag indicates if this is from a `raise` statement (hide caret). + pub(super) fn make_exception(&mut self, exc_value: &Value, is_raise: bool) -> RunError { + let simple_exc = match exc_value { + // Exception instance on heap + Value::Ref(heap_id) => { + if let HeapData::Exception(exc) = self.heap.get(*heap_id) { + exc.clone() + } else { + // Not an exception type + SimpleException::new_msg(ExcType::TypeError, "exceptions must derive from BaseException") + } + } + // Exception type (e.g., `raise ValueError` instead of `raise ValueError()`) + // Instantiate with no message + Value::Builtin(Builtins::ExcType(exc_type)) => SimpleException::new_none(*exc_type), + // Invalid exception value + _ => SimpleException::new_msg(ExcType::TypeError, "exceptions must derive from BaseException"), + }; + + let frame = (!self.current_frame_is_frozen()).then(|| { + if is_raise { + RawStackFrame::from_raise(self.current_position(), self.current_frame_name()) + } else { + self.make_stack_frame() + } + }); + + RunError::Exc(ExceptionRaise { + exc: simple_exc, + frame, + snippet_frame: None, + hide_caret: false, + }) + } + + /// Re-raises the active exception without replacing a user traceback with an internal handler. + pub(super) fn reraise_exception(&mut self) -> (RunError, Option) { + if let Some(caught) = self.exception_stack.last() { + let raised = caught.value().clone_with_heap(self.heap); + let error = if self.current_frame_is_frozen() + && let CaughtException::Frozen { error, .. } = caught + { + RunError::Exc((**error).clone()) + } else { + self.make_exception(&raised, true) + }; + (error, Some(raised)) + } else { + ( + SimpleException::new_msg(ExcType::RuntimeError, "No active exception to reraise").into(), + None, + ) + } + } + + /// Runs fused bare `assert test`. + /// + /// Truthy values pass; falsy values raise with their repr, except literal + /// `False` has no detail because `assert False` adds no information. + pub(super) fn assert_test(&mut self) -> Result<(), RunError> { + let this = self; + let test = this.pop(); + defer_drop!(test, this); + if test.py_bool(this)? { + Ok(()) + } else if matches!(test, Value::Bool(false)) { + Err(this.assertion_error(None)) + } else { + let detail = assert_operand_repr(test, this).map(Some); + Err(this.assert_failure(detail)) + } + } + + /// Runs fused bare `assert lhs OP rhs`. + /// + /// Shares [`cmp_values`](VM::cmp_values) with the `Compare*` opcodes, so + /// the comparison (and any `TypeError` it raises) behaves identically to + /// the unfused form; only a `false` result diverges, raising with both + /// operand reprs. + pub(super) fn assert_cmp(&mut self, op: CmpOperator) -> Result<(), RunError> { + let this = self; + let rhs = this.pop(); + defer_drop!(rhs, this); + let lhs = this.pop(); + defer_drop!(lhs, this); + if this.cmp_values(op, lhs, rhs)? { + Ok(()) + } else { + let detail = assert_operand_repr(lhs, this).and_then(|lhs_repr| { + let rhs_repr = assert_operand_repr(rhs, this)?; + Ok(Some(format!("{lhs_repr} {op} {rhs_repr}"))) + }); + Err(this.assert_failure(detail)) + } + } + + /// Converts best-effort detail into an `AssertionError` message. + /// Catchable formatting errors fall back to no detail; terminal errors propagate. + fn assert_failure(&self, detail: RunResult>) -> RunError { + match detail { + Ok(Some(detail)) => self.assertion_error(Some(format!("assert {detail}"))), + Ok(None) | Err(RunError::Exc(_)) => self.assertion_error(None), + Err(e) => e, + } + } + + /// Raises for failed `assert test, msg`. + /// + /// Uses `msg` first and appends introspected detail when available. If + /// either formatting path raises a Python exception, the other still wins. + pub(super) fn assert_failed_msg(&mut self, cmp_op: Option) -> RunError { + let this = self; + let msg_value = this.pop(); + defer_drop!(msg_value, this); + // Format the operands first so they are popped and released even if + // the message itself fails to stringify. + let detail = match this.assert_detail(cmp_op) { + Ok(detail) => detail, + Err(RunError::Exc(_)) => None, + Err(e) => return e, + }; + let msg = match assert_msg_str(msg_value, this) { + // An empty message adds nothing, so treat it like an absent one and + // show only the detail — avoids a stray leading `\n` before `assert`. + Ok(msg) if msg.is_empty() => None, + Ok(msg) => Some(msg), + Err(RunError::Exc(_)) => None, + Err(e) => return e, + }; + let full = match (msg, detail) { + (Some(msg), Some(detail)) => Some(format!("{msg}\nassert {detail}")), + (Some(msg), None) => Some(msg), + (None, Some(detail)) => Some(format!("assert {detail}")), + (None, None) => None, + }; + this.assertion_error(full) + } + + /// Pops failed assert operands and formats their detail. + /// + /// Comparisons produce `{lhs!r} {op} {rhs!r}`; other tests use the falsy + /// value repr. Literal `False` returns no detail. + fn assert_detail(&mut self, cmp_op: Option) -> RunResult> { + let this = self; + if let Some(op) = cmp_op { + let rhs = this.pop(); + defer_drop!(rhs, this); + let lhs = this.pop(); + defer_drop!(lhs, this); + let lhs_repr = assert_operand_repr(lhs, this)?; + let rhs_repr = assert_operand_repr(rhs, this)?; + Ok(Some(format!("{lhs_repr} {op} {rhs_repr}"))) + } else { + let test = this.pop(); + defer_drop!(test, this); + if matches!(test, Value::Bool(false)) { + Ok(None) + } else { + assert_operand_repr(test, this).map(Some) + } + } + } + + /// Creates an `AssertionError` raised at the current source position. + fn assertion_error(&self, msg: Option) -> RunError { + let frame = (!self.current_frame_is_frozen()) + .then(|| RawStackFrame::from_raise(self.current_position(), self.current_frame_name())); + RunError::Exc(ExceptionRaise { + exc: SimpleException::new(ExcType::AssertionError, msg), + frame, + snippet_frame: None, + hide_caret: false, + }) + } + + /// Handles an exception by searching for a handler in the exception table. + /// + /// Returns: + /// - `Some(VMResult)` if the exception was not caught (should return from run loop) + /// - `None` if the exception was caught (continue execution) + /// + /// When an exception is caught: + /// 1. Unwinds the stack to the handler's expected depth + /// 2. Pushes the exception value onto the stack + /// 3. Sets `current_exception` for bare `raise` + /// 4. Jumps to the handler code + pub(super) fn handle_exception(&mut self, error: RunError) -> Option { + self.handle_exception_with_value(error, None) + } + + /// [`handle_exception`](Self::handle_exception) reusing an already-built + /// exception instead of reallocating an identical one per level; this also + /// preserves its identity, as CPython does. Owned: dropped if unused. + pub(super) fn handle_exception_with_value( + &mut self, + mut error: RunError, + mut raised: Option, + ) -> Option { + loop { + match self.handle_exception_step(error, raised.take()) { + ExceptionHandlingResult::Caught => return None, + ExceptionHandlingResult::Unhandled(error) => return Some(error), + ExceptionHandlingResult::NextTask(next_error) => error = next_error, + } + } + } + + /// Handles one task's exception, returning to the caller's loop if another task must raise. + fn handle_exception_step(&mut self, mut error: RunError, raised: Option) -> ExceptionHandlingResult { + // Ensure exception has initial frame info + error = self.attach_frame_to_error(error); + + // For terminal resource errors such as memory limits, + // we still need to unwind the stack to collect all frames for the traceback + if matches!(error, RunError::UncatchableExc(_) | RunError::Internal(_)) { + if let Some(raised) = raised { + raised.drop_with(self); + } + return ExceptionHandlingResult::Unhandled(self.unwind_for_traceback(error)); + } + + let exc_value = if let Some(raised) = raised { + raised + } else { + // Nothing to reuse: build it from `error`, borrowed rather than + // cloned since it is a local and so cannot alias `self`. + let RunError::Exc(exc) = &error else { + unreachable!("terminal errors returned above") + }; + self.create_exception_value(exc) + }; + + // Use DropGuard because exc_value is conditionally consumed (pushed onto + // exception_stack when handler found) or dropped (when no handler found) + let mut exc_guard = DropGuard::new(exc_value, self); + + // Search for handler in current and outer frames + loop { + let (exc_value, this) = exc_guard.as_parts(); + let frame = this.current_frame(); + let code = frame.code; + let ip = u32::try_from(this.instruction_ip).unwrap_or(u32::MAX); + + // Search exception table for a handler covering this IP + if let Some(entry) = code.find_exception_handler(ip) { + // Unwind operands to the compiler-recorded region depth, + // including any in-flight comprehension values. + let handler_offset = entry.handler() as usize; + let target_stack_depth = + frame.stack_base() + frame.locals_count as usize + entry.stack_depth() as usize; + let target_exc_stack_depth = frame.exception_stack_base() + entry.exception_stack_count() as usize; + let pushes_exception = entry.pushes_exception(); + + // Unwind stack to target depth (drop excess values) + for value in this.stack.drain(target_stack_depth..).rev() { + value.drop_with(this.heap); + } + + // Drop exceptions from bypassed handlers so a later bare + // `raise` cannot revive them. + while this.exception_stack.len() > target_exc_stack_depth { + let value = this.exception_stack.pop().unwrap(); + value.drop_with(this); + } + + // Push the exception only for handlers that read it; cleanup + // handlers re-raise straight from `exception_stack`. + if pushes_exception { + let exc_for_stack = exc_value.clone_with_heap(this); + this.push(exc_for_stack); + } + + // Reclaim exc_value from guard - it's being pushed onto exception_stack + let (exc_value, this) = exc_guard.into_parts(); + + // Push exception onto the exception_stack for bare raise. + // This allows nested except handlers to restore outer + // exception context. + let caught = if this.current_frame_is_frozen() { + let RunError::Exc(error) = error else { + unreachable!("only catchable exceptions enter handlers") + }; + CaughtException::Frozen { + value: exc_value, + error: Box::new(error), + } + } else { + CaughtException::Value(exc_value) + }; + this.exception_stack.push(caught); + + // Jump to handler + this.current_frame_mut().ip = handler_offset; + + return ExceptionHandlingResult::Caught; + } + + // No handler in this frame - pop frame and try outer + if this.suspended_frames.is_empty() { + // No more frames - exception is unhandled + let is_spawned = this.is_spawned_task(); + + // Drop exc_value before potentially switching tasks + drop(exc_guard); + + // For spawned tasks, fail the task instead of propagating + if is_spawned { + return match self.handle_task_failure(error) { + Ok(()) => { + // Switched to next task - continue execution + ExceptionHandlingResult::Caught + } + Err(next_error) => ExceptionHandlingResult::NextTask(next_error), + }; + } + + return ExceptionHandlingResult::Unhandled(error); + } + + // Get the caller's call-site offset before popping frame. + // This is where the caller invoked the function that's failing. + let call_offset = this.current_frame().call_offset; + + // Synchronous evaluation stops unwinding here, but its caller still + // belongs in the traceback when the error crosses that boundary. + let should_return = this.pop_frame(); + + // Add caller frame info to traceback (if we have a call site). + // Resolve the offset now — against the caller, which is the current + // frame after the pop above. + if let Some(off) = call_offset + && !this.current_frame_is_frozen() + { + let pos = this.resolve_offset(off); + let frame_name = this.current_frame_name(); + match &mut error { + RunError::Exc(exc) => exc.add_caller_frame(pos, frame_name), + RunError::UncatchableExc(exc) => exc.add_caller_frame(pos, frame_name), + RunError::Internal(_) => {} + } + } + if should_return { + return ExceptionHandlingResult::Unhandled(error); + } + } + } + + /// Collects terminal-error traceback frames up to the next synchronous boundary. + /// Native callers must release their borrows before their Python frames are unwound. + fn unwind_for_traceback(&mut self, mut error: RunError) -> RunError { + // Pop frames and add caller frame info to the traceback + while !self.suspended_frames.is_empty() { + // Get the caller's call-site offset before popping frame + let call_offset = self.current_frame().call_offset; + + let should_return = self.pop_frame(); + + // Add caller frame info to traceback. Resolve the offset against the + // caller, which is the current frame after the pop above. + if let Some(off) = call_offset + && !self.current_frame_is_frozen() + { + let pos = self.resolve_offset(off); + let frame_name = self.current_frame_name(); + match &mut error { + RunError::Exc(exc) => exc.add_caller_frame(pos, frame_name), + RunError::UncatchableExc(exc) => exc.add_caller_frame(pos, frame_name), + RunError::Internal(_) => {} + } + } + if should_return { + break; + } + } + error + } + + /// Creates an exception Value from exception info. + /// + /// Allocates an Exception on the heap and returns a Value::Ref to it. + fn create_exception_value(&mut self, exc: &ExceptionRaise) -> Value { + let exception = exc.exc.clone(); + let heap_id = self.heap.allocate(HeapData::Exception(exception)); + Value::Ref(heap_id) + } + + /// Checks if an exception matches an `except` clause's exception type. + /// + /// `exc_type` must be either a single exception class, or a *flat* tuple of + /// exception classes. Returns `Ok(true)` if the exception matches, `Ok(false)` + /// if it doesn't, or `Err` if `exc_type` is not a valid exception type. + /// + /// This deliberately does **not** recurse into nested tuples. The exception + /// type handed to `except` is constructed at runtime, so a tuple could be + /// nested arbitrarily deeply regardless of source nesting limits; a recursive + /// matcher would overflow the host's native stack inside this single bytecode + /// instruction. Mirroring CPython's `check_except_type_valid` (the + /// `CHECK_EXC_MATCH` opcode), only one level of tuple is accepted: a nested + /// tuple element — or any non-exception value — raises + /// `TypeError: catching classes that do not inherit from BaseException is not + /// allowed`. Removing the recursion both keeps parity with CPython and + /// eliminates the unbounded-recursion footgun entirely, so no recursion-depth + /// or time bound is needed here. + /// + /// Like CPython, the *whole* tuple is validated rather than short-circuiting + /// on the first match: an invalid element raises the `TypeError` even when an + /// earlier element already matched (e.g. `except (TypeError, (ValueError,))` + /// raising `TypeError` still raises the `TypeError` about catching classes). + pub(super) fn check_exc_match(&self, exception: &Value, exc_type: &Value) -> Result { + let exc_type_enum = exception.py_type(self); + match exc_type { + // Single exception class. + Value::Builtin(Builtins::ExcType(handler_type)) => { + Ok(Self::exc_matches_handler(exc_type_enum, *handler_type)) + } + // Flat tuple of exception classes. CPython does not descend into + // nested tuples in this position, so neither do we. + Value::Ref(id) => { + if let HeapData::Tuple(tuple) = self.heap.get(*id) { + let mut matched = false; + for v in tuple.as_slice() { + match v { + Value::Builtin(Builtins::ExcType(handler_type)) => { + if !matched && Self::exc_matches_handler(exc_type_enum, *handler_type) { + matched = true; + } + } + // A nested tuple or any non-exception value is + // rejected exactly as CPython rejects it, even if a + // previous element already matched. + _ => return Err(ExcType::except_invalid_type_error()), + } + } + Ok(matched) + } else { + // A non-tuple heap value (e.g. an exception instance) is not + // a valid exception type for an `except` clause. + Err(ExcType::except_invalid_type_error()) + } + } + // Any other value is invalid for an `except` clause. + _ => Err(ExcType::except_invalid_type_error()), + } + } + + /// Returns whether a raised exception's type is caught by `handler_type`. + /// + /// Helper shared by the single-class and flat-tuple arms of + /// [`check_exc_match`]; the raised value only matches when its type is an + /// exception that is a subclass of the handler's class. + fn exc_matches_handler(exc_type_enum: Type, handler_type: ExcType) -> bool { + matches!(exc_type_enum, Type::Exception(et) if et.is_subclass_of(handler_type)) + } +} + +/// Streams an assert operand's repr into the configured byte-capped writer. +/// Reaching the cap stops formatting the remainder and appends `…`. +fn assert_operand_repr(value: &Value, vm: &mut VM<'_>) -> RunResult { + let mut writer = TruncatingWriter::new(vm.env.assert_repr_max_bytes as usize); + let mut heap_ids = LazyHeapSet::default(); + match value.py_repr_fmt(&mut writer, vm, &mut heap_ids) { + Ok(()) => Ok(writer.into_string()), + // The cap abort is ours: the partial repr is the result. Genuine + // errors can only surface before the cap (post-cap writes do no VM work). + Err(_) if writer.truncated => Ok(writer.into_string()), + Err(e) => Err(e), + } +} + +/// `str()` of an explicit assert message, matching how the message renders in +/// `AssertionError: {msg}` — not truncated, since the user chose it explicitly. +fn assert_msg_str(value: &Value, vm: &mut VM<'_>) -> RunResult { + let str_value = value.py_str(vm)?; + defer_drop!(str_value, vm); + Ok(str_value.to_str(vm)?.to_owned()) +} + +/// Byte-capped sink that stops repr formatting on a character boundary. +/// Its buffer is untracked because `py_repr_fmt` also needs mutable VM access. +struct TruncatingWriter { + buf: String, + /// Bytes still accepted before the cap. + remaining: usize, + /// Set when input was cut at the cap; `into_string` then appends `…`. + truncated: bool, +} + +impl TruncatingWriter { + fn new(max_bytes: usize) -> Self { + Self { + buf: String::new(), + remaining: max_bytes, + truncated: false, + } + } + + /// Consumes the writer, appending `…` when input was cut at the cap. + fn into_string(mut self) -> String { + if self.truncated { + self.buf.push('…'); + } + self.buf + } +} + +impl Write for TruncatingWriter { + fn write_str(&mut self, s: &str) -> fmt::Result { + if self.truncated { + Err(fmt::Error) + } else if let Some(remaining) = self.remaining.checked_sub(s.len()) { + self.remaining = remaining; + self.buf.push_str(s); + Ok(()) + } else { + // Over budget: cut at the last char boundary in budget (≤3 steps back). + let mut idx = self.remaining; + while !s.is_char_boundary(idx) { + idx -= 1; + } + self.buf.push_str(&s[..idx]); + self.remaining = 0; + self.truncated = true; + Err(fmt::Error) + } + } +} diff --git a/crates/bashkit-monty/src/bytecode/vm/format.rs b/crates/bashkit-monty/src/bytecode/vm/format.rs new file mode 100644 index 000000000..7d101ae7e --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/format.rs @@ -0,0 +1,288 @@ +//! F-string and value formatting helpers for the VM. + +use std::fmt::Write as _; + +use super::VM; +use crate::{ + bytecode::op::{FORMAT_VALUE_HAS_SPEC, FORMAT_VALUE_STATIC_SPEC}, + defer_drop, + exception_private::{ExcType, RunError, SimpleException}, + fstring::{ + ParseFormatSpecReason, ParsedFormatSpec, decode_format_spec, format_string, format_with_spec, + validate_string_spec, + }, + heap::HeapReadOutput, + intern::StringId, + string_builder::StringBuilder, + types::{ + PyTrait, Type, + date::format_date_strftime, + datetime::format_datetime_strftime, + decimal, + str::allocate_string, + time::{attached_timezone, format_time_strftime}, + }, + value::Value, +}; + +impl VM<'_> { + /// Builds an f-string by concatenating n string parts from the stack. + pub(super) fn build_fstring(&mut self, count: usize) -> Result<(), RunError> { + if count == 1 { + return Ok(()); + } + let this = self; + if count == 0 { + this.push(Value::InternString(StringId::EMPTY)); + return Ok(()); + } + + let parts = this.pop_n(count); + defer_drop!(parts, this); + + let mut total_len = 0_usize; + for part in parts.as_slice() { + let s = part.to_str_heap(this.heap, this.interns)?; + total_len = total_len.saturating_add(s.len()); + } + + this.heap.tracker.check_allocation(total_len)?; + let mut result = String::with_capacity(total_len); + + for part in parts.as_slice() { + let s = part.to_str_heap(this.heap, this.interns)?; + result.push_str(s); + } + + let value = allocate_string(result, this.heap); + this.push(value); + Ok(()) + } + + /// Formats a value for f-string interpolation. + /// + /// See `Opcode::FormatValue` for the flag layout. + pub(super) fn format_value(&mut self, flags: u8) -> Result<(), RunError> { + let this = self; + let conversion = flags & 0x03; + let has_format_spec = (flags & FORMAT_VALUE_HAS_SPEC) != 0; + let static_spec = (flags & FORMAT_VALUE_STATIC_SPEC) != 0; + + // Pop format spec if present (pushed before value, so popped after) + let format_spec = if has_format_spec { Some(this.pop()) } else { None }; + + let value = this.pop(); + defer_drop!(value, this); + + let formatted = match format_spec { + Some(spec_value) => { + defer_drop!(spec_value, this); + if static_spec { + // The compiler only sets this flag for encoded integer specs. + let Value::Int(encoded) = spec_value else { + unreachable!("FORMAT_VALUE_STATIC_SPEC flag without Value::Int on stack"); + }; + let spec = decode_format_spec(*encoded); + this.format_parsed_value(value, conversion, &spec)? + } else { + let spec = str_value_into_string(spec_value.py_str(this)?, this)?; + this.format_runtime_value(value, conversion, Some(&spec))? + } + } + None => this.format_runtime_value(value, conversion, None)?, + }; + + let result = allocate_string(formatted, this.heap); + this.push(result); + Ok(()) + } + + /// Formats a value from a runtime format spec. + pub(crate) fn format_runtime_value( + &mut self, + value: &Value, + conversion: u8, + format_spec: Option<&str>, + ) -> Result { + if conversion != 0 { + let converted = self.convert_value(value, conversion)?; + if let Some(format_spec) = format_spec { + self.format_runtime_string(&converted, format_spec) + } else { + Ok(converted) + } + } else if let Some(format_spec) = format_spec { + if let Some(formatted) = self.try_format_temporal(value, format_spec)? { + Ok(formatted) + } else if let Some(formatted) = self.try_format_decimal(value, format_spec)? { + Ok(formatted) + } else { + let value_type = value.py_type_name(self); + let spec = self.parse_runtime_spec(format_spec, &value_type)?; + self.format_parsed_value(value, 0, &spec) + } + } else { + self.convert_value(value, 0) + } + } + + /// Formats an already-converted string from a runtime format spec. + pub(crate) fn format_runtime_string(&mut self, value: &str, format_spec: &str) -> Result { + let spec = self.parse_runtime_spec(format_spec, "str")?; + self.format_parsed_string(value, &spec) + } + + /// Formats a value from a parsed format spec. + fn format_parsed_value( + &mut self, + value: &Value, + conversion: u8, + spec: &ParsedFormatSpec, + ) -> Result { + if conversion == 0 { + // Only a `Decimal` needs the spec back as text; checking first keeps the + // render off every other value's path. + if decimal::py::as_decimal(value, self).is_some() + && let Some(formatted) = self.try_format_decimal(value, &spec.to_spec_string())? + { + return Ok(formatted); + } + format_with_spec(value, spec, self) + } else { + let s = self.convert_value(value, conversion)?; + self.format_parsed_string(&s, spec) + } + } + + /// Formats a string from a parsed format spec. + fn format_parsed_string(&self, value: &str, spec: &ParsedFormatSpec) -> Result { + validate_string_spec(spec)?; + format_string(value, spec, &self.heap.tracker) + } + + /// Applies the f-string and `str.format()` conversion flags to a value. + pub(crate) fn convert_value(&mut self, value: &Value, conversion: u8) -> Result { + match conversion { + 0 | 1 if value.py_type(self) == Type::Str => Ok(value.to_str(self)?.to_owned()), + 2 => str_value_into_string(value.py_repr(self)?, self), + 3 => { + let value = str_value_into_string(value.py_repr(self)?, self)?; + let mut escaped = StringBuilder::with_capacity(value.len(), &self.heap.tracker)?; + for (index, character) in value.chars().enumerate() { + self.heap.tracker.check_time_every(index)?; + if character.is_ascii() { + escaped.push(character)?; + } else { + let code = u32::from(character); + let result = if code <= 0xff { + write!(escaped, "\\x{code:02x}") + } else if code <= 0xffff { + write!(escaped, "\\u{code:04x}") + } else { + write!(escaped, "\\U{code:08x}") + }; + if result.is_err() { + return escaped.finish_raw(); + } + } + } + escaped.finish_raw() + } + // No conversion and `!s` both use `str()`. + _ => str_value_into_string(value.py_str(self)?, self), + } + } + + /// Keeps temporal strftime specs out of generic mini-language parsing. + fn try_format_temporal(&mut self, value: &Value, spec_str: &str) -> Result, RunError> { + let Value::Ref(id) = value else { + return Ok(None); + }; + let id = *id; + let temporal = matches!( + self.heap.read(id), + HeapReadOutput::Date(_) | HeapReadOutput::DateTime(_) | HeapReadOutput::Time(_) + ); + if !temporal { + return Ok(None); + } + + // `datetime.__format__("")` falls back to `str()`. + if spec_str.is_empty() { + return self.convert_value(value, 0).map(Some); + } + + let formatted = match self.heap.read(id) { + HeapReadOutput::Date(d) => format_date_strftime(*d.get(self.heap), spec_str, &self.heap.tracker), + HeapReadOutput::DateTime(d) => format_datetime_strftime(d.get(self.heap), spec_str, &self.heap.tracker), + HeapReadOutput::Time(t) => { + let tz = attached_timezone(t.get(self.heap), self.heap); + format_time_strftime(t.get(self.heap), tz.as_ref(), spec_str, &self.heap.tracker) + } + _ => unreachable!("temporal-ness checked above"), + }; + formatted.map(Some) + } + + /// Formats a `Decimal` with its own spec grammar (`Decimal.__format__`), under the + /// current context's rounding and capitals; `None` for any other value. + fn try_format_decimal(&mut self, value: &Value, spec: &str) -> Result, RunError> { + if decimal::py::as_decimal(value, self).is_some() { + let ctx_id = decimal::py_context::current_context(self); + decimal::py::with_ctx(self, ctx_id, |ctx, vm| { + decimal::py::as_decimal(value, vm) + .expect("checked above") + .format_spec(spec, ctx) + }) + .map(Some) + } else { + Ok(None) + } + } + + /// Parses a runtime spec without copying it onto an error path. + fn parse_runtime_spec(&self, spec: &str, value_type: &str) -> Result { + let reason = match ParsedFormatSpec::parse_runtime(spec) { + Ok(parsed) => return Ok(parsed), + Err(reason) => reason, + }; + let mut message = StringBuilder::new(&self.heap.tracker); + match &reason { + ParseFormatSpecReason::Malformed => { + message.push_str("Invalid format specifier '")?; + message.push_str(spec)?; + message.push('\'')?; + } + ParseFormatSpecReason::NumberOverflow => { + message.push_str("Invalid format specifier '")?; + message.push_str(spec)?; + message.push_str("': width or precision overflows usize")?; + } + ParseFormatSpecReason::MissingPrecision => { + message.push_str("Format specifier missing precision")?; + } + ParseFormatSpecReason::UnknownFormatCode(code) => { + message.push_str("Unknown format code '")?; + message.push(*code)?; + message.push('\'')?; + } + ParseFormatSpecReason::GroupingConflict(detail) => message.push_str(detail)?, + } + if reason.needs_type_suffix() { + message.push_str(" for object of type '")?; + message.push_str(value_type)?; + message.push('\'')?; + } + let message = message.finish_raw()?; + Err(SimpleException::new_msg(ExcType::ValueError, message).into()) + } +} + +/// Resolves a `str` `Value` (as returned by `py_str`/`py_repr`) to an owned +/// `String`, dropping the value's heap reference on every path. Used by the +/// f-string conversion arms, which need the text in an owned buffer to feed +/// the mini-language formatter. +fn str_value_into_string(value: Value, vm: &mut VM<'_>) -> Result { + defer_drop!(value, vm); + Ok(value.to_str(vm)?.to_owned()) +} diff --git a/crates/bashkit-monty/src/bytecode/vm/mod.rs b/crates/bashkit-monty/src/bytecode/vm/mod.rs new file mode 100644 index 000000000..186ddf341 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/mod.rs @@ -0,0 +1,2911 @@ +//! Bytecode virtual machine for executing compiled Python code. +//! +//! The VM uses a stack-based execution model with an operand stack for computation +//! and a call stack for function frames. Each frame owns its instruction pointer (IP). + +mod async_exec; +mod attr; +mod binary; +mod call; +mod collections; +mod compare; +mod context_manager; +mod exceptions; +mod format; +mod namespace; +mod pattern; +mod recursion; +mod scheduler; + +use std::{borrow::Cow, mem}; + +pub(crate) use attr::PendingLookupEffect; +pub(crate) use call::CallResult; +pub(crate) use collections::unpack_exact; +use exceptions::CaughtException; +use monty_types::{InvalidInputError, MontyObject, MontyUuid, OsFunctionCall, PrintWriter, SourceRange}; +pub(crate) use namespace::{FrameNamespace, function_namespace}; +use recursion::frame_recursion_depth; +pub(crate) use recursion::{ContainsVM, RecursionToken, RunReentryGuard}; +use scheduler::Scheduler; + +use crate::{ + args::ArgValues, + asyncio::{CallId, TaskId}, + builtins::Builtins, + bytecode::{ + code::{Code, LocationEntry}, + op::{MATCH_KEYS_REST, Opcode, decode_assert_flags}, + }, + defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{ContainsHeap, DropWithContext, Heap, HeapData, HeapId, HeapReadOutput, HeapReader}, + heap_data::{CellValue, Closure, FunctionDefaults}, + intern::{FunctionId, Interns, StaticStrings, StringId}, + modules::{ + StandardLib, + json::{JsonStringCache, apply_json_load}, + random::apply_seed_random, + re::RePatternCache, + time::apply_clock_reading, + }, + name_map::NameMap, + object_bridge::MontyObjectExt, + os_dispatch::{ + PendingEffect, PostConversionEffect, PreConversionEffect, Reshaped, release_pending_effect, resolve_call_paths, + urandom_reply_error, + }, + parse::CodeRange, + run::{Program, SessionTables, VmEnv}, + types::{ + Dict, PyTrait, SessionRandom, + file::{apply_buffer_load, apply_buffer_store, apply_file_next, apply_open_name, apply_write_position}, + random::SEED_BYTES, + str::allocate_string, + }, + value::{EitherStr, Value}, +}; + +/// Result of executing Await opcode. +/// +/// Indicates what the VM should do after awaiting a value: +/// - `ValueReady`: the awaited value resolved immediately, push it +/// - `FramePushed`: a new frame was pushed for coroutine execution +/// - `Yield`: all tasks blocked, yield to caller with pending futures +enum AwaitResult { + /// The awaited value resolved immediately (e.g., resolved ExternalFuture). + ValueReady(Value), + /// A new frame was pushed to execute a coroutine. + FramePushed, + /// All tasks are blocked - yield to caller with pending futures. + Yield(Vec), +} + +/// Yields when an unhandled task exception leaves `cleanup_current_task`'s +/// parked frame with no successor. Dispatch must not execute that frame. +/// [`VM::pending_futures_exit`] returns surviving tasks' pending calls. +macro_rules! yield_if_parked { + ($self:expr) => { + if $self.current_frame.is_parked { + return $self.pending_futures_exit(); + } + }; +} + +/// Tries an operation and routes a Python exception through the active frames. +macro_rules! try_catch { + ($self:expr, $expr:expr) => { + if let Err(e) = $expr { + if let Some(result) = $self.handle_exception(e) { + return Err(result); + } + yield_if_parked!($self); + } + }; +} + +/// Routes a Python exception through the active frames. +/// +/// Wrapped in a block to allow use in match arm expressions. +macro_rules! catch { + ($self:expr, $err:expr) => {{ + if let Some(result) = $self.handle_exception($err) { + return Err(result); + } + yield_if_parked!($self); + }}; +} + +/// Applies a relative jump offset to the current frame IP. +/// +/// Uses checked arithmetic to safely compute the new IP, panicking if the +/// jump would result in a negative or overflowing instruction pointer. +macro_rules! jump_relative { + ($ip:expr, $offset:expr) => {{ + $ip = $ip + .checked_add_signed($offset.into()) + .expect("jump resulted in negative or overflowing IP"); + }}; +} + +/// Handles the result of a load operation that may yield a `FrameExit::NameLookup`. +/// +/// `load_local` and `load_global` return `Result, RunError>`: +/// - `Ok(None)`: load succeeded, value is on the stack +/// - `Ok(Some(FrameExit::NameLookup { .. }))`: unresolved name, yield to host +/// - `Err(e)`: exception (e.g., UnboundLocalError) +macro_rules! handle_load_result { + ($self:expr, $result:expr) => { + match $result { + Ok(None) => {} + Ok(Some(frame_exit)) => return Ok(frame_exit), + Err(e) => catch!($self, e), + } + }; +} + +/// Handles the result of a call operation that returns `CallResult`. +/// +/// Used by LoadAttr, the call opcodes, `MatchAttr` and the context-manager +/// opcodes. `Value` and `FramePushed` are handled inline; every suspending or +/// awaiting variant goes through the outlined [`VM::suspend_call_result`], so +/// each expansion adds little to the dispatch loop's stack frame — native +/// recursion (`__repr__` calling `repr`) re-enters that loop once per level. +macro_rules! handle_call_result { + ($self:expr, $result:expr) => { + match $result { + Ok(CallResult::Value(result)) => $self.push(result), + Ok(CallResult::FramePushed) => {} + Ok(other) => match $self.suspend_call_result(other) { + Ok(None) => {} + Ok(Some(exit)) => return Ok(exit), + Err(err) => catch!($self, err), + }, + Err(err) => catch!($self, err), + } + }; +} + +/// Result of VM execution. +pub enum FrameExit { + /// Execution completed successfully with a return value. + Return(Value), + + /// Execution paused for an external function call. + /// + /// The caller should execute the external function and call `resume()` + /// with the result. The `call_id` allows the host to use async resolution + /// by calling `run_pending()` instead of `run(result)`. + ExternalCall { + /// Name of the external function to call (interned or heap-owned). + function_name: EitherStr, + /// Arguments for the external function (includes both positional and keyword args). + args: ArgValues, + /// Unique ID for this call, used for async correlation. + call_id: CallId, + /// Optional bytecode IP of the load instruction that produced this `ExtFunction`. + /// + /// When a `LoadGlobalCallable` opcode auto-injects an `ExtFunction` + /// for an undefined name, the load instruction's IP is saved here. In standard execution + /// (without external function support), this IP is used to restore the frame pointer + /// before raising `NameError`, so the traceback points to the name rather than the call. + name_load_ip: Option, + }, + + /// Execution paused for an os function call. + /// + /// The caller should execute a function corresponding to the variant + /// carried in `function_call` and call `resume()` with the result. The + /// `call_id` allows the host to use async resolution by calling + /// `run_pending()` instead of `run(result)`. `function_call` carries the + /// typed args directly — no separate `args: ArgValues` field is needed. + OsCall { + /// Typed dispatch value carrying the OS function variant and its args. + function_call: OsFunctionCall, + /// Unique ID for this call, used for async correlation. + call_id: CallId, + /// Post-processing for this call's result, armed on + /// [`VM::pending_effect`] only once the call reaches the host + /// (`convert_frame_exit`); dropping the exit releases it instead. + effect: Option, + }, + + /// Execution paused for a host-routed call: a method call on a host + /// class instance, or on a host class type (a classmethod, or + /// construction — spelled `__call__`). + /// + /// The caller should invoke the method on the original host object + /// (routed by the `object_id` uuid) and call `resume()` with the + /// result. The receiver is NOT included in `args`. + MethodCall { + /// Method name (e.g. "distance", or "__call__" for construction). + method_name: EitherStr, + /// Arguments for the call (the receiver is not among them). + args: ArgValues, + /// Unique ID for this call, used for async correlation. + call_id: CallId, + /// Uuid of the routed receiver (instance or class type). + object_id: MontyUuid, + }, + + /// Execution paused for a lazy attribute lookup on a host-backed object + /// (a class instance, or a class type when `type_object` is true). + /// + /// Produced by `obj.attr` / `Type.attr` (and `getattr()` / `hasattr()`) + /// when `attr` is public and missing from the eager attrs. Resumed by + /// value like `NameLookup` (no call_id); an "undefined" answer raises + /// `AttributeError` naming `class_name` unless `effect` says otherwise. + AttrLookup { + /// The attribute name being looked up. + name: EitherStr, + /// Class name for the AttributeError message. + class_name: String, + /// Uuid of the object whose attribute is read. + object_id: MontyUuid, + /// True for a lookup on a class type object — selects CPython's + /// `type object '...' has no attribute ...` message on failure. + type_object: bool, + /// How `getattr()` / `hasattr()` consume the answer; `None` for + /// `obj.attr`. The only heap reference this exit can carry. + effect: Option, + }, + + /// All tasks are blocked waiting for external futures to resolve. + /// + /// The caller must resolve the pending CallIds before calling `resume()`. + /// This happens when await is called on an ExternalFuture that hasn't + /// been resolved yet, and there are no other ready tasks to switch to. + ResolveFutures(Vec), + + /// Execution paused for an unresolved name lookup. + /// + /// When the VM encounters an `Undefined` value in a global slot, it yields + /// to the host to resolve the name. + /// The host can return a value to cache in the slot, or indicate the name is + /// truly undefined (which will raise `NameError`). + /// + /// This enables auto-detection of external functions without requiring upfront + /// declaration: unresolved names are lazily resolved by the host at runtime. + NameLookup { + /// The interned name being looked up. + name_id: StringId, + /// The namespace slot where the resolved value should be cached. + namespace_slot: u16, + /// Whether this is a global slot (true) or a local/function slot (false). + is_global: bool, + }, +} + +impl DropWithContext for FrameExit { + fn drop_with(self, heap: &mut C) { + match self { + Self::Return(value) => value.drop_with(heap), + Self::ExternalCall { args, .. } | Self::MethodCall { args, .. } => { + args.drop_with(heap); + } + Self::OsCall { + function_call, effect, .. + } => { + function_call.drop_with(heap); + // Never reached the host, so no `resume` will consume it. + release_pending_effect(effect, heap); + } + Self::AttrLookup { effect, .. } => effect.drop_with(heap), + Self::ResolveFutures(_) | Self::NameLookup { .. } => {} + } + } +} + +/// A single function activation record. +/// +/// Each frame represents one level in the call stack and owns its own +/// instruction pointer. This design avoids sync bugs on call/return. +#[derive(Debug)] +pub struct CallFrame<'code> { + /// Compiled body, stable even when runtime compilation publishes more functions. + code: &'code Code, + + /// Hoisted instruction slice, avoiding a `Code` dereference on every fetch. + bytecode: &'code [u8], + + /// Instruction pointer within this frame's bytecode. + ip: usize, + + /// Base index into the VM stack for this frame's locals region. + /// + /// The frame's locals occupy `stack[stack_base..stack_base + locals_count]`, + /// and operands are pushed above that. `u32` keeps the frame small; the + /// stack can never hold that many values. + stack_base: u32, + + /// Number of local variable slots in this frame. + /// + /// Zero for module-level frames (globals are stored separately). + /// For function frames, this equals `func.namespace_size`. + locals_count: u16, + + /// Base of this frame's entries in the VM-wide `exception_stack`. + /// Recorded region depths are relative to this index, keeping caller + /// exceptions intact when abandoned handlers are unwound. + exception_stack_base: u32, + + /// Function ID (for tracebacks). None for module-level code. + function_id: Option, + + /// Caller's bytecode offset at the call site (for tracebacks). Stored raw + /// and resolved to a `CodeRange` lazily on unwind (see `resolve_offset`) to + /// skip the location-table scan unless the call raises. `None` at the root. + call_offset: Option, + + /// When this frame returns (or exits with an exception) the VM should exit the run loop + /// and return to the caller. Supports `evaluate_function`. + should_return: bool, + + /// Whether this is a non-executing frame parked between active tasks. + is_parked: bool, + + /// Where names that are not stack slots resolve; `None` for every + /// ordinary frame. Owns its dict references: released by + /// `cleanup_frame_state`, or taken by `serialize` for a snapshot. + namespace: Option>, + + /// Whether this frame is a class `__init__` running for `Foo(...)`. + /// + /// When `true`, the `ReturnValue` handler discards the frame's return value + /// (`__init__` returns `None`) and leaves the instance — pushed onto the + /// caller's operand stack before this frame was created — as the result of the + /// construction. Threaded through serialization (`SerializedFrame`) so a + /// suspended initializer resumes correctly. + is_initializer: bool, + + /// Module name for `LoadAttrImport` errors, set by `LoadModule`/`LoadSubmodule`. + /// Keeping it on the frame avoids another opcode operand; the compiler emits + /// no intervening instructions that change it. + import_from_module: Option, +} + +/// Narrows a VM stack index to the frame's `u32` field. +/// Panics instead of truncating an index beyond the frame representation. +#[inline] +pub(super) fn stack_index(index: usize) -> u32 { + u32::try_from(index).expect("VM stack index exceeds u32") +} + +/// The code a saved frame runs: its function's, or `module_code` for the +/// module-level frame, which has no function ID. +pub(super) fn frame_code<'code>( + interns: &'code Interns, + module_code: &'code Code, + function_id: Option, +) -> &'code Code { + function_id.map_or(module_code, |id| &interns.get_function(id).code) +} + +impl<'code> CallFrame<'code> { + /// Creates a new call frame for module-level code. + /// + /// Module frames have `locals_count = 0` because module-level variables + /// are stored in the VM's `globals` vec, not in the stack. + pub fn new_module(code: &'code Code, exception_stack_base: usize) -> Self { + Self { + code, + bytecode: code.bytecode(), + ip: 0, + stack_base: 0, + locals_count: 0, + exception_stack_base: stack_index(exception_stack_base), + function_id: None, + call_offset: None, + should_return: false, + is_parked: false, + namespace: None, + is_initializer: false, + import_from_module: None, + } + } + + /// Creates a non-executing frame for a VM with no active Python task. + fn new_parked(code: &'code Code) -> Self { + let mut frame = Self::new_module(code, 0); + frame.is_parked = true; + frame + } + + /// Parks this finished frame between tasks; its namespace must already be released. + fn park(&mut self, module_code: &'code Code) { + self.code = module_code; + self.bytecode = module_code.bytecode(); + self.ip = 0; + self.stack_base = 0; + self.locals_count = 0; + self.exception_stack_base = 0; + self.function_id = None; + self.call_offset = None; + self.should_return = false; + self.is_parked = true; + self.is_initializer = false; + debug_assert!(self.namespace.is_none(), "parked frame still owns a namespace"); + } + + /// Creates a new call frame for a function call. + /// + /// The frame's layout on the VM stack is + /// `[locals (locals_count) | operand stack ...]`. `stack_base` points at + /// the start of the locals region; comprehension variables are pushed + /// onto the operand stack at each comprehension's entry and popped at + /// its exit, so they share the same address space as ordinary operand + /// values (no separate per-frame region). + pub fn new_function( + code: &'code Code, + stack_base: usize, + locals_count: u16, + exception_stack_base: usize, + function_id: FunctionId, + call_offset: Option, + namespace: Option>, + ) -> Self { + Self { + code, + bytecode: code.bytecode(), + ip: 0, + stack_base: stack_index(stack_base), + locals_count, + exception_stack_base: stack_index(exception_stack_base), + function_id: Some(function_id), + call_offset, + should_return: false, + is_parked: false, + namespace, + is_initializer: false, + import_from_module: None, + } + } +} + +impl CallFrame<'_> { + /// Fetches `N` operand bytes with a single bounds check and advances the frame IP. + #[inline] + fn fetch_array(&mut self) -> [u8; N] { + let Some(bytes) = self.bytecode.get(self.ip..).and_then(<[u8]>::first_chunk::) else { + unreachable!("instruction IP is out of bounds of the bytecode") + }; + self.ip += N; + *bytes + } + + /// Fetches a `u8` operand at the current IP. + #[inline] + fn fetch_u8(&mut self) -> u8 { + self.fetch_array::<1>()[0] + } + + /// Fetches an `i8` operand at the current IP. + #[inline] + fn fetch_i8(&mut self) -> i8 { + self.fetch_u8().cast_signed() + } + + /// Fetches a little-endian `u16` operand at the current IP. + #[inline] + fn fetch_u16(&mut self) -> u16 { + u16::from_le_bytes(self.fetch_array()) + } + + /// Fetches a little-endian `i16` operand at the current IP. + #[inline] + fn fetch_i16(&mut self) -> i16 { + self.fetch_u16().cast_signed() + } + + /// Fetches two consecutive `u8` operands in a single bounds check. + /// + /// Mirrors `CodeBuilder::emit_u8_u8` on the encode side. + #[inline] + fn fetch_u8_u8(&mut self) -> (u8, u8) { + let [a, b] = self.fetch_array(); + (a, b) + } + + /// Fetches a little-endian `u16` followed by a `u8`, in a single bounds check. + /// + /// Mirrors `CodeBuilder::emit_u16_u8` on the encode side. + #[inline] + fn fetch_u16_u8(&mut self) -> (u16, u8) { + let [a, b, c] = self.fetch_array(); + (u16::from_le_bytes([a, b]), c) + } + + /// Fetches two consecutive little-endian `u16`s, in a single bounds check. + /// + /// Mirrors the `Operand::U16U16` encoding (e.g. `LoadGlobalCallable`). + #[inline] + fn fetch_u16_u16(&mut self) -> (u16, u16) { + let [a, b, c, d] = self.fetch_array(); + (u16::from_le_bytes([a, b]), u16::from_le_bytes([c, d])) + } + + /// Fetches a little-endian `u16` followed by two `u8`s, in a single bounds check. + /// + /// Mirrors `CodeBuilder::emit_u16_u8_u8` on the encode side. + #[inline] + fn fetch_u16_u8_u8(&mut self) -> (u16, u8, u8) { + let [a, b, c, d] = self.fetch_array(); + (u16::from_le_bytes([a, b]), c, d) + } + + /// Fetches two little-endian `u16`s followed by a `u8`, in a single bounds check. + /// + /// Mirrors `CodeBuilder::emit_name_op` on the encode side. + #[inline] + fn fetch_u16_u16_u8(&mut self) -> (u16, u16, u8) { + let [slot_lo, slot_hi, name_lo, name_hi, flags] = self.fetch_array(); + ( + u16::from_le_bytes([slot_lo, slot_hi]), + u16::from_le_bytes([name_lo, name_hi]), + flags, + ) + } + + /// Start of this frame's locals region on the VM stack. + #[inline] + pub(super) fn stack_base(&self) -> usize { + self.stack_base as usize + } + + /// Start of this frame's entries in the VM-wide `exception_stack`. + #[inline] + pub(super) fn exception_stack_base(&self) -> usize { + self.exception_stack_base as usize + } +} + +/// Serializable representation of a call frame. +/// +/// Cannot store `&Code` (a reference) — instead stores `FunctionId` to look up +/// the pre-compiled Code object on resume. Module-level code uses `None`. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct SerializedFrame { + /// Which function's code this frame executes (None = module-level). + #[serde(rename = "F")] + function_id: Option, + + /// Instruction pointer within this frame's bytecode. + #[serde(rename = "P")] + ip: usize, + + /// Base index into the VM stack for this frame's locals region. + #[serde(rename = "S")] + stack_base: usize, + + /// Number of local variable slots (0 for module-level frames). + #[serde(rename = "L")] + locals_count: u16, + + /// Base index into the VM-wide `exception_stack` for this frame. + /// See `CallFrame.exception_stack_base`. + #[serde(rename = "E")] + exception_stack_base: usize, + + /// Caller's bytecode offset at the call site (for tracebacks). See + /// `CallFrame.call_offset`. + #[serde(rename = "C")] + call_offset: Option, + + /// Whether this frame is a class `__init__` (see `CallFrame.is_initializer`). + /// + /// Unlike `should_return`, an initializer frame can legitimately be live + /// across a suspend (an `__init__` that calls an external/OS function), so it + /// must round-trip — otherwise the resumed frame would push `__init__`'s + /// `None` instead of leaving the instance on the stack. + #[serde(rename = "I")] + is_initializer: bool, + + /// Frame namespace, with ownership of its dict references (see + /// `CallFrame.namespace`). + #[serde(rename = "N")] + namespace: Option>, + + /// The `from ... import` in progress, if the frame suspended inside one. + #[serde(default, rename = "M")] + import_from_module: Option, +} + +impl CallFrame<'_> { + /// Converts this frame to a serializable representation, moving the + /// namespace's owned references across so the live frame releases nothing. + fn serialize(&mut self) -> SerializedFrame { + assert!(!self.is_parked, "cannot serialize a parked frame"); + assert!( + !self.should_return, + "cannot serialize frame marked for return - not yet supported" + ); + SerializedFrame { + function_id: self.function_id, + ip: self.ip, + stack_base: self.stack_base(), + locals_count: self.locals_count, + exception_stack_base: self.exception_stack_base(), + call_offset: self.call_offset, + is_initializer: self.is_initializer, + namespace: mem::take(&mut self.namespace), + import_from_module: self.import_from_module, + } + } +} + +/// VM state for pause/resume at external function calls. +/// +/// **Ownership:** This struct OWNS the values (refcounts were already incremented). +/// Must be used with the serialized Heap - HeapId values are indices into that heap. +/// +/// **Usage:** When the VM pauses for an external call, call `into_snapshot()` to +/// create this snapshot. The snapshot can be serialized and stored. On resume, +/// use `restore()` to reconstruct the VM and continue execution. +/// +/// Note: This struct does not implement `Clone` because `Value` uses manual +/// reference counting. Snapshots transfer ownership - they are not copied. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct VMSnapshot { + /// Operand stack — locals and operands interleaved per frame. + /// + /// Each function frame's locals occupy `stack[frame.stack_base..frame.stack_base + frame.locals_count]`, + /// with operands pushed above. + pub(crate) stack: Vec, + + /// Module-level (global) variable storage. + pub(crate) globals: Vec, + + /// Call frames (serializable form — stores FunctionId, not &Code). + frames: Vec, + + /// Stack of exceptions being handled for nested except blocks. + /// + /// When entering an except handler, the exception is pushed onto this stack. + /// When exiting via `ClearException`, the top is popped. This allows nested + /// except handlers to restore the outer exception context. + exception_stack: Vec, + + /// IP of the instruction that caused the pause (for exception handling). + instruction_ip: usize, + + /// Scheduler state (always present). + /// + /// Contains call ID counter, task state, pending calls, and resolved futures. + scheduler: Scheduler, + + /// In-flight resume effect for the paused OS call, if any. See + /// [`VM::pending_effect`]. + pending_effect: Option, + /// In-flight resume effect for the paused lazy attribute lookup, if any. + /// See [`VM::pending_lookup_effect`]. + pending_lookup_effect: Option, + + /// Working directory at the pause, including any `os.chdir` so far. + cwd: String, + /// The session's `random` state at the pause. + random: SessionRandom, +} + +impl VMSnapshot { + /// Discards the in-flight execution state of a snapshot that will never be + /// restored, releasing every heap reference it holds (operand and exception + /// stacks, scheduler tasks, pending resume effects), and returns the + /// globals, working directory and `random` generator so an abandoned REPL + /// snippet keeps its namespace, any `os.chdir` it made and any seed it + /// set. Mirrors `VM::drop`. + pub(crate) fn abandon(self, heap: &mut Heap) -> (Vec, String, SessionRandom) { + let Self { + stack, + globals, + frames, + exception_stack, + mut scheduler, + pending_effect, + pending_lookup_effect, + cwd, + random, + .. + } = self; + HeapReader::with(heap, &mut (), |heap, ()| { + release_pending_effect(pending_effect, heap); + pending_lookup_effect.drop_with(heap); + exception_stack.drop_with(heap); + stack.drop_with(heap); + for frame in frames { + frame.namespace.drop_with(heap); + } + scheduler.cleanup(heap); + }); + (globals, cwd, random) + } + + /// Number of tasks the scheduler held when this snapshot was taken. + /// + /// Test-only bridge for [`crate::ResolveFutures::__live_task_count_for_tests`]; + /// `scheduler` is private to this module. + #[cfg(feature = "test-hooks")] + pub(crate) fn live_task_count(&self) -> usize { + self.scheduler.task_count() + } +} + +// ============================================================================ +// Virtual Machine +// ============================================================================ + +/// The bytecode virtual machine. +/// +/// Executes compiled bytecode using a stack-based execution model. +/// The instruction pointer (IP) lives in each `CallFrame`, not here, +/// to avoid sync bugs on call/return. +pub struct VM<'h> { + /// Operand stack — locals and operands interleaved per frame. + /// + /// Each function frame's locals occupy `stack[frame.stack_base..frame.stack_base + frame.locals_count]`, + /// with operands pushed above. Module-level frames have `locals_count = 0` + /// because globals are stored separately. + pub(crate) stack: Vec, + + /// Module-level (global) variable storage. + /// + /// Indexed by slot number from `LoadGlobal`/`StoreGlobal` opcodes. + /// Separated from the stack because globals persist across function calls + /// and are accessed via dedicated opcodes. + pub(crate) globals: Vec, + + /// Frame currently executing, or a placeholder while no task is active. + current_frame: CallFrame<'h>, + + /// Caller frames suspended below `current_frame`. + suspended_frames: Vec>, + + /// Heap for reference-counted objects. + pub(crate) heap: &'h mut HeapReader<'h>, + + /// Stable committed entries, which remain borrowable across runtime compilation. + pub(crate) interns: &'h Interns, + + /// Module-level global names, slot by slot; extended alongside + /// [`globals`](Self::globals) when runtime-compiled code binds a new name. + pub(crate) global_names: &'h mut NameMap, + + /// Print output writer, borrowed so callers retain access to collected output. + pub(crate) print_writer: PrintWriter<'h>, + + /// Stack of exceptions being handled for nested except blocks. + /// + /// Used by bare `raise` to re-raise the current exception. + /// When entering an except handler, the exception is pushed onto this stack. + /// When exiting via `ClearException`, the top is popped. This allows nested + /// except handlers to restore the outer exception context. + exception_stack: Vec, + + /// IP of the instruction being executed (for exception table lookup). + /// + /// Updated at the start of each instruction before operands are fetched. + /// This allows us to find the correct exception handler when an error occurs. + instruction_ip: usize, + + /// Scheduler for task management and call ID allocation. + /// + /// Always present — owns `next_call_id` (used by both sync and async paths) + /// plus async task state. Internal collections don't allocate until first use, + /// so sync-only code pays only for the main task entry. + scheduler: Scheduler, + + /// Module-level code (for restoring main task frames). + /// + /// Stored here because the main task's frames have `function_id: None` and + /// need a reference to the module code when being restored after task switching. + module_code: &'h Code, + + /// Bytecode IP of the most recent `LoadGlobalCallable` that + /// pushed an `ExtFunction` for an undefined name. + /// + /// Used to restore the frame IP when standard execution converts an `ExternalCall` + /// back to a `NameError`, so the traceback points to the name reference rather than + /// the call expression. + ext_function_load_ip: Option, + + /// Per-run string cache for `json.loads()`. + /// + /// Deduplicates heap allocations for repeated strings (especially dict keys) + /// across multiple `json.loads()` calls within a single execution. Lazily + /// initialized on first use, cleaned up when the VM is dropped. + pub(crate) json_string_cache: JsonStringCache, + + /// File state update to apply when the next OS-call result resumes. + /// + /// `Some(effect)` between the yield to the host and the matching + /// `resume()`; `None` otherwise. Cleared on resume after applying the + /// file state effect, or on exception cleanup before the host-raised + /// error is rethrown into Monty code. + /// + /// At most one OS call can be in flight at a time for a given task — the + /// VM is single-threaded and OS calls are strictly request/response — so a + /// single `Option` is sufficient even with async tasks (which interleave + /// between OS calls, not within one). + pub(crate) pending_effect: Option, + + /// How the paused lazy attribute lookup's answer is consumed on `resume` + /// (`hasattr()` / `getattr()` default), armed like + /// [`pending_effect`](Self::pending_effect) once the lookup reaches + /// the host; `None` for `obj.attr` and when nothing is in flight. + pub(crate) pending_lookup_effect: Option, + + /// Current recursion depth — charged by non-frozen call frames and by nested + /// data-structure traversals (`repr`/`eq`/`cmp`/`hash`, json, ...). + /// + /// See [`recursion`](self::recursion) for the guard/token primitives that + /// maintain it. Not serialized: it is reconstructed from the active frame + /// count, excluding root and frozen frames, on `restore` and async switches. + recursion_depth: usize, + + /// Reusable scratch buffer for building a sync call's locals, avoiding a + /// `malloc`/`free` per call. Only held transiently within + /// `call_sync_function`, so one shared buffer is safe under recursion. + namespace_scratch: Vec, + /// Remaining native stack budget for `evaluate_function`, partials and callable-instance dispatch. + /// Not serialized: nested runs cannot suspend, and callable wrappers release their + /// charge before returning a suspending `CallResult`. Checked by [`Self::snapshot`]. + run_reentry_depth: u8, + + /// Per-run cache of compiled patterns for module-level `re.*` calls. Not + /// snapshotted (a pure performance cache), so default-initialized on restore. + pub(crate) re_pattern_cache: RePatternCache, + + /// Module generator and state for initializing unseeded generators. + /// Preserved across snapshots and REPL feeds, including `random.seed()` changes. + pub(crate) random: SessionRandom, + + /// Working directory, `__file__` inputs and the assert-repr cap for this + /// run. Rebuilt from the executor on restore, except the working + /// directory, which travels in the snapshot because `os.chdir` may have + /// moved it. + pub(crate) env: VmEnv<'h>, +} + +impl<'h> VM<'h> { + /// Creates a new VM ready to run `program`'s module code. + /// + /// The global-name map is borrowed mutably; committed intern entries and + /// `program` remain shared while runtime compilation appends new entries. + pub fn new( + globals: Vec, + tables: &'h mut SessionTables, + program: &'h Program, + heap: &'h mut HeapReader<'h>, + print_writer: PrintWriter<'h>, + ) -> Self { + let SessionTables { global_names, interns } = tables; + Self { + stack: Vec::with_capacity(64), + globals, + current_frame: CallFrame::new_module(&program.module_code, 0), + suspended_frames: Vec::with_capacity(16), + heap, + interns, + global_names, + print_writer, + exception_stack: Vec::new(), + instruction_ip: 0, + scheduler: Scheduler::new(), + ext_function_load_ip: None, // Set by LoadGlobalCallable + module_code: &program.module_code, + json_string_cache: JsonStringCache::default(), + pending_effect: None, + pending_lookup_effect: None, + recursion_depth: 0, + namespace_scratch: Vec::new(), + run_reentry_depth: recursion::MAX_RUN_REENTRY_DEPTH, + re_pattern_cache: RePatternCache::default(), + random: SessionRandom::default(), + env: program.vm_env(), + } + } + + /// Reconstructs a VM from a snapshot. + /// + /// The heap must already be deserialized. `FunctionId` values in frames + /// are used to look up pre-compiled `Code` objects from the intern table; + /// `program.module_code` serves frames with `function_id = None`. The + /// snapshot's working directory overrides the program's. + pub fn restore( + snapshot: VMSnapshot, + tables: &'h mut SessionTables, + program: &'h Program, + heap: &'h mut HeapReader<'h>, + print_writer: PrintWriter<'h>, + ) -> Self { + let SessionTables { global_names, interns } = tables; + // Reconstruct call frames from serialized form + let frames: Vec> = snapshot + .frames + .into_iter() + .map(|sf| { + let code = frame_code(interns, &program.module_code, sf.function_id); + CallFrame { + code, + bytecode: code.bytecode(), + ip: sf.ip, + stack_base: stack_index(sf.stack_base), + locals_count: sf.locals_count, + exception_stack_base: stack_index(sf.exception_stack_base), + function_id: sf.function_id, + call_offset: sf.call_offset, + should_return: false, + is_parked: false, + namespace: sf.namespace, + is_initializer: sf.is_initializer, + import_from_module: sf.import_from_module, + } + }) + .collect(); + + let current_frame_depth = frame_recursion_depth(frames.iter().map(|f| f.function_id), interns); + let mut frames = frames; + let current_frame = frames + .pop() + .unwrap_or_else(|| CallFrame::new_parked(&program.module_code)); + + Self { + stack: snapshot.stack, + globals: snapshot.globals, + current_frame, + suspended_frames: frames, + heap, + interns, + global_names, + print_writer, + exception_stack: snapshot.exception_stack, + instruction_ip: snapshot.instruction_ip, + scheduler: snapshot.scheduler, + module_code: &program.module_code, + ext_function_load_ip: None, + json_string_cache: JsonStringCache::default(), + pending_effect: snapshot.pending_effect, + pending_lookup_effect: snapshot.pending_lookup_effect, + recursion_depth: current_frame_depth, + namespace_scratch: Vec::new(), + // Always default value at a restore boundary — see the `run_reentry_depth` field doc. + run_reentry_depth: recursion::MAX_RUN_REENTRY_DEPTH, + re_pattern_cache: RePatternCache::default(), + random: snapshot.random, + env: { + let mut env = program.vm_env(); + env.cwd = Cow::Owned(snapshot.cwd); + env + }, + } + } + + /// Consumes the VM and creates a snapshot for pause/resume. + /// + /// **Ownership transfer:** This method takes `self` by value, consuming the VM. + /// The snapshot owns all Values (refcounts already correct from the live VM). + /// The heap and namespaces must be serialized alongside this snapshot. + /// + /// This is NOT a clone - it's a transfer. After calling this, the original VM + /// is gone and only the snapshot (+ serialized heap/namespaces) represents the state. + pub fn snapshot(mut self) -> VMSnapshot { + // Always fully released (== MAX) here — see the field doc. Asserted to + // catch a future `run()` call site that can suspend mid-re-entry. + debug_assert_eq!( + self.run_reentry_depth, + recursion::MAX_RUN_REENTRY_DEPTH, + "VM snapshotted while inside a nested native re-entry" + ); + debug_assert!( + !self.current_frame.is_parked || self.suspended_frames.is_empty(), + "parked frame has suspended callers" + ); + + // Drop cached JSON strings before consuming the VM — they are not + // included in the snapshot and their refcounts must be decremented. + self.json_string_cache.drop_all(self.heap); + + VMSnapshot { + // Move values directly — no clone, no refcount increment needed + // (the VM owned them, now the snapshot owns them) + stack: mem::take(&mut self.stack), + globals: mem::take(&mut self.globals), + frames: if self.current_frame.is_parked { + Vec::new() + } else { + self.suspended_frames + .iter_mut() + .chain([&mut self.current_frame]) + .map(CallFrame::serialize) + .collect() + }, + exception_stack: mem::take(&mut self.exception_stack), + instruction_ip: self.instruction_ip, + scheduler: mem::take(&mut self.scheduler), + pending_effect: self.pending_effect.take(), + pending_lookup_effect: self.pending_lookup_effect.take(), + // Reset to the starting directory rather than `take` (an empty + // string), so a later `take_changed_cwd` on this VM stays honest. + cwd: mem::replace(&mut self.env.cwd, Cow::Borrowed(self.env.initial_cwd)).into_owned(), + random: mem::take(&mut self.random), + } + } + + /// Returns the `stack_base` of the current (topmost) call frame. + /// + /// Used by `NameLookup` resolution to determine which stack region to cache + /// resolved values into when the lookup originated from a function scope. + pub fn current_stack_base(&self) -> usize { + self.current_frame.stack_base() + } + + /// Takes ownership of the globals vector, replacing it with an empty vec. + /// + /// Used by the REPL to reclaim globals after VM execution completes. + /// Must be called before the VM is dropped, since `Drop` will clean up + /// any remaining globals with `drop_with`. + pub fn take_globals(&mut self) -> Vec { + mem::take(&mut self.globals) + } + + /// Takes the working directory if this run owns one: after an `os.chdir`, + /// or always for a restored VM (its snapshot carried the directory). The + /// REPL writes it back so a directory change persists into later feeds. + pub fn take_changed_cwd(&mut self) -> Option { + match mem::replace(&mut self.env.cwd, Cow::Borrowed(self.env.initial_cwd)) { + Cow::Owned(cwd) => Some(cwd), + Cow::Borrowed(_) => None, + } + } + + /// Joins paths to cwd and rejects NUL bytes before yielding an OS call. + /// Rejected calls release their pending effect; existence predicates finish locally. + fn prepare_os_call( + &mut self, + mut call: OsFunctionCall, + effect: Option, + ) -> RunResult> { + resolve_call_paths(&mut call, &self.env.cwd); + if let Err(message) = call.check_path_null_bytes() { + release_pending_effect(effect, self.heap); + if call.is_existence_check() { + self.push(Value::Bool(false)); + Ok(None) + } else { + Err(ExcType::value_error(message)) + } + } else { + // The effect is armed only after this exit is accepted for dispatch. + Ok(Some(FrameExit::OsCall { + function_call: call, + call_id: self.allocate_call_id(), + effect, + })) + } + } + + /// Allocates a new `CallId` for an external function call. + fn allocate_call_id(&mut self) -> CallId { + self.scheduler.allocate_call_id() + } + + /// Returns true if we're on the main task (or no async at all). + /// + /// This is used to determine whether a `ReturnValue` at the last frame means + /// module-level completion (return to host) or spawned task completion + /// (handle task completion and switch). + fn is_main_task(&self) -> bool { + self.scheduler.current_task_id().is_none_or(TaskId::is_main) + } + + /// Runs the VM from a host boundary, bracketing the loop with the + /// tracker's execution-clock hooks so the time limits measure + /// *execution* time only — the clock stops whenever this returns + /// (completion, error, or suspension at an external call). + /// + /// Every host turn must enter the loop through exactly one + /// `run_external` call, and it must NEVER nest: VM-internal re-entry + /// (task switches, `evaluate_function`) uses the raw private [`Self::run`] + /// instead, whose time is already inside the enclosing window. + pub(crate) fn run_external(&mut self) -> Result { + self.heap.tracker.on_execution_start(); + let result = self.run(); + self.heap.tracker.on_execution_stop(); + self.finish_host_turn(result) + } + + /// Epilogue for every host-boundary execution window (here, and the + /// uncaught branch of `resume_with_exception`, which ends a turn without + /// entering the loop): re-checks both resource limits so an + /// overshoot that arose after the run loop's last amortized check — or + /// was swallowed by a truncating caller (repr's `...[timeout]`) — cannot + /// escape as a successful result. Consumes a discarded success so its + /// heap refcounts are released rather than leaked. + pub(crate) fn finish_host_turn>( + &mut self, + result: Result, + ) -> Result { + // A turn shorter than the dispatch-checkpoint interval never probes + // GC inside the run loop, so a stream of tiny feeds could otherwise + // accumulate eligible cyclic garbage indefinitely — and the memory + // check below could trip on memory a collection would reclaim. The + // collection is charged to the execution clock like dispatch-loop GC, + // so the limit check sees post-GC elapsed time as well as memory. + // Skipped after a resource error, where refcounts are unreliable and + // trial deletion could free live entries; ordinary Python exceptions + // unwind through the drop machinery, so they still collect. + if !matches!(result, Err(RunError::UncatchableExc(_))) && self.heap.should_gc() { + self.heap.tracker.on_execution_start(); + self.run_gc(); + self.heap.tracker.on_execution_stop(); + } + // Checked for erroring turns too: session state survives Python + // exceptions, so allocate-then-raise feeds must not evade the limits. + // The uncatchable resource error out-ranks the turn's own error. + match self.heap.tracker.check_memory_time() { + Ok(()) => result, + Err(e) => { + if let Ok(value) = result { + value.drop_with(self); + } + Err(e.into()) + } + } + } + + /// The rarely taken arms of [`handle_call_result!`]: turns a suspending + /// `CallResult` into the `FrameExit` that yields to the host, or awaits an + /// `AwaitValue`. `Ok(None)` means execution continues in the current frame. + #[inline(never)] + fn suspend_call_result(&mut self, result: CallResult) -> Result, RunError> { + let exit = match result { + CallResult::Value(value) => { + self.push(value); + return Ok(None); + } + CallResult::FramePushed => return Ok(None), + CallResult::External(name, args) => FrameExit::ExternalCall { + function_name: name, + args, + call_id: self.allocate_call_id(), + name_load_ip: self.ext_function_load_ip.take(), + }, + CallResult::OsCall(call) => return self.prepare_os_call(call, None), + CallResult::OsCallWithEffect { call, effect } => return self.prepare_os_call(call, Some(effect)), + CallResult::MethodCall { name, args, object_id } => FrameExit::MethodCall { + method_name: name, + args, + call_id: self.allocate_call_id(), + object_id, + }, + CallResult::AttrLookup { + name, + class_name, + object_id, + type_object, + effect, + } => FrameExit::AttrLookup { + name, + class_name, + object_id, + type_object, + effect, + }, + CallResult::AwaitValue(value) => { + // Push the value and implicitly await it (used by asyncio.run()) + self.push(value); + return match self.exec_get_awaitable()? { + AwaitResult::ValueReady(value) => { + self.push(value); + Ok(None) + } + AwaitResult::FramePushed => Ok(None), + AwaitResult::Yield(pending_calls) => Ok(Some(FrameExit::ResolveFutures(pending_calls))), + }; + } + }; + Ok(Some(exit)) + } + + /// Periodic dispatch-loop work, outlined (`#[inline(never)]`) so the hot + /// loop stays small: the amortized memory + time check — where a timeout + /// swallowed by a truncating caller re-detects (elapsed time is + /// monotonic), backstopped by the `run_external` exit check — the + /// GC-scheduling probe, and the print writer's flush poll. + #[inline(never)] + fn dispatch_checkpoint(&mut self, check_limits: bool, poll_print: bool) -> Result<(), RunError> { + if check_limits { + self.heap.tracker.check_memory_time()?; + } + if self.heap.should_gc() { + self.run_gc(); + } + // A buffering writer only flushes when written to, so code that prints + // and then computes in silence would hold that output until its next + // print. This is what bounds that wait. + if poll_print { + self.print_writer.poll_flush()?; + } + Ok(()) + } + + /// Main execution loop. + /// + /// Fetches opcodes from the current frame's bytecode and executes them. + /// Returns when execution completes, an error occurs, or an external + /// call is needed. + /// + /// Private: host boundaries go through [`Self::run_external`] (directly + /// or via `run_external`/`resume`/`resume_with_exception`/ + /// `resume_with_resolved_futures`) so the execution clock is accounted; + /// only VM-internal re-entry calls this raw loop. + /// + /// The current frame is stored separately from its suspended callers, so + /// dispatch updates its authoritative instruction pointer directly. + fn run(&mut self) -> Result { + /// How often (in instructions) the dispatch loop runs its periodic + /// work: the full `check_memory_time` and the GC-scheduling probe. + /// The checkpoint reads the clock when limits are armed, so this sets + /// the entire cost of limit enforcement — ~40% on tight loops at 10, + /// ~2% at u8::MAX (see the `_limits` benchmarks) — while detection + /// latency stays sub-µs. Native ops poll internally and the host-turn + /// epilogue re-checks, so only this dispatch cadence rides on it. + /// The countdown is per-`run()`, so `evaluate_function` re-entry + /// restarts it — a native loop calling a shorter callback reaches no + /// checkpoint at all and must poll the tracker itself. + const CHECK_INTERVAL: u8 = u8::MAX; + + // Limits cannot change mid-run (`set_max_feed_duration` needs `&mut` at the + // host boundary), so with none configured the whole checkpoint reduces + // to this one hoisted, well-predicted branch per instruction. + let check_limits = self.heap.tracker.has_memory_time_limit(); + // Likewise hoisted: only a `Callback` writer can buffer, so every other + // variant skips the poll — and the clock read behind it — entirely. + let poll_print = self.print_writer.wants_poll(); + + let mut countdown = CHECK_INTERVAL; + + loop { + // One decrement-and-branch per instruction; the periodic work + // runs every `CHECK_INTERVAL`-th, outlined to keep the hot loop + // small. GC triggering is allocation-count-based (intervals in + // the hundreds), so probing it a few instructions late is + // immaterial. + if let Some(c) = countdown.checked_sub(1) { + countdown = c; + } else { + countdown = CHECK_INTERVAL; + try_catch!(self, self.dispatch_checkpoint(check_limits, poll_print)); + } + + // Track instruction IP for exception table lookup + self.instruction_ip = self.current_frame.ip; + + // Fetch the opcode and advance the authoritative frame IP. + let opcode = { + let byte = self.current_frame.bytecode[self.current_frame.ip]; + self.current_frame.ip += 1; + Opcode::from_repr(byte).expect("invalid opcode in bytecode") + }; + + match opcode { + // ============================================================ + // Stack Operations + // ============================================================ + Opcode::Pop => { + let value = self.pop(); + value.drop_with(self); + } + Opcode::Dup => { + let value = self.peek().clone_with_heap(self); + self.push(value); + } + Opcode::Dup2 => { + let len = self.stack.len(); + let first = self.stack[len - 2].clone_with_heap(self); + let second = self.stack[len - 1].clone_with_heap(self); + self.push(first); + self.push(second); + } + Opcode::Rot2 => { + // Swap top two: [a, b] → [b, a] + let len = self.stack.len(); + self.stack.swap(len - 1, len - 2); + } + Opcode::Rot3 => { + // Rotate top three: [a, b, c] → [c, a, b] + // Uses in-place rotation without cloning + let len = self.stack.len(); + // Move c out, then shift a→b→c, then put c at a's position + // Equivalent to: [..rest, a, b, c] → [..rest, c, a, b] + self.stack[len - 3..].rotate_right(1); + } + // Constants & Literals + Opcode::LoadConst => { + let idx = self.current_frame.fetch_u16(); + let value = self.current_frame.code.constant(idx); + self.push(value.clone_with_heap(self)); + } + Opcode::LoadNone => self.push(Value::None), + Opcode::LoadTrue => self.push(Value::Bool(true)), + Opcode::LoadFalse => self.push(Value::Bool(false)), + Opcode::BuildCell => { + let cell_id = self.heap.allocate(HeapData::Cell(CellValue(Value::Undefined))); + self.push(Value::Ref(cell_id)); + } + Opcode::LoadSmallInt => { + let n = self.current_frame.fetch_i8(); + self.push(Value::Int(i64::from(n))); + } + // Variables - Specialized Local Loads (no operand) + Opcode::LoadLocal0 => try_catch!(self, self.load_local(0)), + Opcode::LoadLocal1 => try_catch!(self, self.load_local(1)), + Opcode::LoadLocal2 => try_catch!(self, self.load_local(2)), + Opcode::LoadLocal3 => try_catch!(self, self.load_local(3)), + // Variables - General Local Operations + Opcode::LoadLocal => { + let slot = u16::from(self.current_frame.fetch_u8()); + try_catch!(self, self.load_local(slot)); + } + Opcode::LoadLocalW => { + let slot = self.current_frame.fetch_u16(); + try_catch!(self, self.load_local(slot)); + } + Opcode::StoreLocal => { + let slot = u16::from(self.current_frame.fetch_u8()); + self.store_local(slot); + } + Opcode::StoreLocalW => { + let slot = self.current_frame.fetch_u16(); + self.store_local(slot); + } + Opcode::LiftToTop => { + let n = self.current_frame.fetch_u8(); + // Move the item at TOS - n to TOS, shifting items in + // between down by one. Single `rotate_left(1)` on the + // affected slice does exactly that. + let len = self.stack.len(); + let src_idx = len - 1 - n as usize; + self.stack[src_idx..].rotate_left(1); + } + Opcode::SinkTop => { + let n = usize::from(self.current_frame.fetch_u8()); + // Move TOS beneath the n items below it: one rotation of the + // affected slice, the mirror image of `LiftToTop`. + let len = self.stack.len(); + self.stack[len - 1 - n..].rotate_right(1); + } + Opcode::RaiseUnboundLocal => { + let name_idx = self.current_frame.fetch_u16(); + let name_id = StringId::from_index(name_idx); + catch!(self, self.unbound_local_error(0, Some(name_id))); + } + Opcode::DeleteLocal => { + let slot = u16::from(self.current_frame.fetch_u8()); + self.delete_local(slot); + } + Opcode::DeleteGlobal => { + let slot = self.current_frame.fetch_u16(); + try_catch!(self, self.delete_global(slot)); + } + // Variables - runtime name resolution (eval/exec snippets) + Opcode::LoadName => { + let (slot, name_idx, flags) = self.current_frame.fetch_u16_u16_u8(); + handle_load_result!(self, self.load_name(slot, StringId::from_index(name_idx), flags)); + } + Opcode::StoreName => { + let (slot, name_idx, flags) = self.current_frame.fetch_u16_u16_u8(); + try_catch!(self, self.store_name(slot, StringId::from_index(name_idx), flags)); + } + Opcode::DeleteName => { + let (slot, name_idx, flags) = self.current_frame.fetch_u16_u16_u8(); + try_catch!(self, self.delete_name(slot, StringId::from_index(name_idx), flags)); + } + // Variables - Global Operations + Opcode::LoadGlobal => { + let slot = self.current_frame.fetch_u16(); + handle_load_result!(self, self.load_global(slot)); + } + Opcode::LoadGlobalCallable => { + let (slot, name_idx) = self.current_frame.fetch_u16_u16(); + let name_id = StringId::from_index(name_idx); + self.load_global_callable(slot, name_id); + } + Opcode::StoreGlobal => { + let slot = self.current_frame.fetch_u16(); + self.store_global(slot); + } + // Variables - Cell Operations (closures) + Opcode::LoadCell => { + let slot = self.current_frame.fetch_u16(); + try_catch!(self, self.load_cell(slot)); + } + Opcode::StoreCell => { + let slot = self.current_frame.fetch_u16(); + self.store_cell(slot); + } + Opcode::DeleteCell => { + let slot = self.current_frame.fetch_u16(); + self.delete_cell(slot); + } + // Binary Operations - route through exception handling for tracebacks + Opcode::BinaryAdd => try_catch!(self, self.binary_add()), + Opcode::BinarySub => try_catch!(self, self.binary_sub()), + Opcode::BinaryMul => try_catch!(self, self.binary_mult()), + Opcode::BinaryDiv => try_catch!(self, self.binary_div()), + Opcode::BinaryFloorDiv => try_catch!(self, self.binary_floordiv()), + Opcode::BinaryMod => try_catch!(self, self.binary_mod()), + Opcode::BinaryPow => try_catch!(self, self.binary_pow()), + // Bitwise operations - only work on integers + Opcode::BinaryAnd => try_catch!(self, self.binary_and()), + Opcode::BinaryOr => try_catch!(self, self.binary_or()), + Opcode::BinaryXor => try_catch!(self, self.binary_xor()), + Opcode::BinaryLShift => { + try_catch!(self, self.binary_lshift()); + } + Opcode::BinaryRShift => { + try_catch!(self, self.binary_rshift()); + } + Opcode::BinaryMatMul => try_catch!(self, self.binary_matmul()), + // Comparison Operations + Opcode::CompareEq => try_catch!(self, self.compare_eq()), + Opcode::CompareNe => try_catch!(self, self.compare_ne()), + Opcode::CompareLt => try_catch!(self, self.compare_lt()), + Opcode::CompareLe => try_catch!(self, self.compare_le()), + Opcode::CompareGt => try_catch!(self, self.compare_gt()), + Opcode::CompareGe => try_catch!(self, self.compare_ge()), + Opcode::CompareIs => try_catch!(self, self.compare_is()), + Opcode::CompareIsNot => try_catch!(self, self.compare_is_not()), + Opcode::CompareIn => try_catch!(self, self.compare_in()), + Opcode::CompareNotIn => try_catch!(self, self.compare_not_in()), + // Unary Operations + Opcode::UnaryNot => { + let value = self.pop(); + let result = value.py_bool(self); + value.drop_with(self); + match result { + Ok(value) => self.push(Value::Bool(!value)), + Err(error) => catch!(self, error), + } + } + Opcode::UnaryNeg => try_catch!(self, self.unary_neg()), + Opcode::UnaryPos => try_catch!(self, self.unary_pos()), + Opcode::UnaryInvert => try_catch!(self, self.unary_invert()), + // In-place Operations - route through exception handling. + // `+=`/`-=`/`&=`/`|=` first try a true in-place `Counter` op + // (mutating the left operand); everything else — and the + // non-Counter fallback — reuses the binary implementation, since + // Monty's other types have no distinct in-place form. + Opcode::InplaceAdd => try_catch!(self, self.inplace_add()), + Opcode::InplaceSub => try_catch!(self, self.inplace_sub()), + Opcode::InplaceMul => try_catch!(self, self.binary_mult()), + Opcode::InplaceDiv => try_catch!(self, self.binary_div()), + Opcode::InplaceFloorDiv => try_catch!(self, self.binary_floordiv()), + Opcode::InplaceMod => try_catch!(self, self.binary_mod()), + Opcode::InplacePow => try_catch!(self, self.binary_pow()), + Opcode::InplaceAnd => { + try_catch!(self, self.inplace_and()); + } + Opcode::InplaceOr => try_catch!(self, self.inplace_or()), + Opcode::InplaceXor => { + try_catch!(self, self.binary_xor()); + } + Opcode::InplaceLShift => { + try_catch!(self, self.binary_lshift()); + } + Opcode::InplaceRShift => { + try_catch!(self, self.binary_rshift()); + } + // Collection Building - route through exception handling + Opcode::BuildList => { + let count = self.current_frame.fetch_u16() as usize; + self.build_list(count); + } + Opcode::BuildTuple => { + let count = self.current_frame.fetch_u16() as usize; + self.build_tuple(count); + } + Opcode::BuildDict => { + let count = self.current_frame.fetch_u16() as usize; + try_catch!(self, self.build_dict(count)); + } + Opcode::BuildSet => { + let count = self.current_frame.fetch_u16() as usize; + try_catch!(self, self.build_set(count)); + } + Opcode::FormatValue => { + let flags = self.current_frame.fetch_u8(); + try_catch!(self, self.format_value(flags)); + } + Opcode::BuildFString => { + let count = self.current_frame.fetch_u16() as usize; + try_catch!(self, self.build_fstring(count)); + } + Opcode::BuildSlice => { + try_catch!(self, self.build_slice()); + } + Opcode::ListExtend => { + try_catch!(self, self.list_extend()); + } + Opcode::ListToTuple => { + try_catch!(self, self.list_to_tuple()); + } + Opcode::DictMerge => { + let func_name_id = self.current_frame.fetch_u16(); + try_catch!(self, self.dict_merge(func_name_id)); + } + Opcode::MethodDictMerge => { + let func_name_id = self.current_frame.fetch_u16(); + try_catch!(self, self.method_dict_merge(func_name_id)); + } + // PEP 448 literal building + Opcode::DictUpdate => { + let depth = self.current_frame.fetch_u8() as usize; + try_catch!(self, self.dict_update(depth)); + } + Opcode::SetExtend => { + let depth = self.current_frame.fetch_u8() as usize; + try_catch!(self, self.set_extend(depth)); + } + // Comprehension Building - append/add/set items during iteration + Opcode::ListAppend => { + let depth = self.current_frame.fetch_u8() as usize; + try_catch!(self, self.list_append(depth)); + } + Opcode::SetAdd => { + let depth = self.current_frame.fetch_u8() as usize; + try_catch!(self, self.set_add(depth)); + } + Opcode::DictSetItem => { + let depth = self.current_frame.fetch_u8() as usize; + try_catch!(self, self.dict_set_item(depth)); + } + // Subscript & Attribute - route through exception handling + Opcode::BinarySubscr => { + let index = self.pop(); + let obj = self.pop(); + let result = obj.py_getitem(&index, self); + obj.drop_with(self); + index.drop_with(self); + match result { + Ok(v) => self.push(v), + Err(e) => catch!(self, e), + } + } + Opcode::StoreSubscr => { + // Stack order: value, obj, index (TOS) + let index = self.pop(); + let mut obj = self.pop(); + let value = self.pop(); + let result = obj.py_setitem(index, value, self); + obj.drop_with(self); + if let Err(e) = result { + catch!(self, e); + } + } + Opcode::LoadAttr => { + let name_idx = self.current_frame.fetch_u16(); + let name_id = StringId::from_index(name_idx); + handle_call_result!(self, self.load_attr(name_id)); + } + Opcode::LoadSubmodule => { + let (name_idx, path_idx) = self.current_frame.fetch_u16_u16(); + let path_id = StringId::from_index(path_idx); + // the module a following `LoadAttrImport` names in its `ImportError` + self.current_frame.import_from_module = Some(path_id); + handle_call_result!(self, self.load_submodule(StringId::from_index(name_idx), path_id)); + } + Opcode::LoadAttrImport => { + let name_idx = self.current_frame.fetch_u16(); + let name_id = StringId::from_index(name_idx); + // the compiler emits this only after the statement's `LoadModule` + let module_id = self + .current_frame + .import_from_module + .expect("LoadAttrImport runs after its LoadModule set the frame's module"); + handle_call_result!(self, self.load_attr_import(name_id, module_id)); + } + Opcode::StoreAttr => { + let name_idx = self.current_frame.fetch_u16(); + let name_id = StringId::from_index(name_idx); + try_catch!(self, self.store_attr(name_id)); + } + // Control Flow - use self.current_frame.ip directly for jumps + Opcode::Jump => { + let offset = self.current_frame.fetch_i16(); + jump_relative!(self.current_frame.ip, offset); + } + Opcode::JumpIfTrue => { + let offset = self.current_frame.fetch_i16(); + let cond = self.pop(); + let result = cond.py_bool(self); + cond.drop_with(self); + match result { + Ok(true) => jump_relative!(self.current_frame.ip, offset), + Ok(false) => {} + Err(error) => catch!(self, error), + } + } + Opcode::JumpIfFalse => { + let offset = self.current_frame.fetch_i16(); + let cond = self.pop(); + let result = cond.py_bool(self); + cond.drop_with(self); + match result { + Ok(false) => jump_relative!(self.current_frame.ip, offset), + Ok(true) => {} + Err(error) => catch!(self, error), + } + } + Opcode::JumpIfTrueOrPop => { + let offset = self.current_frame.fetch_i16(); + let value = self.pop(); + match value.py_bool(self) { + Ok(true) => { + self.push(value); + jump_relative!(self.current_frame.ip, offset); + } + Ok(false) => value.drop_with(self), + Err(error) => { + value.drop_with(self); + catch!(self, error); + } + } + } + Opcode::JumpIfFalseOrPop => { + let offset = self.current_frame.fetch_i16(); + let value = self.pop(); + match value.py_bool(self) { + Ok(true) => value.drop_with(self), + Ok(false) => { + self.push(value); + jump_relative!(self.current_frame.ip, offset); + } + Err(error) => { + value.drop_with(self); + catch!(self, error); + } + } + } + // Iteration - route through exception handling + Opcode::GetIter => { + let value = self.pop(); + let iterator = value.py_iter(self).and_then(|call| call.require_synchronous(self)); + value.drop_with(self); + match iterator { + Ok(iterator) => self.push(iterator), + Err(e) => catch!(self, e), + } + } + Opcode::ForIter => { + let offset = self.current_frame.fetch_i16(); + // Iterator implementations return heap objects from `py_iter`. + let Value::Ref(heap_id) = *self.peek() else { + return Err(RunError::internal("ForIter: expected iterator ref on stack")); + }; + let mut iter = self.heap.read(heap_id); + // A file nobody has read yet has no buffer to slice: load it from + // the host, then re-dispatch this instruction against the buffer. + if let HeapReadOutput::OpenFile(file) = &iter + && file.needs_buffer_load(self) + { + let effect = PostConversionEffect::BufferLoad { file_id: heap_id }; + let call = file.buffer_load_call(self, effect); + drop(iter); + self.current_frame.ip = self.instruction_ip; + handle_call_result!(self, Ok(call)); + continue; + } + + match iter.py_next(self) { + Ok(Some(value)) => self.push(value), + Ok(None) => { + // Drop the HeapRead before dec_ref to release the reader count + drop(iter); + // Iterator exhausted - pop it and jump to end + let iter = self.pop(); + iter.drop_with(self); + jump_relative!(self.current_frame.ip, offset); + } + Err(e) => { + // Drop the HeapRead before dec_ref to release the reader count + drop(iter); + // Error during iteration (e.g., dict size changed) + let iter = self.pop(); + iter.drop_with(self); + catch!(self, e); + } + } + } + // Function Calls + Opcode::CallFunction => { + let arg_count = self.current_frame.fetch_u8() as usize; + handle_call_result!(self, self.exec_call_function(arg_count)); + } + Opcode::CallBuiltinFunction => { + let (builtin_id, arg_count) = self.current_frame.fetch_u8_u8(); + let result = self.exec_call_builtin_function(builtin_id, arg_count as usize); + handle_call_result!(self, result); + } + Opcode::CallBuiltinType => { + let (type_id, arg_count) = self.current_frame.fetch_u8_u8(); + let arg_count = arg_count as usize; + + handle_call_result!(self, self.exec_call_builtin_type(type_id, arg_count)); + } + Opcode::CallFunctionKw => { + // Fetch operands: pos_count, kw_count, then kw_count name indices + let (pos_count, kw_count) = self.current_frame.fetch_u8_u8(); + let (pos_count, kw_count) = (pos_count as usize, kw_count as usize); + + handle_call_result!(self, self.exec_call_function_kw(pos_count, kw_count)); + } + Opcode::CallAttr => { + // CallAttr: u16 name_id, u8 arg_count + // Stack: [obj, arg1, arg2, ..., argN] -> [result] + let (name_idx, arg_count) = self.current_frame.fetch_u16_u8(); + let name_id = StringId::from_index(name_idx); + let arg_count = arg_count as usize; + + handle_call_result!(self, self.exec_call_attr(name_id, arg_count)); + } + Opcode::CallAttrKw => { + // CallAttrKw: u16 name_id, u8 pos_count, u8 kw_count, then kw_count u16 name indices + // Stack: [obj, pos_args..., kw_values...] -> [result] + let (name_idx, pos_count, kw_count) = self.current_frame.fetch_u16_u8_u8(); + let name_id = StringId::from_index(name_idx); + let (pos_count, kw_count) = (pos_count as usize, kw_count as usize); + + handle_call_result!(self, self.exec_call_attr_kw(name_id, pos_count, kw_count)); + } + Opcode::CallFunctionExtended => { + let flags = self.current_frame.fetch_u8(); + let has_kwargs = (flags & 0x01) != 0; + + handle_call_result!(self, self.exec_call_function_extended(has_kwargs)); + } + Opcode::CallAttrExtended => { + let (name_idx, flags) = self.current_frame.fetch_u16_u8(); + let name_id = StringId::from_index(name_idx); + let has_kwargs = (flags & 0x01) != 0; + + handle_call_result!(self, self.exec_call_attr_extended(name_id, has_kwargs)); + } + // Function Definition + Opcode::MakeFunction => { + let (func_idx, defaults_count) = self.current_frame.fetch_u16_u8(); + let func_id = FunctionId::from_index(func_idx); + let defaults_count = defaults_count as usize; + + // A function defined under an explicit globals dict carries it. + let globals = self + .current_frame + .namespace + .as_deref() + .and_then(FrameNamespace::dict_globals); + if defaults_count == 0 && globals.is_none() { + // No defaults - use inline Value::Function (no heap allocation) + self.push(Value::DefFunction(func_id)); + } else { + // Pop default values from stack (drain maintains order: first pushed = first in vec) + let defaults = self.pop_n(defaults_count); + if let Some(globals) = globals { + self.heap.inc_ref(globals); + } + + // Create FunctionDefaults on heap and push reference + let heap_id = self.heap.allocate(HeapData::FunctionDefaults(FunctionDefaults { + func_id, + defaults, + globals, + })); + self.push(Value::Ref(heap_id)); + } + } + Opcode::MakeClosure => { + let (func_idx, defaults_count, cell_count) = self.current_frame.fetch_u16_u8_u8(); + let func_id = FunctionId::from_index(func_idx); + let (defaults_count, cell_count) = (defaults_count as usize, cell_count as usize); + + // Pop cells from stack (pushed after defaults, so on top) + // Cells are Value::Ref pointing to HeapData::Cell + // We use individual pops which reverses order, so we need to reverse back + let mut cells = Vec::with_capacity(cell_count); + for _ in 0..cell_count { + // mut needed for dec_ref_forget when memory-model-checks feature is enabled + #[cfg_attr(not(feature = "memory-model-checks"), expect(unused_mut))] + let mut cell_val = self.pop(); + match &cell_val { + Value::Ref(heap_id) => { + // Keep the reference - the Closure will own the HeapId + cells.push(*heap_id); + // Mark the Value as dereferenced since Closure takes ownership + // of the reference count (we don't call drop_with because + // we're not decrementing the refcount, just transferring it) + #[cfg(feature = "memory-model-checks")] + cell_val.dec_ref_forget(); + } + _ => { + return Err(RunError::internal("MakeClosure: expected cell reference on stack")); + } + } + } + // Reverse to get original order (individual pops reverse the order) + cells.reverse(); + + // Pop default values from stack (drain maintains order: first pushed = first in vec) + let defaults = self.pop_n(defaults_count); + let globals = self + .current_frame + .namespace + .as_deref() + .and_then(FrameNamespace::dict_globals); + if let Some(globals) = globals { + self.heap.inc_ref(globals); + } + + // Create Closure on heap and push reference + let heap_id = self.heap.allocate(HeapData::Closure(Closure { + func_id, + cells: cells.into_boxed_slice(), + defaults: defaults.into_boxed_slice(), + globals, + })); + self.push(Value::Ref(heap_id)); + } + // Exception Handling + Opcode::Raise => { + let exc = self.pop(); + let error = self.make_exception(&exc, true); // is_raise=true, hide caret + // Re-raise an instance as-is so `raise e` preserves `e`'s + // identity, like CPython. A bare type or non-exception has + // nothing to reuse and rebuilds from the error. + let raised = match &exc { + Value::Ref(id) if matches!(self.heap.get(*id), HeapData::Exception(_)) => Some(exc), + _ => { + exc.drop_with(self); + None + } + }; + if let Some(result) = self.handle_exception_with_value(error, raised) { + return Err(result); + } + yield_if_parked!(self); + } + Opcode::Assert => { + match decode_assert_flags(self.current_frame.fetch_u8()).expect("invalid assert flags in bytecode") + { + Some(op) => try_catch!(self, self.assert_cmp(op)), + None => try_catch!(self, self.assert_test()), + } + } + Opcode::AssertFailed => { + let cmp_op = + decode_assert_flags(self.current_frame.fetch_u8()).expect("invalid assert flags in bytecode"); + let error = self.assert_failed_msg(cmp_op); + catch!(self, error); + } + Opcode::Reraise => { + // Clone rather than pop: a locally caught bare raise must + // preserve its enclosing handler's active exception. + let (error, raised) = self.reraise_exception(); + if let Some(result) = self.handle_exception_with_value(error, raised) { + return Err(result); + } + yield_if_parked!(self); + } + Opcode::ClearException => { + // Pop the current exception from the stack + // This restores the previous exception context (if any) + if let Some(exc) = self.exception_stack.pop() { + exc.drop_with(self); + } + } + Opcode::CheckExcMatch => { + // Stack: [exception, exc_type] -> [exception, bool] + let exc_type = self.pop(); + let exception = self.peek(); + let result = self.check_exc_match(exception, &exc_type); + exc_type.drop_with(self); + match result { + Ok(matched) => self.push(Value::Bool(matched)), + // An invalid `except` type (e.g. `except 123:` or a + // nested tuple) raises a `TypeError`. As in CPython this + // is an ordinary exception raised while evaluating the + // clause: it propagates out of the whole `try` and may be + // caught by an enclosing handler, so route it through the + // exception machinery rather than aborting the run. + Err(err) => catch!(self, err), + } + } + // Return + Opcode::ReturnValue => { + let value = self.pop(); + if self.suspended_frames.is_empty() { + // Last frame - check if this is main task or spawned task + let is_main_task = self.is_main_task(); + + if is_main_task { + // Module-level return - we're done + return Ok(FrameExit::Return(value)); + } + + // Spawned task completed - handle task completion + let result = self.handle_task_completion(value); + match result { + Ok(AwaitResult::ValueReady(v)) => { + self.push(v); + } + Ok(AwaitResult::FramePushed) => {} + Ok(AwaitResult::Yield(pending)) => { + // All tasks blocked - return to host + return Ok(FrameExit::ResolveFutures(pending)); + } + Err(e) => catch!(self, e), + } + continue; + } + // Read the initializer flag before popping the frame. + let is_init = self.current_frame().is_initializer; + // Pop current frame; `stop` requests returning to the host + // (e.g. `evaluate_function`). + let stop = self.pop_frame(); + if is_init { + if !matches!(value, Value::None) { + // CPython raises at the `Foo(...)` call site: the + // initializer frame is already popped, so the traceback + // matches (no `__init__` frame). + let type_name = value.py_type_name(self); + value.drop_with(self); + let err = ExcType::type_error_init_return(type_name); + if stop { + // The initializer was driven by `evaluate_function` + // and its frame boundary is already popped — + // propagate directly rather than unwinding into + // frames that must not observe this error. The + // pending instance left on the operand stack is + // reclaimed by the eventual `handle_exception` + // stack drain (or final teardown). + return Err(err); + } + catch!(self, err); + continue; + } + // `__init__` returned None — discard it. The instance was + // pushed onto the caller's stack before this frame ran and + // is the real result of `Foo(...)`. + value.drop_with(self); + if stop { + let instance = self.pop(); + return Ok(FrameExit::Return(instance)); + } + // Instance already on the caller's stack — push nothing. + } else if stop { + // This frame indicated evaluation should stop - return to host with value + // e.g. `evaluate_function` + return Ok(FrameExit::Return(value)); + } else { + self.push(value); + } + } + // Async/Await + Opcode::Await => { + let result = self.exec_get_awaitable(); + match result { + Ok(AwaitResult::ValueReady(value)) => { + self.push(value); + } + Ok(AwaitResult::FramePushed) => {} + Ok(AwaitResult::Yield(pending_calls)) => { + // All tasks are blocked - return control to host + return Ok(FrameExit::ResolveFutures(pending_calls)); + } + Err(e) => { + catch!(self, e); + } + } + } + // Unpacking - route through exception handling + Opcode::UnpackSequence => { + let count = self.current_frame.fetch_u8() as usize; + try_catch!(self, self.unpack_sequence(count)); + } + Opcode::UnpackEx => { + let (before, after) = self.current_frame.fetch_u8_u8(); + try_catch!(self, self.unpack_ex(before as usize, after as usize)); + } + // Pattern matching + Opcode::MatchShape => { + let (length, flags) = self.current_frame.fetch_u16_u8(); + self.match_shape(length, flags); + } + Opcode::MatchKeys => { + let mode = self.current_frame.fetch_u8(); + if mode == MATCH_KEYS_REST { + try_catch!(self, self.match_keys_rest()); + } else { + try_catch!(self, self.match_keys()); + } + } + Opcode::MatchClass => { + let nargs = usize::from(self.current_frame.fetch_u8()); + try_catch!(self, self.match_class(nargs)); + } + Opcode::MatchAttr => { + let index = usize::from(self.current_frame.fetch_u8()); + handle_call_result!(self, self.match_attr(index)); + } + // Special + Opcode::Nop => { + // No operation + } + // Module Operations + Opcode::LoadModule => { + let module_id = self.current_frame.fetch_u16(); + // for the `LoadAttrImport`s of a `from ... import`; harmless for a bare `import` + self.current_frame.import_from_module = Some(StringId::from_index(module_id)); + handle_call_result!(self, Ok(self.load_module(module_id))); + } + // Context Managers + Opcode::BeforeWith => { + handle_call_result!(self, self.exec_before_with()); + } + Opcode::WithExit => { + handle_call_result!(self, self.exec_with_exit()); + } + Opcode::WithExceptStart => { + handle_call_result!(self, self.exec_with_except_start()); + } + } + } + } + + /// Loads a top-level built-in or suspends with [`OsFunctionCall::Import`]. + /// The host's value becomes the module; `NotFound` raises `ModuleNotFoundError`. + /// `LoadSubmodule` resolves the remaining dotted components. + fn load_module(&mut self, module_id: u16) -> CallResult { + let name_id = StringId::from_index(module_id); + match self.interns.static_string(name_id).and_then(StandardLib::from_static) { + Some(module) => CallResult::Value(Value::Ref(module.create(self))), + None => CallResult::OsCall(OsFunctionCall::Import(self.interns.get_str(name_id).to_owned())), + } + } + + /// Resumes execution after an external call completes. + /// + /// Pushes the return value onto the stack and continues execution. + /// + /// If the paused OS call has a pending effect, the result is routed + /// through the corresponding helper (file-state update or `os.listdir` + /// name reduction) before it is pushed back to Python. + pub fn resume(&mut self, obj: MontyObject) -> Result { + // Pre-conversion effects reshape the raw host object; a post-conversion + // effect waits in the slot until the value exists to apply it to. + let obj = match self.pending_effect.take() { + Some(PendingEffect::Pre(effect)) => match effect.reshape(obj, self) { + Ok(Reshaped::Value(obj)) => obj, + Ok(Reshaped::Call { call, effect }) => return self.suspend_again(call, effect), + Err(err) => return self.resume_with_exception(err), + }, + // Builds its result straight from the raw reply, never converting it. + Some(PendingEffect::Scan(effect)) => { + return match effect.apply(Ok(obj), self) { + Ok(value) => { + self.push(value); + self.run_external() + } + Err(err) => self.resume_with_exception(err), + }; + } + post => { + self.pending_effect = post; + obj + } + }; + // The sleeps ignore the host's answer, so an unconvertible one (a + // host object with no wire form, say) must not fail them. + let obj = match self.pending_effect.take() { + Some(PendingEffect::Post(PostConversionEffect::DiscardResult)) => { + self.push(Value::None); + return self.run_external(); + } + Some(PendingEffect::Post(PostConversionEffect::SleepResult { result })) => { + let settled = self.settled_awaitable(result); + self.push(settled); + return self.run_external(); + } + effect => { + self.pending_effect = effect; + obj + } + }; + // Output-only entropy replies must raise the os.urandom contract error at the draw. + let seeding = matches!( + self.pending_effect, + Some(PendingEffect::Post(PostConversionEffect::SeedRandom { .. })) + ); + let reply_type = seeding.then(|| obj.as_ref().type_name().to_owned()); + // Surface resource-exhaustion failures from `to_value` (e.g. a host + // string whose `heap.allocate` trips `max_memory`) as the same + // `RunError::Resource` that pure-Monty allocations produce, so the + // user sees `MemoryError` instead of `RuntimeError: invalid return + // type`. Other input errors stay as `RuntimeError`. + let value = match obj.to_value(self) { + Ok(value) => value, + Err(InvalidInputError::Resource(err)) => return Err(RunError::from(err)), + Err(InvalidInputError::InvalidType(_)) if let Some(type_name) = reply_type => { + let effect = self.pending_effect.take(); + release_pending_effect(effect, self.heap); + return self.resume_with_exception(urandom_reply_error(Err(&type_name), SEED_BYTES)); + } + Err(other @ InvalidInputError::InvalidType(_)) => { + return Err( + SimpleException::new(ExcType::RuntimeError, Some(format!("invalid return type: {other}"))).into(), + ); + } + }; + let result = match self.pending_effect.take() { + Some(PendingEffect::Post(PostConversionEffect::BufferStore { file_id })) => { + apply_buffer_store(file_id, value, self).map(Some) + } + // Parsing runs outside `run_external`, so it needs its own execution-clock window. + Some(PendingEffect::Post(PostConversionEffect::JsonLoad { file_id })) => { + self.heap.tracker.on_execution_start(); + let parsed = apply_json_load(file_id, value, self); + self.heap.tracker.on_execution_stop(); + parsed.map(Some) + } + // Answers nothing: the `ForIter` that asked for the load re-dispatches. + Some(PendingEffect::Post(PostConversionEffect::BufferLoad { file_id })) => { + apply_buffer_load(file_id, value, self).map(|()| None) + } + Some(PendingEffect::Post(PostConversionEffect::FileNext { file_id, default })) => { + apply_file_next(file_id, default, value, self).map(Some) + } + Some(PendingEffect::Post(PostConversionEffect::WritePosition { + file_id, + text_length, + result_none, + .. + })) => apply_write_position(file_id, text_length, result_none, value, self).map(Some), + Some(PendingEffect::Post(PostConversionEffect::LoadThenCall { + file_id, + callable, + args, + })) => return self.resume_load_then_call(file_id, callable, args, value), + Some(PendingEffect::Post(PostConversionEffect::OpenName { name, newline })) => { + apply_open_name(name, newline, value, self).map(Some) + } + Some(PendingEffect::Post(PostConversionEffect::SeedRandom { target, retry })) => { + apply_seed_random(target, retry, value, self).map(Some) + } + Some(PendingEffect::Post(PostConversionEffect::ClockReading { reading })) => { + apply_clock_reading(reading, value, self).map(Some) + } + // The sleeps were answered above; any pre-conversion effect was consumed. + Some( + PendingEffect::Post(PostConversionEffect::DiscardResult | PostConversionEffect::SleepResult { .. }) + | PendingEffect::Pre(_) + | PendingEffect::Scan(_), + ) + | None => Ok(Some(value)), + }; + match result { + Ok(value) => { + if let Some(value) = value { + self.push(value); + } + self.run_external() + } + Err(err) => self.resume_with_exception(err), + } + } + + /// `LoadThenCall` resume: installs the host content, then replays the call + /// that found its file unread. The call's own outcome decides what happens + /// next, since the replay may itself suspend (a second unread file). + fn resume_load_then_call( + &mut self, + file_id: HeapId, + callable: Value, + args: ArgValues, + value: Value, + ) -> Result { + if let Err(err) = apply_buffer_load(file_id, value, self) { + callable.drop_with(self); + args.drop_with(self); + return self.resume_with_exception(err); + } + // The replay runs Python (a `fieldnames` iterator, a dialect object's attributes) + // outside `run_external`, so it needs its own execution-clock window. + self.heap.tracker.on_execution_start(); + let result = self.call_function(&callable, args); + self.heap.tracker.on_execution_stop(); + callable.drop_with(self); + match result { + Ok(CallResult::Value(value)) => { + self.push(value); + self.run_external() + } + Ok(CallResult::FramePushed) => self.run_external(), + Ok(CallResult::OsCall(call)) => self.suspend_again(call, None), + Ok(CallResult::OsCallWithEffect { call, effect }) => self.suspend_again(call, Some(effect)), + Ok(other) => { + other.drop_with(self); + Err(RunError::internal( + "LoadThenCall: replayed call produced an unexpected result", + )) + } + Err(err) => self.resume_with_exception(err), + } + } + + /// Yields the next call of a multi-step operation from `resume`: the VM is + /// still suspended at the same instruction, so the host sees another + /// `OsCall` and the eventual value is pushed where the first would have been. + /// A call answered locally (a NUL byte in a predicate) resumes Python at once. + fn suspend_again(&mut self, call: OsFunctionCall, effect: Option) -> Result { + match self.prepare_os_call(call, effect) { + Ok(Some(exit)) => Ok(exit), + Ok(None) => self.run_external(), + Err(err) => self.resume_with_exception(err), + } + } + + /// Sets the instruction IP used for exception table lookup and traceback generation. + /// + /// Used by `run()` to restore the IP to the load instruction's position before + /// raising `NameError` for auto-injected `ExtFunction` values, so the traceback + /// points to the name reference rather than the call expression. + pub fn set_instruction_ip(&mut self, ip: usize) { + self.instruction_ip = ip; + } + + /// Resumes execution after an external call raised an exception. + /// + /// Uses the exception handling mechanism to try to catch the exception. + /// If caught, continues execution at the handler. If not, propagates the error. + /// + /// Also clears any pending file effect so user code that catches a + /// host-side OS exception can retry without stale in-flight state. + pub fn resume_with_exception(&mut self, error: RunError) -> Result { + if let Some(effect) = self.pending_effect.take() { + match effect { + // Resume on attempting to unlink missing file with unlink(missing_ok=True) + PendingEffect::Pre(PreConversionEffect::Unlink { missing_ok: true }) if matches!(&error, RunError::Exc(raise) if raise.exc.exc_type() == ExcType::FileNotFoundError) => + { + self.push(Value::None); + return self.run_external(); + } + PendingEffect::Post( + PostConversionEffect::BufferStore { file_id } | PostConversionEffect::JsonLoad { file_id }, + ) => { + if let HeapReadOutput::OpenFile(file) = self.heap.read(file_id) { + file.get_mut(self.heap).clear_pending_read(); + drop(file); + } + self.heap.dec_ref(file_id); + } + PendingEffect::Post(PostConversionEffect::WritePosition { + file_id, + previous_position, + previous_length, + .. + }) => { + if let HeapReadOutput::OpenFile(file) = self.heap.read(file_id) { + file.get_mut(self.heap) + .rollback_write_position(previous_position, previous_length); + drop(file); + } + self.heap.dec_ref(file_id); + } + // Nothing was installed or seeded, so there is nothing to roll + // back: dropping the pin and any stashed value is the whole undo. + PendingEffect::Post( + effect @ (PostConversionEffect::BufferLoad { .. } + | PostConversionEffect::FileNext { .. } + | PostConversionEffect::LoadThenCall { .. } + | PostConversionEffect::SeedRandom { .. }), + ) => effect.release(self.heap), + PendingEffect::Post(PostConversionEffect::SleepResult { result }) => result.drop_with(self), + // A walk or glob turns an `OSError` into its result, as CPython's + // do for a failed `scandir`; anything else still raises. + PendingEffect::Scan(effect) if effect.absorbs(&error) => { + return match effect.apply(Err(error), self) { + Ok(value) => { + self.push(value); + self.run_external() + } + Err(err) => self.resume_with_exception(err), + }; + } + PendingEffect::Scan(effect) => effect.release(self.heap), + // Hold no state or heap references — nothing to roll back. + PendingEffect::Pre(_) + | PendingEffect::Post( + PostConversionEffect::OpenName { .. } + | PostConversionEffect::DiscardResult + | PostConversionEffect::ClockReading { .. }, + ) => {} + } + } + // Use the normal exception handling mechanism + // handle_exception returns None if caught, Some(error) if not caught + if let Some(uncaught_error) = self.handle_exception(error) { + // The turn ends here without entering the run loop, so this is its + // only chance at the limit re-check every host turn ends with. + return self.finish_host_turn(Err(uncaught_error)); + } + yield_if_parked!(self); + // Exception was caught, continue execution + self.run_external() + } + + // ======================================================================== + // Stack Operations + // ======================================================================== + + /// Pushes a value onto the operand stack. + #[inline] + pub(crate) fn push(&mut self, value: Value) { + self.stack.push(value); + } + + /// Pops a value from the operand stack. + #[inline] + pub(super) fn pop(&mut self) -> Value { + self.stack.pop().expect("stack underflow") + } + + /// Peeks at the top of the operand stack without removing it. + #[inline] + pub(super) fn peek(&self) -> &Value { + self.stack.last().expect("stack underflow") + } + + /// Pops n values from the stack in reverse order (first popped is last in vec). + pub(super) fn pop_n(&mut self, n: usize) -> Vec { + let start = self.stack.len() - n; + self.stack.drain(start..).collect() + } + + // ======================================================================== + // Frame Operations + // ======================================================================== + + /// Returns the frame currently executing, or the parked placeholder. + #[inline] + pub(crate) fn current_frame(&self) -> &CallFrame<'h> { + &self.current_frame + } + + /// Returns mutable access to the current frame. + #[inline] + pub(super) fn current_frame_mut(&mut self) -> &mut CallFrame<'h> { + &mut self.current_frame + } + + /// Pushes a frame, releasing its state if the recursion limit rejects it. + pub(super) fn push_frame(&mut self, frame: CallFrame<'h>) -> RunResult<()> { + if !self.current_frame.is_parked + && let Err(e) = self.incr_recursion() + { + self.cleanup_frame_state(frame); + return Err(e.into()); + } + self.push_admitted_frame(frame); + Ok(()) + } + + /// Installs a frame after any required recursion reservation. + fn push_admitted_frame(&mut self, frame: CallFrame<'h>) { + let caller = mem::replace(&mut self.current_frame, frame); + self.suspended_frames.push(caller); + } + + /// Pops the current frame from the call stack. + /// + /// Cleans up the frame's stack region and namespace (except for global namespace). + /// Syncs `instruction_ip` to the parent frame's IP so that exception handling + /// looks up handlers in the correct frame's exception table. + /// + /// Returns `true` if this frame indicated evaluation should stop when popped. + pub(super) fn pop_frame(&mut self) -> bool { + let is_frozen = self.current_frame_is_frozen(); + let caller = self.suspended_frames.pop().expect("cannot pop the root frame"); + let frame = mem::replace(&mut self.current_frame, caller); + let should_return = frame.should_return; + self.cleanup_frame_state(frame); + // Sync instruction_ip to the restored caller so exception table lookups + // target the correct frame after returning from a nested run() call. + self.instruction_ip = self.current_frame.ip; + if !self.current_frame.is_parked && !is_frozen { + self.decr_recursion(); + } + should_return + } + + /// Releases what a finished frame owns: its stack region and namespace. + #[inline] + fn cleanup_frame_state(&mut self, frame: CallFrame<'_>) { + // Clean up frame's stack region (locals + operand stack, which now + // includes any in-flight comprehension variables — the operand-stack + // drain naturally covers them). + self.stack + .drain(frame.stack_base()..) + .for_each(|value| value.drop_with(&mut *self.heap)); + // Almost every frame has no namespace; skip the release call for those. + if let Some(namespace) = frame.namespace { + namespace.drop_with(self.heap); + } + } + + /// Drops the current task's operand and exception stacks and discards its frames. + /// Leaves a parked frame until another task is activated, or the VM is dropped. + pub(super) fn cleanup_current_task(&mut self) { + self.stack.drain(..).drop_with(self.heap); + self.exception_stack.drain(..).drop_with(self.heap); + for frame in self.suspended_frames.drain(..) { + frame.namespace.drop_with(self.heap); + } + self.current_frame.namespace.take().drop_with(self.heap); + self.current_frame.park(self.module_code); + } + + /// Runs the trial-deletion cycle collector. + /// + /// Roots are not enumerated by the VM: every value held in the stack, + /// globals, exception stack, scheduler tasks, JSON-string cache, etc. + /// already keeps its referent alive via refcount, so the collector treats + /// any non-zero refcount as proof of liveness. See + /// [`Heap::collect_cycles`]. + /// + /// Returns the number of unreachable heap entries freed during the sweep. + fn run_gc(&mut self) -> usize { + self.heap.collect_cycles() + } + + /// Forces a GC cycle and returns the freed count. + /// + /// This is only compiled for tests so integration tests can reproduce GC + /// bugs deterministically. + #[cfg(feature = "test-hooks")] + pub(crate) fn __force_gc_for_tests(&mut self) -> usize { + self.run_gc() + } + + /// Releases everything the scheduler still holds, as dropping the VM + /// would. + /// + /// A run can end with tasks still live — a task detached from a failed + /// gather outlives it, and the module can return before that task next + /// gets a turn. Their references are real, so the leak check in + /// `run_ref_counts_with_tracker` has to run *after* this rather than + /// count them as unreachable. + #[cfg(feature = "ref-count-return")] + pub(crate) fn __finalize_tasks_for_tests(&mut self) { + self.cleanup_current_task(); + self.scheduler.cleanup(self.heap); + } + + /// Returns surviving tasks' pending calls when every task is blocked + /// or [`yield_if_parked`] detects that dispatch has no runnable frame. + /// With no pending calls, report the stall now: resuming cannot progress + /// and would obscure the discarded task that caused it. + pub(super) fn pending_futures_exit(&self) -> Result { + let pending_call_ids = self.scheduler.pending_call_ids(); + if pending_call_ids.is_empty() { + Err(RunError::internal( + "asyncio scheduler stalled: no task to run and no pending external calls", + )) + } else { + Ok(FrameExit::ResolveFutures(pending_call_ids)) + } + } + + /// Returns the source position for the instruction currently executing. + pub(super) fn current_position(&self) -> CodeRange { + self.current_frame + .code + .location_for_offset(self.instruction_ip) + .map(LocationEntry::range) + .unwrap_or_default() + } + + /// Returns the position a suspension at the current instruction reports. + /// + /// `instruction_ip` still names the suspending opcode; its location entry + /// gives the byte range, so this reads no source. + pub(crate) fn suspension_position(&self) -> SourceRange { + self.code_position(self.current_frame.code, self.instruction_ip) + } + + /// Returns the source position of the `await` the main task is blocked on. + /// + /// The position reported when every task is blocked on host futures: the + /// blocked main task may be the loaded context, or parked in the scheduler + /// with its frames saved while a spawned task ran last. + pub(crate) fn main_task_position(&self) -> SourceRange { + if self.is_main_task() && !self.current_frame.is_parked { + self.suspension_position() + } else { + // `save_task_context` pushes the executing frame last. + self.scheduler + .main_task() + .and_then(|task| Some((task.frames.last()?, task.instruction_ip))) + .map_or_else(SourceRange::unknown, |(frame, ip)| { + self.code_position(frame_code(self.interns, self.module_code, frame.function_id), ip) + }) + } + } + + /// The byte range of the instruction at `offset` in `code`, named by its source. + fn code_position(&self, code: &Code, offset: usize) -> SourceRange { + code.location_for_offset(offset) + .map_or_else(SourceRange::unknown, |entry| { + let range = entry.range(); + SourceRange::new( + self.interns.get_filename(range.filename), + range.start_byte, + range.end_byte, + ) + }) + } + + /// Captures the caller's current bytecode offset for a call site, or `None` + /// while the VM is parked with no active Python task. + /// + /// The cheap counterpart to [`current_position`](Self::current_position): + /// no location-table scan, so it is affordable on every call. Out-of-range + /// offsets (an invariant violation) degrade to `None` rather than panic. + pub(super) fn current_offset(&self) -> Option { + if self.current_frame.is_parked { + None + } else { + u32::try_from(self.instruction_ip).ok() + } + } + + /// Resolves a raw caller offset (`CallFrame::call_offset`) to a source + /// [`CodeRange`] against the current frame's code, during traceback unwind + /// once the failing frame has been popped so the current frame is the caller. + pub(super) fn resolve_offset(&self, offset: u32) -> CodeRange { + self.current_frame + .code + .location_for_offset(offset as usize) + .map(LocationEntry::range) + .unwrap_or_default() + } + + // ======================================================================== + // Variable Operations + // ======================================================================== + + /// Loads a local variable and pushes it onto the stack. + /// + /// Raises `UnboundLocalError` if the slot holds `Undefined` — every reachable + /// `LoadLocal*` slot is registered as assigned by the compiler, so an undefined + /// value can only mean access-before-assignment. + fn load_local(&mut self, slot: u16) -> RunResult<()> { + let index = self.current_frame.stack_base() + slot as usize; + if matches!(self.stack[index], Value::Undefined) { + let name = self.current_frame.code.local_name(slot); + Err(self.unbound_local_error(slot, name)) + } else { + let value = self.stack[index].clone_with_heap(self.heap); + self.push(value); + Ok(()) + } + } + + /// Loads a global variable in call context, pushing an external function for undefined names. + /// + /// Unlike `load_global`, this never yields `NameLookup`. When the variable is undefined, + /// it allocates an external function so that the subsequent `CallFunction` opcode can + /// yield `FunctionCall` instead. Before doing so it tries the builtin fallback + /// (see [`builtin_for_name`]) so `f()` style calls into a builtin still work when + /// the name happens to have a module slot allocated (e.g. because the module also + /// `def`-binds the same name elsewhere) but that slot is currently `Undefined`. + fn load_global_callable(&mut self, slot: u16, name_id: StringId) { + let value = self.globals[slot as usize].clone_with_heap(self); + + if matches!(value, Value::Undefined) { + if let Some(builtin) = self.builtin_for_name(name_id) { + self.push(builtin); + return; + } + // A reserved module dunder (e.g. `__name__`) in call position resolves + // to its fixed value; the subsequent call then fails with the usual + // "object is not callable" error, matching CPython. + if let Some(value) = self.module_dunder(name_id) { + self.push(value); + return; + } + // Save the load instruction's IP so NameError tracebacks point to the name + self.ext_function_load_ip = Some(self.instruction_ip); + let function = self.heap.get_ext_function(self.interns.get_str(name_id)); + self.push(function); + } else { + self.push(value); + } + } + + /// Creates an UnboundLocalError for a local variable accessed before assignment. + fn unbound_local_error(&self, slot: u16, name: Option) -> RunError { + let name_str = match name { + Some(id) => self.interns.get_str(id).to_string(), + None => format!(""), + }; + ExcType::unbound_local_error(&name_str).into() + } + + /// Returns the builtin value for a name, if the name happens to match a builtin. + /// + /// Function-level global reads fall back to builtins at runtime when the module + /// slot is `Undefined`, mirroring CPython's `globals → builtins` lookup order. + /// Function-scope name resolution never substitutes `Expr::Builtin` at parse time + /// (see `prepare::resolve_name_or_builtin`), so this fallback is also what makes + /// late-binding patterns work: + /// + /// ```python + /// def f(): return sum(...) # uses builtin sum + /// f() + /// def sum(*args): return 42 # later module-level shadow + /// f() # picks up the user-defined sum + /// ``` + /// + /// The first call hits `globals[sum_slot] = Undefined` and falls back here to + /// the builtin; once `def sum` runs, the slot holds the user function and the + /// fallback isn't taken anymore. + fn builtin_for_name(&self, name_id: StringId) -> Option { + Builtins::value_from_name(self.interns.get_str(name_id)) + } + + /// Returns the fixed value for a module-level dunder, or `None` if `name_id` + /// does not name one of [`RESERVED_MODULE_DUNDERS`](crate::bytecode::RESERVED_MODULE_DUNDERS). + /// + /// Backs the read side of those dunders: `__name__` is always `'__main__'` + /// (Monty only ever runs a top-level module) and `__debug__` is `True` + /// (asserts always run). `__doc__`/`__spec__`/`__package__` default to + /// `None` and `__annotations__` to a fresh empty dict — module-level + /// annotations are not stored (see `limitations/typing.md`), so it is + /// always empty. `__file__` is the script name's final component under the + /// working directory the run started in. `__loader__` is deliberately + /// *not* exposed: CPython only ever puts a loader object there (never + /// `None`), so rather than diverge on the type we let it raise `NameError` + /// like other unexposed dunders (`__cached__`, …). + fn module_dunder(&self, name_id: StringId) -> Option { + let value = match self.interns.get_str(name_id) { + "__name__" => Value::InternString(self.interns.intern_static(StaticStrings::DunderMain)), + "__debug__" => Value::Bool(true), + "__file__" => allocate_string(self.env.file(), self.heap), + "__annotations__" => Value::Ref(self.heap.allocate(HeapData::Dict(Dict::new()))), + "__doc__" | "__spec__" | "__package__" => Value::None, + _ => return None, + }; + Some(value) + } + + /// Creates a NameError for an undefined global variable. + fn name_error(&self, slot: u16, name: Option) -> RunError { + let name_str = match name { + Some(id) => self.interns.get_str(id).to_string(), + None => format!(""), + }; + ExcType::name_error(&name_str).into() + } + + /// Pops the top of stack and stores it in a local variable. + fn store_local(&mut self, slot: u16) { + let value = self.pop(); + let index = self.current_frame.stack_base() + slot as usize; + let old_value = mem::replace(&mut self.stack[index], value); + old_value.drop_with(self); + } + + /// Deletes a local variable (sets it to Undefined). + fn delete_local(&mut self, slot: u16) { + let index = self.current_frame.stack_base() + slot as usize; + let old_value = mem::replace(&mut self.stack[index], Value::Undefined); + old_value.drop_with(self); + } + + /// Loads a global variable and pushes it onto the stack. + /// + /// When the variable is undefined, falls back to builtin resolution (see + /// [`builtin_for_name`]) before yielding `NameLookup` so the host can supply + /// an external binding. + #[inline] + fn load_global(&mut self, slot: u16) -> Result, RunError> { + let value = self.globals[slot as usize].clone_with_heap(self); + + // Check for undefined value — raise appropriate error or yield to host + if matches!(value, Value::Undefined) { + let name = self.global_name(slot); + + let Some(name_id) = name else { + // No name available — raise NameError directly + return Err(self.name_error(slot, None)); + }; + if let Some(builtin) = self.builtin_for_name(name_id) { + self.push(builtin); + return Ok(None); + } + if let Some(value) = self.module_dunder(name_id) { + self.push(value); + return Ok(None); + } + Ok(Some(FrameExit::NameLookup { + name_id, + namespace_slot: slot, + is_global: true, + })) + } else { + self.push(value); + Ok(None) + } + } + + /// Returns the interned name of a module-level global at `slot`, if known. + /// + /// Read from the live name map rather than the module `Code`, so slots + /// first allocated after the module was compiled are named too. + fn global_name(&self, slot: u16) -> Option { + self.global_names.names().get(usize::from(slot)).copied() + } + + /// Pops the top of stack and stores it in a global variable. + /// + /// Reassigning a reserved module dunder (see [`RESERVED_MODULE_DUNDERS`]) is + /// rejected at compile time (see `Compiler::compile_store`), so no name + /// check is needed here. + #[inline] + fn store_global(&mut self, slot: u16) { + let value = self.pop(); + self.set_global_slot(slot, value); + } + + /// Binds `value` at a global slot, releasing what the slot held. + fn set_global_slot(&mut self, slot: u16, value: Value) { + let old_value = mem::replace(&mut self.globals[slot as usize], value); + old_value.drop_with(self); + } + + /// Deletes a global variable (sets it to `Undefined`). + /// + /// Raises `NameError` if the slot is already `Undefined`. + fn delete_global(&mut self, slot: u16) -> RunResult<()> { + // TODO: the `Undefined` branch is currently unreachable from Python source, + // needs support for the `del` statement. + if matches!(self.globals[slot as usize], Value::Undefined) { + let name = self.global_name(slot); + return Err(self.name_error(slot, name)); + } + let old_value = mem::replace(&mut self.globals[slot as usize], Value::Undefined); + old_value.drop_with(self); + Ok(()) + } + + /// Loads from a closure cell and pushes onto the stack. + /// + /// The cell `HeapId` is read from the frame's local variable slot on the stack + /// (cells are stored as `Value::Ref(cell_id)` at known positions in the locals region). + /// Returns a `NameError` if the cell value is undefined (free variable not bound). + fn load_cell(&mut self, slot: u16) -> RunResult<()> { + let cell_id = self.cell_id_from_local(slot); + let value = match self.heap.get(cell_id) { + HeapData::Cell(c) => c.0.clone_with_heap(self), + _ => panic!("LoadCell: entry is not a Cell"), + }; + + // An undefined value raises the error CPython picks by cell kind: the + // free-variable NameError only for a cell *captured* from an enclosing + // function; an unbound cell this frame owns (a local captured by + // nested functions) is an ordinary UnboundLocalError, like any local. + if matches!(value, Value::Undefined) { + value.drop_with(self); + let name = self.current_frame.code.local_name(slot); + Err(if self.is_free_var_slot(slot) { + self.free_var_error(name) + } else { + self.unbound_local_error(slot, name) + }) + } else { + self.push(value); + Ok(()) + } + } + + /// Extracts the cell `HeapId` from a local variable slot on the stack. + /// + /// Cell variables are stored as `Value::Ref(cell_id)` in the frame's locals region. + fn cell_id_from_local(&self, slot: u16) -> HeapId { + match &self.stack[self.current_frame.stack_base() + slot as usize] { + Value::Ref(cell_id) => *cell_id, + other => panic!("LoadCell/StoreCell: expected cell reference in local slot {slot}, found {other:?}"), + } + } + + /// Whether `slot` holds a cell captured from an enclosing function (a + /// free variable), as opposed to a cell this frame owns. Module frames + /// (`function_id: None`) own all their cells — the only module-level + /// cells are inlined-comprehension captures. + fn is_free_var_slot(&self, slot: u16) -> bool { + self.current_frame().function_id.is_some_and(|id| { + self.interns + .get_function(id) + .free_var_slots + .iter() + .any(|s| s.as_u16() == slot) + }) + } + + /// Creates a NameError for an unbound free variable. + fn free_var_error(&self, name: Option) -> RunError { + let name_str = match name { + Some(id) => self.interns.get_str(id).to_string(), + None => "".to_string(), + }; + ExcType::name_error_free_variable(&name_str).into() + } + + /// Pops the top of stack and stores it in a closure cell. + /// + /// The cell `HeapId` is read from the frame's local variable slot on the stack. + fn store_cell(&mut self, slot: u16) { + let value = self.pop(); + // The guard will clean up the new value if we panic, or the old value if we swap + let this = self; + defer_drop_mut!(value, this); + + let cell_id = this.cell_id_from_local(slot); + let HeapReadOutput::Cell(cell) = this.heap.read(cell_id) else { + panic!("StoreCell: entry is not a Cell") + }; + mem::swap(&mut cell.get_mut(this.heap).0, value); + } + + /// Unbinds a closure cell: replaces its contents with `Undefined`, so a + /// later [`Self::load_cell`] raises the free-variable `NameError` — + /// CPython's `DELETE_DEREF` cleanup of a captured `except ... as` target. + /// The only emitter stores `None` first, so the cell is never already + /// unbound here (no error path, unlike [`Self::delete_global`]). + fn delete_cell(&mut self, slot: u16) { + let value = Value::Undefined; + // the guard drops the cell's previous contents after the swap + let this = self; + defer_drop_mut!(value, this); + + let cell_id = this.cell_id_from_local(slot); + let HeapReadOutput::Cell(cell) = this.heap.read(cell_id) else { + panic!("DeleteCell: entry is not a Cell") + }; + mem::swap(&mut cell.get_mut(this.heap).0, value); + } +} + +// `heap` is not a public field on VM, so this implementation needs to go here rather than in `heap.rs` +impl ContainsHeap for VM<'_> { + fn heap(&self) -> &Heap { + self.heap + } + fn heap_mut(&mut self) -> &mut Heap { + self.heap + } +} + +/// Ensures proper reference-counting cleanup when the VM goes out of scope. +/// +/// Drains exception stack, operand stack, globals, scheduler state, and JSON +/// string cache — all of which may hold heap references that need their +/// ref-counts decremented. Fields that were already emptied (e.g. by +/// `take_globals`) are harmlessly drained as empty. +impl Drop for VM<'_> { + fn drop(&mut self) { + release_pending_effect(self.pending_effect.take(), self.heap); + self.pending_lookup_effect.take().drop_with(self.heap); + self.cleanup_current_task(); + self.scheduler.cleanup(self.heap); + self.globals.drain(..).drop_with(self.heap); + self.json_string_cache.drop_all(self.heap); + } +} diff --git a/crates/bashkit-monty/src/bytecode/vm/namespace.rs b/crates/bashkit-monty/src/bytecode/vm/namespace.rs new file mode 100644 index 000000000..8fd6ab68f --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/namespace.rs @@ -0,0 +1,424 @@ +//! Frame namespaces: where a frame resolves names that are not stack slots. +//! +//! Ordinary frames resolve every name at compile time to a stack slot or a +//! `VM::globals` slot. Code compiled at runtime by `eval()` / `exec()` cannot: +//! its top level may run against a locals dict, an explicit globals dict, or +//! both, and functions it defines under a globals dict keep resolving their +//! globals through that dict at every call. [`FrameNamespace`] records which +//! case a frame is in; the descriptor owns the dict references it names. + +use std::iter; + +use ahash::AHashSet; + +use super::{CallFrame, VM}; +use crate::{ + bytecode::{FrameExit, NAME_CALLABLE, NAME_GLOBAL_ONLY}, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{ContainsHeap, DropGuard, DropWithContext, HeapData, HeapId, HeapReadOutput}, + intern::{CompileInterns, FunctionId, StringId}, + prepare::SnippetNames, + types::Dict, + value::Value, +}; + +/// Where a frame's global names live. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub(crate) enum FrameGlobals { + /// The module's dense `VM::globals` array, addressed by slot. + Slots, + /// An explicit `exec()` / `eval()` globals dict, addressed by name. The + /// frame owns a reference to it. + Dict(HeapId), +} + +/// The namespaces a frame resolves names through, for the frames that need +/// any: an ordinary frame (locals in stack slots, globals in `VM::globals`) +/// carries `None`, so the common case costs one null pointer. +/// +/// Every `HeapId` here is OWNED by the frame: released exactly once by +/// `VM::cleanup_frame_state`, or handed to a serialized frame by +/// `CallFrame::serialize`. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum FrameNamespace { + /// A function or class body defined under an explicit globals dict: locals + /// in stack slots, globals looked up by name in `globals`. + Function { + /// The `exec()` / `eval()` globals dict the function was defined under. + globals: HeapId, + }, + /// The top-level frame of an `eval()` / `exec()` snippet: names are looked + /// up at runtime through `locals` (when present) and then `globals`. + Snippet { + /// Where the snippet's globals live. + globals: FrameGlobals, + /// The snippet's locals dict, if it runs with one distinct from its globals. + locals: Option, + }, +} + +impl FrameNamespace { + /// The globals dict a function created in this frame must carry, so its + /// own frames resolve globals the same way; `None` for slot globals. + pub(crate) fn dict_globals(&self) -> Option { + match self { + Self::Snippet { + globals: FrameGlobals::Slots, + .. + } => None, + Self::Function { globals } + | Self::Snippet { + globals: FrameGlobals::Dict(globals), + .. + } => Some(*globals), + } + } +} + +/// The namespace for a frame of a function that carries `globals`: an owned +/// reference to the dict (inc_ref'd here), or `None` for slot globals. +#[inline] +pub(crate) fn function_namespace(globals: Option, heap: &impl ContainsHeap) -> Option> { + globals.map(|globals| { + heap.heap().inc_ref(globals); + Box::new(FrameNamespace::Function { globals }) + }) +} + +impl DropWithContext for Box { + fn drop_with(self, ctx: &mut C) { + match *self { + FrameNamespace::Function { globals } => ctx.heap_mut().dec_ref(globals), + FrameNamespace::Snippet { globals, locals } => { + if let FrameGlobals::Dict(globals) = globals { + ctx.heap_mut().dec_ref(globals); + } + if let Some(locals) = locals { + ctx.heap_mut().dec_ref(locals); + } + } + } + } +} + +impl<'h> VM<'h> { + /// The namespace an `eval()` / `exec()` snippet runs in, from the call's + /// `globals` / `locals` dicts (owned references, or `None`), and the mode + /// its top level compiles in. + /// + /// Without a `globals` dict the snippet inherits the caller's: a snippet + /// frame's own namespace (so nested implicit calls share it), a + /// dict-namespaced function's dict, or the module slots. Without a + /// `locals` dict a function frame contributes a snapshot of its locals + /// (PEP 667), a module frame nothing. + pub(crate) fn snippet_namespace( + &mut self, + globals: Option, + locals: Option, + ) -> RunResult<(SnippetNames, Box)> { + let (globals, locals) = match globals { + Some(dict) => (FrameGlobals::Dict(dict), locals), + None => match self.namespace_frame().namespace.as_deref() { + Some(FrameNamespace::Snippet { + globals, + locals: frame_locals, + }) => { + let (globals, frame_locals) = (*globals, *frame_locals); + if let FrameGlobals::Dict(dict) = globals { + self.heap.inc_ref(dict); + } + let locals = match (locals, frame_locals) { + (Some(dict), _) => Some(dict), + (None, Some(dict)) => { + self.heap.inc_ref(dict); + Some(dict) + } + (None, None) => None, + }; + (globals, locals) + } + Some(FrameNamespace::Function { globals }) => { + let dict = *globals; + let locals = match locals { + Some(dict) => Some(dict), + None => Some(self.snapshot_locals()?), + }; + self.heap.inc_ref(dict); + (FrameGlobals::Dict(dict), locals) + } + None => { + let locals = match (locals, self.namespace_frame().function_id) { + (Some(dict), _) => Some(dict), + (None, Some(_)) => Some(self.snapshot_locals()?), + (None, None) => None, + }; + (FrameGlobals::Slots, locals) + } + }, + }; + let names = match (globals, locals) { + (FrameGlobals::Dict(_), _) => SnippetNames::NameOverDict, + (FrameGlobals::Slots, Some(_)) => SnippetNames::NameOverSlots, + (FrameGlobals::Slots, None) => SnippetNames::Slots, + }; + Ok((names, Box::new(FrameNamespace::Snippet { globals, locals }))) + } + + /// Admits a snippet before publishing its compilation and installing its frame. + /// A recursion-limit rejection discards both the overlay and the owned namespace. + pub(crate) fn push_snippet_frame( + &mut self, + func_id: FunctionId, + overlay: CompileInterns<'_>, + namespace: Box, + ) -> RunResult<()> { + let mut namespace_guard = DropGuard::new(namespace, self); + let (_, vm) = namespace_guard.as_parts_mut(); + debug_assert!(!vm.current_frame.is_parked, "snippet needs an executing caller"); + vm.incr_recursion()?; + // Publication makes the code borrowable for the run. Nothing fallible or + // re-entrant may intervene between admission and installing the frame. + overlay.commit(); + let (namespace, vm) = namespace_guard.into_parts(); + let code = &vm.interns.get_function(func_id).code; + let frame = CallFrame::new_function( + code, + vm.stack.len(), + 0, + vm.exception_stack.len(), + func_id, + vm.current_offset(), + Some(namespace), + ); + vm.push_admitted_frame(frame); + Ok(()) + } + + /// The dict `locals()` returns in the current frame. + /// + /// A snippet with a locals dict returns that dict itself; one that runs + /// straight in a globals dict returns the dict. Every other frame gets a + /// snapshot: named stack slots for a function, bound slots for a module. + pub(crate) fn locals_dict(&mut self) -> RunResult { + let dict_id = match self.namespace_frame().namespace.as_deref() { + Some( + FrameNamespace::Snippet { locals: Some(dict), .. } + | FrameNamespace::Snippet { + globals: FrameGlobals::Dict(dict), + locals: None, + }, + ) => { + let dict = *dict; + self.heap.inc_ref(dict); + dict + } + Some(FrameNamespace::Snippet { + globals: FrameGlobals::Slots, + locals: None, + }) => self.snapshot_globals()?, + Some(FrameNamespace::Function { .. }) => self.snapshot_locals()?, + None if self.namespace_frame().function_id.is_none() => self.snapshot_globals()?, + None => self.snapshot_locals()?, + }; + Ok(Value::Ref(dict_id)) + } + + /// A fresh dict of the bound module globals, for `locals()` at module scope. + fn snapshot_globals(&mut self) -> RunResult { + let dict_id = self.heap.allocate(HeapData::Dict(Dict::new())); + // Owned by the guard until every entry is in, so a failed insert frees it. + let mut dict_guard = DropGuard::new(Value::Ref(dict_id), self); + let (_, this) = dict_guard.as_parts_mut(); + for slot in 0..this.global_names.len() { + if !matches!(this.globals[slot], Value::Undefined) { + let name_id = this.global_names.names()[slot]; + let value = this.globals[slot].clone_with_heap(this.heap); + this.namespace_set(dict_id, name_id, value)?; + } + } + let (dict, _) = dict_guard.into_parts(); + Ok(dict.into_ref_id().expect("snapshot dict is a heap reference")) + } + + /// `LoadName`: resolves `name_id` through the frame's namespace and pushes it. + /// + /// With slot globals the tail of the lookup is [`load_global`](Self::load_global) + /// (or the callable variant under `NAME_CALLABLE`), so builtins, module + /// dunders and the host `NameLookup` suspension behave exactly as for + /// compiled code. Dict globals see the dict and builtins only: CPython + /// resolves nothing else for `exec(src, {})`. + pub(super) fn load_name(&mut self, slot: u16, name_id: StringId, flags: u8) -> RunResult> { + let (globals, locals) = self.frame_namespace(); + if flags & NAME_GLOBAL_ONLY == 0 + && let Some(locals) = locals + && let Some(value) = self.namespace_get(locals, name_id)? + { + self.push(value); + return Ok(None); + } + match globals { + FrameGlobals::Slots if flags & NAME_CALLABLE != 0 => { + self.load_global_callable(slot, name_id); + Ok(None) + } + FrameGlobals::Slots => self.load_global(slot), + FrameGlobals::Dict(dict) => { + if let Some(value) = self.namespace_get(dict, name_id)? { + self.push(value); + } else if let Some(builtin) = self.builtin_for_name(name_id) { + self.push(builtin); + } else { + return Err(ExcType::name_error(self.interns.get_str(name_id)).into()); + } + Ok(None) + } + } + } + + /// `StoreName`: pops the value and binds `name_id` in the locals dict when + /// there is one (and `NAME_GLOBAL_ONLY` is clear), else in the globals. + pub(super) fn store_name(&mut self, slot: u16, name_id: StringId, flags: u8) -> RunResult<()> { + let value = self.pop(); + match self.frame_namespace() { + (_, Some(locals)) if flags & NAME_GLOBAL_ONLY == 0 => self.namespace_set(locals, name_id, value), + (FrameGlobals::Slots, _) => { + self.set_global_slot(slot, value); + Ok(()) + } + (FrameGlobals::Dict(dict), _) => self.namespace_set(dict, name_id, value), + } + } + + /// `DeleteName`: unbinds `name_id` where [`store_name`](Self::store_name) + /// would bind it; `NameError` if it is not bound there. + pub(super) fn delete_name(&mut self, slot: u16, name_id: StringId, flags: u8) -> RunResult<()> { + let removed = match self.frame_namespace() { + (_, Some(locals)) if flags & NAME_GLOBAL_ONLY == 0 => self.namespace_pop(locals, name_id)?, + (FrameGlobals::Slots, _) => return self.delete_global(slot), + (FrameGlobals::Dict(dict), _) => self.namespace_pop(dict, name_id)?, + }; + if removed { + Ok(()) + } else { + Err(ExcType::name_error(self.interns.get_str(name_id)).into()) + } + } + + /// Builds the dict `locals()` reports for the current frame: a snapshot of + /// its named stack slots, with captured variables read through their cells + /// (PEP 667 semantics — writes to the dict never reach the frame). + /// + /// Returns an owned reference to the new dict. + pub(crate) fn snapshot_locals(&mut self) -> RunResult { + let dict_id = self.heap.allocate(HeapData::Dict(Dict::new())); + // Owned by the guard until every entry is in, so a failed insert frees it. + let mut dict_guard = DropGuard::new(Value::Ref(dict_id), self); + let (_, this) = dict_guard.as_parts_mut(); + let frame = this.namespace_frame(); + let base = frame.stack_base(); + let code = frame.code; + let names = (0..frame.locals_count).filter_map(|slot| { + code.local_name(slot) + .filter(|name_id| *name_id != StringId::default()) + .map(|name_id| (usize::from(slot), name_id)) + }); + // Cell slots go last so a captured parameter's live cell value replaces + // the stale copy left in its parameter slot under the same name. + let cell_slots: AHashSet = frame + .function_id + .map(|id| this.interns.get_function(id)) + .into_iter() + .flat_map(|func| { + func.cell_var_slots + .iter() + .chain(&func.free_var_slots) + .map(|slot| slot.index()) + }) + .collect(); + for (slot, name_id) in names.clone().filter(|(slot, _)| !cell_slots.contains(slot)) { + let value = this.stack[base + slot].clone_with_heap(this.heap); + this.snapshot_entry(dict_id, name_id, value)?; + } + for (slot, name_id) in names.filter(|(slot, _)| cell_slots.contains(slot)) { + let value = match &this.stack[base + slot] { + Value::Ref(cell_id) => match this.heap.get(*cell_id) { + HeapData::Cell(cell) => cell.0.clone_with_heap(this.heap), + _ => Value::Undefined, + }, + _ => Value::Undefined, + }; + this.snapshot_entry(dict_id, name_id, value)?; + } + let (dict, _) = dict_guard.into_parts(); + Ok(dict.into_ref_id().expect("snapshot dict is a heap reference")) + } + + /// Finds the Python caller for namespace-sensitive builtins invoked by frozen code. + /// Private continuation locals must never escape through `locals()`, `eval()` or `exec()`. + fn namespace_frame(&self) -> &CallFrame<'h> { + self.suspended_frames + .iter() + .chain(iter::once(&self.current_frame)) + .rev() + .find(|frame| { + frame + .function_id + .is_none_or(|id| !self.interns.is_internal_function(id)) + }) + .expect("frozen code has a Python caller") + } + + /// Stores one `locals()` entry, skipping unbound slots. + fn snapshot_entry(&mut self, dict_id: HeapId, name_id: StringId, value: Value) -> RunResult<()> { + if matches!(value, Value::Undefined) { + Ok(()) + } else { + self.namespace_set(dict_id, name_id, value) + } + } + + /// The globals and locals the current frame resolves names through. + /// + /// A frame with no namespace resolves like compiled module code. + fn frame_namespace(&self) -> (FrameGlobals, Option) { + match self.current_frame.namespace.as_deref() { + None => (FrameGlobals::Slots, None), + Some(FrameNamespace::Function { globals }) => (FrameGlobals::Dict(*globals), None), + Some(FrameNamespace::Snippet { globals, locals }) => (*globals, *locals), + } + } + + /// Looks `name_id` up in a namespace dict, returning an owned value. + fn namespace_get(&mut self, dict_id: HeapId, name_id: StringId) -> RunResult> { + let HeapReadOutput::Dict(dict) = self.heap.read(dict_id) else { + return Err(RunError::internal("namespace is not a dict")); + }; + dict.dict_get(&Value::InternString(name_id), self) + } + + /// Binds `name_id` to `value` in a namespace dict, releasing any old value. + fn namespace_set(&mut self, dict_id: HeapId, name_id: StringId, value: Value) -> RunResult<()> { + let HeapReadOutput::Dict(dict) = self.heap.read(dict_id) else { + value.drop_with(self); + return Err(RunError::internal("namespace is not a dict")); + }; + let old = dict.set(Value::InternString(name_id), value, self)?; + old.drop_with(self); + Ok(()) + } + + /// Removes `name_id` from a namespace dict; `false` if it was not bound. + fn namespace_pop(&mut self, dict_id: HeapId, name_id: StringId) -> RunResult { + let HeapReadOutput::Dict(dict) = self.heap.read(dict_id) else { + return Err(RunError::internal("namespace is not a dict")); + }; + match dict.pop(&Value::InternString(name_id), self)? { + Some((key, value)) => { + key.drop_with(self); + value.drop_with(self); + Ok(true) + } + None => Ok(false), + } + } +} diff --git a/crates/bashkit-monty/src/bytecode/vm/pattern.rs b/crates/bashkit-monty/src/bytecode/vm/pattern.rs new file mode 100644 index 000000000..0e4c025a4 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/pattern.rs @@ -0,0 +1,448 @@ +//! Runtime support for `match` statement patterns: the `MatchShape`, +//! `MatchKeys`, `MatchClass` and `MatchAttr` opcodes, Monty's counterparts of +//! CPython's `MATCH_SEQUENCE` / `MATCH_MAPPING` / `MATCH_KEYS` / `MATCH_CLASS`. +//! +//! The compiler (`bytecode/pattern.rs`) only emits these against values it has +//! already shaped: `MatchKeys` always follows a successful mapping `MatchShape`, +//! `MatchAttr` a successful `MatchClass`, and the keys / keyword-name tuples +//! are built by the preceding `BuildTuple`. Class patterns read one attribute +//! per `MatchAttr` instruction so a read that has to go to the host can suspend +//! between them like any other attribute load. + +use super::{CallResult, VM, attr::PendingLookupEffect}; +use crate::{ + builtins::{Builtins, isinstance::isinstance_check}, + bytecode::op::{MATCH_SHAPE_MAPPING, MATCH_SHAPE_MIN_LEN}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{DropGuard, DropWithContext, Heap, HeapData, HeapReadOutput}, + types::{ + Dict, PyTrait, Type, instance::class_name, set::set_element_hash, str::allocate_string, tuple::allocate_tuple, + }, + value::{EitherStr, Value}, +}; + +/// Builtin types whose class pattern with one positional sub-pattern matches +/// the subject itself (`case int(x)`), CPython's `_Py_TPFLAGS_MATCH_SELF`. +/// Subclasses inherit the flag, hence `defaultdict` and `Counter`. +const SELF_MATCHING_TYPES: [Type; 12] = [ + Type::Bool, + Type::Bytes, + Type::Counter, + Type::DefaultDict, + Type::Dict, + Type::Float, + Type::FrozenSet, + Type::Int, + Type::List, + Type::Set, + Type::Str, + Type::Tuple, +]; + +/// How a class pattern's positional sub-patterns read the subject, once their +/// count has been checked against `__match_args__`. +enum MatchArgs { + /// A self-matching builtin: the single positional sub-pattern gets the subject. + SelfMatch, + /// The attribute name for each positional sub-pattern, in order. + Names(Vec), +} + +impl VM<'_> { + /// `MatchShape`: pushes whether the subject on top of the stack is a + /// sequence or mapping (per `flags`) of an acceptable length. + /// + /// Sequences are `list`, `tuple`, namedtuples, `range` and `deque`, never + /// `str` or `bytes`; mappings are `dict` and its `collections` subclasses. + pub(super) fn match_shape(&mut self, length: u16, flags: u8) { + let subject = self.peek(); + let ty = subject.py_type(self); + let shape_ok = if flags & MATCH_SHAPE_MAPPING != 0 { + matches!(ty, Type::Dict | Type::DefaultDict | Type::Counter) + } else { + matches!( + ty, + Type::List | Type::Tuple | Type::NamedTuple | Type::Range | Type::Deque + ) + }; + let matched = shape_ok && { + let actual = subject.py_len(self).unwrap_or(0); + if flags & MATCH_SHAPE_MIN_LEN != 0 { + actual >= usize::from(length) + } else { + actual == usize::from(length) + } + }; + self.push(Value::Bool(matched)); + } + + /// `MatchKeys` (values mode): `[subject, keys] -> [subject, keys, values_or_None, bool]`. + /// + /// Every key is looked up without triggering `defaultdict` factories, as + /// CPython's `dict.get`-based lookup does; one missing key fails the match. + pub(super) fn match_keys(&mut self) -> RunResult<()> { + let keys = self.pop(); + let subject = self.pop(); + let mut guard = DropGuard::new((subject, keys), self); + let ((subject, keys), vm) = guard.as_parts(); + let values = lookup_pattern_keys(subject, keys, vm)?; + let ((subject, keys), vm) = guard.into_parts(); + vm.push(subject); + vm.push(keys); + if let Some(values) = values { + let tuple = allocate_tuple(values.into_iter().collect(), vm.heap); + vm.push(tuple); + vm.push(Value::Bool(true)); + } else { + vm.push(Value::None); + vm.push(Value::Bool(false)); + } + Ok(()) + } + + /// `MatchKeys` (rest mode): `[subject, keys] -> [rest]`, a new plain `dict` + /// of the subject's entries minus the matched keys, for `**rest`. + pub(super) fn match_keys_rest(&mut self) -> RunResult<()> { + let this = self; + let keys = this.pop(); + let subject = this.pop(); + defer_drop!(keys, this); + defer_drop!(subject, this); + let rest = build_rest_dict(subject, keys, this)?; + this.push(rest); + Ok(()) + } + + /// `MatchClass`: `[subject, cls, kwd_names] -> [subject, cls, names_or_None, bool]`. + /// + /// Checks `isinstance(subject, cls)` and resolves the attribute names the + /// sub-patterns read: `nargs` from `cls.__match_args__` (a `None` entry + /// meaning the subject itself, for self-matching builtins), then the + /// keywords. Every other problem raises `TypeError`; the reads themselves + /// are the following `MatchAttr` instructions. + pub(super) fn match_class(&mut self, nargs: usize) -> RunResult<()> { + let this = self; + let kwd_names = this.pop(); + let len = this.stack.len(); + let cls = this.stack[len - 1].clone_with_heap(this.heap); + let subject = this.stack[len - 2].clone_with_heap(this.heap); + defer_drop!(kwd_names, this); + defer_drop!(cls, this); + defer_drop!(subject, this); + if let Some(names) = class_pattern_names(subject, cls, kwd_names, nargs, this)? { + let tuple = allocate_tuple(names.into_iter().collect(), this.heap); + this.push(tuple); + this.push(Value::Bool(true)); + } else { + this.push(Value::None); + this.push(Value::Bool(false)); + } + Ok(()) + } + + /// `MatchAttr`: `[subject, cls, names] -> [subject, cls, names, value, bool]`. + /// + /// Reads attribute `index` of the names tuple off the subject. A missing + /// attribute fails the match; a host-side attribute suspends with a + /// [`PendingLookupEffect::MatchAttr`] that lands the same pair on resume. + /// A name already read by an earlier index is CPython's + /// `TypeError: Cls() got multiple sub-patterns for attribute 'x'`, raised + /// here rather than up front so a missing earlier attribute still wins. + pub(super) fn match_attr(&mut self, index: usize) -> Result { + let this = self; + let len = this.stack.len(); + let subject = this.stack[len - 3].clone_with_heap(this.heap); + let cls = this.stack[len - 2].clone_with_heap(this.heap); + defer_drop!(subject, this); + defer_drop!(cls, this); + let Value::Ref(names_id) = &this.stack[len - 1] else { + unreachable!("MatchAttr follows a successful MatchClass, which pushed the names tuple") + }; + let HeapReadOutput::Tuple(names) = this.heap.read(*names_id) else { + unreachable!("MatchAttr follows a successful MatchClass, which pushed the names tuple") + }; + let name = names.clone_item(index, this); + defer_drop!(name, this); + let Some(attr) = name.as_either_str(this.heap) else { + // A self-matching builtin: the sub-pattern gets the subject itself. + this.push(subject.clone_with_heap(this.heap)); + return Ok(CallResult::Value(Value::Bool(true))); + }; + for earlier in 0..index { + let earlier = names.clone_item(earlier, this); + defer_drop!(earlier, this); + let repeated = earlier + .as_either_str(this.heap) + .is_some_and(|e| e.as_str(this.interns) == attr.as_str(this.interns)); + if repeated { + let class = class_pattern_name(cls, this); + return Err(ExcType::type_error(format!( + "{class}() got multiple sub-patterns for attribute '{}'", + attr.as_str(this.interns) + ))); + } + } + match subject.py_getattr(&attr, this) { + Ok(CallResult::Value(value)) => { + this.push(value); + Ok(CallResult::Value(Value::Bool(true))) + } + Ok(CallResult::AttrLookup { + name, + class_name, + object_id, + type_object, + effect, + }) => { + effect.drop_with(this); + Ok(CallResult::AttrLookup { + name, + class_name, + object_id, + type_object, + effect: Some(PendingLookupEffect::MatchAttr), + }) + } + Ok(other) => { + other.drop_with(this); + Err(ExcType::type_error(format!( + "class pattern attribute '{}' is not a plain attribute", + attr.as_str(this.interns) + ))) + } + Err(RunError::Exc(exc)) if exc.exc.exc_type() == ExcType::AttributeError => { + this.push(Value::None); + Ok(CallResult::Value(Value::Bool(false))) + } + Err(err) => Err(err), + } + } +} + +/// Looks every key of the `keys` tuple up in the mapping `subject`: the values +/// in key order, or `None` as soon as one key is absent. +/// +/// Keys are checked in order against the ones before them, like CPython's +/// `seen` set: a key equal to an earlier one is a `ValueError`, unless an +/// earlier key was already found missing. Only keys with equal hashes are +/// compared, so large distinct keys never cost a full `==` each. +fn lookup_pattern_keys(subject: &Value, keys: &Value, vm: &mut VM<'_>) -> RunResult>> { + let (Value::Ref(subject_id), Value::Ref(keys_id)) = (subject, keys) else { + return Ok(None); + }; + let (HeapReadOutput::Dict(dict), HeapReadOutput::Tuple(keys)) = (vm.heap.read(*subject_id), vm.heap.read(*keys_id)) + else { + return Ok(None); + }; + let len = keys.get(vm.heap).as_slice().len(); + let mut guard = DropGuard::new(Vec::with_capacity(len), vm); + let (values, vm) = guard.as_parts_mut(); + let mut hashes = Vec::with_capacity(len); + for i in 0..len { + let key = keys.clone_item(i, vm); + defer_drop!(key, vm); + let hash = set_element_hash(key, vm)?; + for earlier in (0..i).filter(|&earlier| hashes[earlier] == hash) { + let earlier = keys.clone_item(earlier, vm); + defer_drop!(earlier, vm); + if earlier.py_eq(key, vm)? { + return Err(ExcType::value_error_duplicate_mapping_key(key, vm)); + } + } + hashes.push(hash); + match dict.dict_get(key, vm)? { + Some(value) => values.push(value), + None => return Ok(None), + } + } + Ok(Some(guard.into_inner())) +} + +/// Builds the `**rest` dict: a plain `dict` copy of `subject` with every key +/// in the `keys` tuple removed. +fn build_rest_dict(subject: &Value, keys: &Value, vm: &mut VM<'_>) -> RunResult { + let (Value::Ref(subject_id), Value::Ref(keys_id)) = (subject, keys) else { + unreachable!("MatchKeys rest mode runs after a successful mapping MatchShape") + }; + let (HeapReadOutput::Dict(dict), HeapReadOutput::Tuple(keys)) = (vm.heap.read(*subject_id), vm.heap.read(*keys_id)) + else { + unreachable!("MatchKeys rest mode runs after a successful mapping MatchShape") + }; + let pairs = dict.clone_all_pairs(vm)?; + let rest = Dict::from_pairs(pairs, vm)?; + let rest_id = vm.heap.allocate(HeapData::Dict(rest)); + let mut guard = DropGuard::new(Value::Ref(rest_id), vm); + let (_, vm) = guard.as_parts(); + let HeapReadOutput::Dict(rest) = vm.heap.read(rest_id) else { + unreachable!("just allocated as a dict") + }; + let len = keys.get(vm.heap).as_slice().len(); + for i in 0..len { + let key = keys.clone_item(i, vm); + defer_drop!(key, vm); + if let Some(removed) = rest.pop(key, vm)? { + removed.drop_with(vm); + } + } + Ok(guard.into_inner()) +} + +/// The attribute names a class pattern reads, as `str` values (`None` for the +/// subject itself), or `None` when the subject is not an instance of `cls`. +fn class_pattern_names( + subject: &Value, + cls: &Value, + kwd_names: &Value, + nargs: usize, + vm: &mut VM<'_>, +) -> RunResult>> { + if !is_class_object(cls, vm) { + return Err(ExcType::type_error("called match pattern must be a class")); + } + if !isinstance_check(subject, cls, vm)? { + return Ok(None); + } + let mut guard = DropGuard::new(Vec::with_capacity(nargs), vm); + let (names, vm) = guard.as_parts_mut(); + if nargs > 0 { + match class_match_args(cls, nargs, vm)? { + MatchArgs::SelfMatch => names.push(Value::None), + MatchArgs::Names(positional) => { + names.extend(positional.iter().map(|name| either_str_value(name, vm.heap))); + } + } + } + let Value::Ref(kwd_id) = kwd_names else { + unreachable!("MatchClass keyword names are a tuple built by the compiler") + }; + let HeapReadOutput::Tuple(kwd_names) = vm.heap.read(*kwd_id) else { + unreachable!("MatchClass keyword names are a tuple built by the compiler") + }; + let len = kwd_names.get(vm.heap).as_slice().len(); + for i in 0..len { + names.push(kwd_names.clone_item(i, vm)); + } + Ok(Some(guard.into_inner())) +} + +/// Whether `value` is something `isinstance` accepts as a single class. +fn is_class_object(value: &Value, vm: &VM<'_>) -> bool { + match value { + Value::Builtin(Builtins::Type(_) | Builtins::ExcType(_)) => true, + Value::Ref(id) => matches!( + vm.heap.get(*id), + HeapData::Class(_) | HeapData::NamedTupleClass(_) | HeapData::HostClassType(_) + ), + _ => false, + } +} + +/// Resolves `cls.__match_args__` for the first `nargs` positional sub-patterns. +/// +/// Builtins carry no `__match_args__`: the self-matching ones accept one +/// positional sub-pattern, the rest none. A namedtuple's are its fields; a +/// user or host class's come from its namespace and must be a tuple of strings +/// (checked only as far as `nargs`, like CPython). Too many positional +/// sub-patterns is reported before a bad element, as CPython does. +fn class_match_args(cls: &Value, nargs: usize, vm: &mut VM<'_>) -> RunResult { + let check_count = |allowed: usize, vm: &VM<'_>| { + if allowed < nargs { + Err(positional_count_error(cls, allowed, nargs, vm)) + } else { + Ok(()) + } + }; + let Value::Ref(cls_id) = cls else { + return match cls { + Value::Builtin(Builtins::Type(t)) if SELF_MATCHING_TYPES.contains(t) => { + check_count(1, vm).map(|()| MatchArgs::SelfMatch) + } + _ => check_count(0, vm).map(|()| MatchArgs::Names(Vec::new())), + }; + }; + let match_args = match vm.heap.get(*cls_id) { + HeapData::NamedTupleClass(class) => { + let fields = class.field_names(); + check_count(fields.len(), vm)?; + return Ok(MatchArgs::Names(fields[..nargs].to_vec())); + } + HeapData::Class(class) => class + .namespace() + .get_by_str("__match_args__", vm.heap, vm.interns) + .map(|value| value.clone_with_heap(vm.heap)), + // A host class only has `__match_args__` if the host sent it as a class attribute. + HeapData::HostClassType(class) => class + .attrs() + .get_by_str("__match_args__", vm.heap, vm.interns) + .map(|value| value.clone_with_heap(vm.heap)), + _ => None, + }; + let Some(match_args) = match_args else { + check_count(0, vm)?; + return Ok(MatchArgs::Names(Vec::new())); + }; + defer_drop!(match_args, vm); + let Value::Ref(args_id) = match_args else { + return Err(match_args_type_error(cls, match_args, vm)); + }; + let HeapReadOutput::Tuple(tuple) = vm.heap.read(*args_id) else { + return Err(match_args_type_error(cls, match_args, vm)); + }; + check_count(tuple.get(vm.heap).as_slice().len(), vm)?; + let mut names = Vec::with_capacity(nargs); + for i in 0..nargs { + let item = tuple.clone_item(i, vm); + defer_drop!(item, vm); + let Some(name) = item.as_either_str(vm.heap) else { + let type_name = item.py_type_name(vm); + return Err(ExcType::type_error(format!( + "__match_args__ elements must be strings (got {type_name})" + ))); + }; + names.push(name); + } + Ok(MatchArgs::Names(names)) +} + +/// An attribute name as a `str` value for the `MatchClass` names tuple. +fn either_str_value(name: &EitherStr, heap: &Heap) -> Value { + match name { + EitherStr::Interned(id) => Value::InternString(*id), + EitherStr::Heap(text) => allocate_string(text.clone(), heap), + } +} + +/// `TypeError: Foo.__match_args__ must be a tuple (got list)`. +fn match_args_type_error(cls: &Value, match_args: &Value, vm: &VM<'_>) -> RunError { + let class = class_pattern_name(cls, vm); + let type_name = match_args.py_type_name(vm); + ExcType::type_error(format!("{class}.__match_args__ must be a tuple (got {type_name})")) +} + +/// `TypeError: Foo() accepts 2 positional sub-patterns (3 given)`. +fn positional_count_error(cls: &Value, allowed: usize, given: usize, vm: &VM<'_>) -> RunError { + let class = class_pattern_name(cls, vm); + let plural = if allowed == 1 { "" } else { "s" }; + ExcType::type_error(format!( + "{class}() accepts {allowed} positional sub-pattern{plural} ({given} given)" + )) +} + +/// The class's `__name__`, as CPython's class pattern errors spell it. +fn class_pattern_name(cls: &Value, vm: &VM<'_>) -> String { + match cls { + Value::Builtin(Builtins::Type(t)) => t.dunder_name(vm.heap, vm.interns).into_owned(), + Value::Builtin(Builtins::ExcType(exc_type)) => { + let qualified = exc_type.to_string(); + qualified.rsplit('.').next().unwrap_or(&qualified).to_owned() + } + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Class(_) => class_name(*id, vm.heap, vm.interns).into_owned(), + HeapData::NamedTupleClass(class) => class.name(vm.interns).to_owned(), + HeapData::HostClassType(class) => class.name(vm.interns).to_owned(), + _ => cls.py_type_name(vm).to_string(), + }, + _ => cls.py_type_name(vm).to_string(), + } +} diff --git a/crates/bashkit-monty/src/bytecode/vm/recursion.rs b/crates/bashkit-monty/src/bytecode/vm/recursion.rs new file mode 100644 index 000000000..0633be5ac --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/recursion.rs @@ -0,0 +1,245 @@ +//! Recursion-depth tracking for the [`VM`]. +//! +//! The recursion counter lives on the `VM` (not the heap) because every site +//! that charges depth — non-frozen call frames, container `repr`/`eq`/`cmp`/`hash`, +//! `isinstance`, json encoding — has a `&mut VM` in scope. Two primitives charge +//! a level: +//! +//! - [`VM::recursion_guard`] for lexically-scoped recursion: an RAII guard that +//! derefs to the VM and releases the level on drop (every path, incl. `?`). +//! - [`VM::incr_recursion`] for reservations that must outlive a lexical scope — +//! notably the container iterators, which store the [`RecursionToken`] so the +//! bound is owned by the iterator and a caller cannot forget to charge it. +//! +//! A stored token can't be released through the heap alone (the heap has no path +//! back to the VM counter), so its [`DropWithContext`] impl is bound by +//! [`ContainsVM`] rather than [`ContainsHeap`], and it is cleaned up through the +//! same `defer_drop!` machinery as any other value. + +use std::ops::{Deref, DerefMut}; + +use monty_types::ResourceError; + +use super::VM; +use crate::{ + heap::{ContainsHeap, DropWithContext}, + intern::{FunctionId, Interns}, +}; + +/// Counts charged frames when restoring a VM or switching tasks. +/// The first frame is the uncharged root; frozen implementation frames never contribute. +pub(super) fn frame_recursion_depth(frames: impl Iterator>, interns: &Interns) -> usize { + frames + .skip(1) + .filter(|id| id.is_none_or(|id| !interns.is_internal_function(id))) + .count() +} + +impl<'h> VM<'h> { + /// Enters a lexically-scoped recursive operation, returning a guard that + /// releases the depth level when dropped. + /// + /// The guard derefs to the VM, so recursive calls run through `&mut *guard`: + /// + /// ```ignore + /// let mut guard = vm.recursion_guard()?; + /// let vm = &mut *guard; + /// // ... recurse through `vm`; the level is released when `guard` drops ... + /// ``` + /// + /// Returns `Err(ResourceError::Recursion)` if the limit would be exceeded. + pub(crate) fn recursion_guard(&mut self) -> Result, ResourceError> { + self.incr_recursion()?; + Ok(RecursionGuard { vm: self }) + } + + /// Reserves one recursion level as a standalone [`RecursionToken`], released + /// via [`DropWithContext`] rather than tied to a lexical scope. + /// + /// Unlike [`recursion_guard`](Self::recursion_guard), the token does not + /// borrow the VM, so it can be stored (e.g. inside a container iterator) and + /// released later with `defer_drop!`. + pub(crate) fn recursion_token(&mut self) -> Result { + self.incr_recursion()?; + Ok(RecursionToken(())) + } + + /// Checks the recursion limit against the heap's tracker and increments the + /// depth counter. + #[inline] + pub(crate) fn incr_recursion(&mut self) -> Result<(), ResourceError> { + self.heap.tracker.check_recursion_depth(self.recursion_depth)?; + self.recursion_depth += 1; + Ok(()) + } + + /// Releases one recursion level. Paired with [`incr_recursion`](Self::incr_recursion); + /// called by the guard/token cleanup and by `pop_frame`. + #[inline] + pub(crate) fn decr_recursion(&mut self) { + debug_assert!(self.recursion_depth > 0, "decr_recursion called when depth is 0"); + self.recursion_depth -= 1; + } +} + +/// RAII guard for a lexically-scoped recursion level (see [`VM::recursion_guard`]). +/// +/// Derefs to the [`VM`] so recursive operations run through the guard; the +/// reserved level is released when the guard is dropped on any code path. +pub(crate) struct RecursionGuard<'a, 'h> { + vm: &'a mut VM<'h>, +} + +impl<'h> Deref for RecursionGuard<'_, 'h> { + type Target = VM<'h>; + fn deref(&self) -> &Self::Target { + self.vm + } +} + +impl DerefMut for RecursionGuard<'_, '_> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.vm + } +} + +impl Drop for RecursionGuard<'_, '_> { + fn drop(&mut self) { + self.vm.decr_recursion(); + } +} + +/// Hard cap on native Rust call-stack re-entry, enforced by +/// [`VM::enter_run_reentry`] and released by [`RunReentryGuard`]. Much smaller +/// than the 1000-frame Python recursion limit because each level costs a real +/// nested call to [`VM::run`], not a switch of the VM's current frame. +/// +/// Tuned conservatively from the smallest native stack observed while fixing +/// recursive callback crashes. A debug monty-datatest worker with an ~2 MiB +/// stack crashed at depth 19 on macOS/arm64; keep this much lower and +/// revalidate on all supported host targets before raising it. +/// +/// A hard safety constant, not a Python-visible setting: unlike ordinary +/// recursion depth, it does not go through the tracker and cannot be changed +/// by sandboxed code or test hooks. +// TODO set this value to custom values per-OS/arch +pub(crate) const MAX_RUN_REENTRY_DEPTH: u8 = 12; + +impl VM<'_> { + /// Charges one native re-entry level, counting the remaining budget down + /// from [`MAX_RUN_REENTRY_DEPTH`]; errors when it's exhausted. Pair with + /// [`RunReentryGuard::new`] to release the level on every exit path. + /// + /// Split into a plain `Result<(), _>` check (unlike + /// [`recursion_guard`](Self::recursion_guard)'s combined check-and-wrap) so + /// `evaluate_function` can `if let Err(e) = ...` it and run its own cleanup + /// (dropping owned arguments) without a `Drop` guard extending `self`'s + /// borrow across the match. Bypasses the tracker: a fixed safety constant, + /// not a user-configurable limit. + #[inline] + pub(crate) fn enter_run_reentry(&mut self) -> Result<(), ResourceError> { + if let Some(new_value) = self.run_reentry_depth.checked_sub(1) { + self.run_reentry_depth = new_value; + Ok(()) + } else { + Err(ResourceError::Recursion { + limit: MAX_RUN_REENTRY_DEPTH as usize, + depth: MAX_RUN_REENTRY_DEPTH as usize, + }) + } + } + + /// Releases one native re-entry level. Paired with + /// [`enter_run_reentry`](Self::enter_run_reentry); called only by + /// [`RunReentryGuard`]'s `Drop` impl. + #[inline] + pub(crate) fn release_run_reentry(&mut self) { + debug_assert!( + self.run_reentry_depth < MAX_RUN_REENTRY_DEPTH, + "release_run_reentry called when depth is MAX_RUN_REENTRY_DEPTH" + ); + self.run_reentry_depth += 1; + } +} + +/// RAII guard for one level of native `run()` re-entry, wrapping a level +/// already reserved via [`VM::enter_run_reentry`]. +/// +/// Derefs to the [`VM`] so the nested `call_function`/`run()` call runs +/// through the guard; the reserved level is released when the guard is +/// dropped on any code path (normal return, `?`, or early return). +/// +/// Dropping it also restores `instruction_ip`: the nested run leaves it on the +/// next instruction, and a suspension the outer instruction makes afterwards +/// must report the outer instruction's position. +pub(crate) struct RunReentryGuard<'a, 'h> { + vm: &'a mut VM<'h>, + /// The outer instruction's `instruction_ip`, restored on drop. + instruction_ip: usize, +} + +impl<'a, 'h> RunReentryGuard<'a, 'h> { + /// Wraps a re-entry level already charged by a prior + /// [`VM::enter_run_reentry`] call. + pub(crate) fn new(vm: &'a mut VM<'h>) -> Self { + let instruction_ip = vm.instruction_ip; + Self { vm, instruction_ip } + } +} + +impl<'h> Deref for RunReentryGuard<'_, 'h> { + type Target = VM<'h>; + fn deref(&self) -> &Self::Target { + self.vm + } +} + +impl DerefMut for RunReentryGuard<'_, '_> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.vm + } +} + +impl Drop for RunReentryGuard<'_, '_> { + fn drop(&mut self) { + self.vm.instruction_ip = self.instruction_ip; + self.vm.release_run_reentry(); + } +} + +/// Zero-size reservation of one recursion level, returned by [`VM::incr_recursion`]. +/// +/// Released via [`DropWithContext`] (it cannot reach the VM counter through the heap). +/// Stored by container iterators so the depth bound is owned by the iterator and +/// released on every exit path via `defer_drop!`. +pub(crate) struct RecursionToken(()); + +/// Accessor for the [`VM`] behind a cleanup context — the VM-capable extension of +/// [`ContainsHeap`](crate::heap::ContainsHeap). +/// +/// Implemented by the [`VM`] itself and by wrappers that own a `&mut VM` (the json +/// `Encoder`). A [`DropWithContext`] impl bounds its context `C` by `ContainsVM` +/// (rather than just `ContainsHeap`) when it must reach the VM-side recursion +/// counter — e.g. dropping a [`RecursionToken`] — while a wrapper like the encoder +/// stays borrowable through the same handle. Because `ContainsVM: ContainsHeap`, +/// such a context can still drop plain heap fields via `drop_with(ctx)`. +pub(crate) trait ContainsVM<'h>: ContainsHeap { + fn vm(&mut self) -> &mut VM<'h>; +} + +impl<'h> ContainsVM<'h> for VM<'h> { + fn vm(&mut self) -> &mut Self { + self + } +} + +/// A [`RecursionToken`] releases its reserved level through any [`ContainsVM`] +/// context. The `C: ContainsVM<'h>` bound (rather than `ContainsHeap`) is what +/// confines token cleanup to a `VM`/`Encoder` — a bare heap cannot reach the +/// counter — and there is no overlap with the heap-only impls because those are +/// for different `Self` types. +impl<'h, C: ContainsVM<'h>> DropWithContext for RecursionToken { + fn drop_with(self, ctx: &mut C) { + ctx.vm().decr_recursion(); + } +} diff --git a/crates/bashkit-monty/src/bytecode/vm/scheduler.rs b/crates/bashkit-monty/src/bytecode/vm/scheduler.rs new file mode 100644 index 000000000..873d7b4b0 --- /dev/null +++ b/crates/bashkit-monty/src/bytecode/vm/scheduler.rs @@ -0,0 +1,434 @@ +//! Task scheduler for async execution and call ID allocation. +//! +//! # Task Model +//! +//! The current task's context lives in the VM; all other contexts live in their tasks. +//! Task 0 is the main task. Spawned tasks (1+) deliver results to their gather. + +use std::{collections::VecDeque, mem}; + +use ahash::AHashMap; +use smallvec::{SmallVec, smallvec}; + +use super::{FrameNamespace, exceptions::CaughtException}; +use crate::{ + asyncio::{Awaiter, CallId, TaskId}, + exception_private::RunResult, + heap::{ContainsHeap, DropWithContext, Heap, HeapId, HeapReadOutput, HeapReader}, + intern::{FunctionId, StringId}, + value::Value, +}; + +/// Live tasks are runnable or blocked; completion removes the task from the scheduler. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +enum TaskState { + /// Queued or currently executing. `Err` must be raised before executing more bytecode. + Ready(RunResult<()>), + /// Owns an inc_ref on the awaitable; its awaiter identifies the task to wake. + Blocked(HeapId), +} + +impl DropWithContext for TaskState { + fn drop_with(self, heap: &mut C) { + match self { + Self::Ready(_) => {} + Self::Blocked(id) => heap.heap_mut().dec_ref(id), + } + } +} + +/// A live async task. Its execution context is saved here while another task runs. +/// The current task's frames and stacks live in the VM, including for the main task. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct Task { + /// Unique identifier for this task. + pub id: TaskId, + /// Saved frames; empty while this task is current or has not started. + pub frames: Vec, + /// Saved operand stack; the current task uses the VM's stack. + pub stack: Vec, + /// Exception stack for nested except blocks. + pub exception_stack: Vec, + /// VM-level instruction_ip (for exception table lookup). + pub instruction_ip: usize, + /// Owned coroutine reference for a spawned task; the main task has none. + pub coroutine_id: Option, + /// Result recipient, owning an inc_ref for a gather. An already-settled gather + /// discards the result. The main task has no awaiter. + pub awaiter: Option, + /// Current execution state. + state: TaskState, +} + +impl DropWithContext for Task { + fn drop_with(mut self, heap: &mut C) { + self.stack.drain(..).drop_with(heap); + self.exception_stack.drain(..).drop_with(heap); + for frame in self.frames.drain(..) { + frame.namespace.drop_with(heap); + } + self.state.drop_with(heap); + if let Some(coro_id) = self.coroutine_id.take() { + heap.heap_mut().dec_ref(coro_id); + } + if let Some(awaiter) = self.awaiter.take() { + awaiter.drop_with(heap); + } + } +} + +/// Serialized call frame for task storage. +/// +/// Similar to `SerializedFrame` but used within the scheduler for task context. +/// Cannot store `&Code` references - uses `FunctionId` to look up code on resume. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct SerializedTaskFrame { + /// Which function's code this frame executes (None = module-level). + pub function_id: Option, + /// Instruction pointer within this frame's bytecode. + pub ip: usize, + /// Base index into the VM stack for this frame's locals region. + pub stack_base: usize, + /// Number of local variable slots (0 for module-level frames). + pub locals_count: u16, + /// Base index into the VM-wide `exception_stack` for this frame. + /// See `CallFrame.exception_stack_base`. + pub exception_stack_base: usize, + /// Caller's bytecode offset at the call site (for tracebacks). See + /// `CallFrame.call_offset`. + pub call_offset: Option, + /// Whether this frame is a class `__init__` (see `CallFrame.is_initializer`). + pub is_initializer: bool, + /// Frame namespace, owning its dict references (see `CallFrame.namespace`). + pub namespace: Option>, + /// The `from ... import` in progress, if the frame parked inside one. + #[serde(default)] + pub import_from_module: Option, +} + +impl Task { + /// Creates a runnable task, taking ownership of its coroutine and awaiter references. + pub fn new(id: TaskId, coroutine_id: Option, awaiter: Option) -> Self { + Self { + id, + frames: Vec::new(), + stack: Vec::new(), + exception_stack: Vec::new(), + instruction_ip: 0, + coroutine_id, + awaiter, + state: TaskState::Ready(Ok(())), + } + } +} + +/// Owns live tasks, pending external futures, and call IDs for both sync and async execution. +/// A blocked task is queued once when its awaitable settles, for either a value or an error. +/// Selecting that task consumes its queue entry and resume result before bytecode can run. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct Scheduler { + /// All tasks keyed by their `TaskId`. + tasks: AHashMap, + /// Tasks ready to execute or raise a pending exception. + ready_queue: VecDeque, + /// Task whose context is in the VM, or `None` when that context has been discarded. + current_task: Option, + /// Counter for generating new task IDs. + next_task_id: u32, + /// Counter for external call IDs (always incremented, even for sync resolution). + next_call_id: u32, + /// Host-side index mapping each unresolved external call to its + /// `HeapData::ExternalFuture` entry. The scheduler holds an inc_ref on + /// each value until the host resolves or fails the call — that ref keeps + /// the future entry alive between yield and resume even if no awaiter is + /// holding a `Value::Ref` to it. + pending_externals: AHashMap, + /// Index mapping a spawned coroutine's `HeapId` to the `TaskId` driving + /// it. Populated in [`Scheduler::spawn`] and removed in + /// [`Scheduler::cancel_task`]. Lets `GatherFuture` and other call sites + /// dispatch from coroutine heap id back to the driving task without + /// scanning all tasks. + coroutine_to_task: AHashMap, +} + +impl Scheduler { + /// Creates the main task as current; it needs no queue entry to start executing. + pub fn new() -> Self { + let main_task_id = TaskId::default(); + let main_task = Task::new(main_task_id, None, None); + let mut tasks = AHashMap::new(); + tasks.insert(main_task_id, main_task); + Self { + tasks, + ready_queue: VecDeque::new(), // Main task is current, not in ready queue + current_task: Some(main_task_id), + next_task_id: 1, + next_call_id: 0, + pending_externals: AHashMap::new(), + coroutine_to_task: AHashMap::new(), + } + } + + /// Identifies the VM's loaded context, even when that task is blocked on a host call. + #[inline] + pub fn current_task_id(&self) -> Option { + self.current_task + } + + /// Whether awaiting the current call can proceed without delaying other work. + pub fn can_await_eagerly(&self) -> bool { + self.ready_queue.is_empty() && self.pending_externals.is_empty() + } + + /// Returns the main task, whose context is saved here whenever another + /// task is loaded; `None` once it has been cancelled. + pub fn main_task(&self) -> Option<&Task> { + self.tasks.get(&TaskId::default()) + } + + /// Returns a mutable reference to a task by ID. + /// + /// # Panics + /// Panics if the task ID doesn't exist. + #[inline] + pub fn get_task_mut(&mut self, task_id: TaskId) -> &mut Task { + self.tasks + .get_mut(&task_id) + .expect("Scheduler::get_task_mut: task not found") + } + + /// Allocates a new CallId for an external function call. + /// + /// The counter always increments, even for sync resolution, to keep IDs unique. + pub fn allocate_call_id(&mut self) -> CallId { + let id = CallId::new(self.next_call_id); + self.next_call_id += 1; + id + } + + /// Registers a freshly created `ExternalFuture` for `call_id`. + /// + /// The scheduler inc_refs `future_id` so the entry stays alive between + /// the yield to the host and the matching `resolve_future` / `fail_future` + /// call, even if no awaiter holds a `Value::Ref` to it. + pub fn add_pending_external(&mut self, call_id: CallId, future_id: HeapId, heap: &Heap) { + heap.inc_ref(future_id); + let prev = self.pending_externals.insert(call_id, future_id); + debug_assert!(prev.is_none(), "add_pending_external: CallId already registered"); + } + + /// Removes and returns the `ExternalFuture` heap id for `call_id`, if any. + /// + /// The caller becomes responsible for the inc_ref previously held by the + /// scheduler (typically dec_ref'd once the state transition is committed). + pub fn take_pending_external(&mut self, call_id: CallId) -> Option { + self.pending_externals.remove(&call_id) + } + + /// Marks the current task as `Blocked` on the awaitable at `awaitable_id`. + /// + /// The task will be unblocked when the awaitable settles and its awaiter + /// slot routes back here (`Awaiter::Task(task_id)` on either + /// `ExternalFuture::Pending` or `AwaitedGather`). + pub fn block_current_on(&mut self, awaitable_id: HeapId, heap: &Heap) { + if let Some(task_id) = self.current_task { + let task = self.get_task_mut(task_id); + debug_assert!(matches!(task.state, TaskState::Ready(Ok(())))); + heap.inc_ref(awaitable_id); + task.state = TaskState::Blocked(awaitable_id); + } + } + + /// Returns all pending (unresolved) CallIds. + pub fn pending_call_ids(&self) -> Vec { + self.pending_externals.keys().copied().collect() + } + + /// Removes the queue entry when delivering directly to an exiting task's waiter. + pub fn remove_from_ready_queue(&mut self, task_id: TaskId) { + self.ready_queue.retain(|&id| id != task_id); + } + + /// Spawns a new task from a coroutine, enforcing one-task-per-coroutine. + /// + /// Returns `None` if `coroutine_id` is already driving a task — + /// caught here because cross-gather reuse can hit two spawns while + /// both coroutine states are still `New`, so the state check in + /// `await_coroutine` doesn't catch it. Callers translate `None` + /// into a `RuntimeError: cannot reuse already awaited coroutine`. + /// Both `coroutine_id` and the `GatherSlot` built from `gather_id` become + /// **owning** references held by the new task; the matching `dec_ref` + /// happens in [`Scheduler::cancel_task`]. It takes `gather_id` rather than + /// a ready-made `Awaiter` so the `None` return above has nothing to unwind. + pub fn spawn(&mut self, heap: &Heap, coroutine_id: HeapId, gather_id: Option) -> Option { + if self.coroutine_to_task.contains_key(&coroutine_id) { + return None; + } + + let task_id = TaskId::new(self.next_task_id); + self.next_task_id += 1; + + // Take ownership of the heap references — the task now holds an inc_ref'd + // pointer to its coroutine and (if applicable) its enclosing gather. + // The slot is keyed by the coroutine's own id, which is what + // `resolve_child` looks up. + heap.inc_ref(coroutine_id); + let awaiter = gather_id.map(|gather| { + heap.inc_ref(gather); + Awaiter::GatherSlot { + gather, + source: coroutine_id, + } + }); + + let task = Task::new(task_id, Some(coroutine_id), awaiter); + self.tasks.insert(task_id, task); + self.coroutine_to_task.insert(coroutine_id, task_id); + self.ready_queue.push_back(task_id); + + Some(task_id) + } + + /// Gets the next ready task from the queue. + /// + /// Returns `None` if no tasks are ready. + pub fn next_ready_task(&mut self) -> Option { + self.ready_queue.pop_front() + } + + /// Wakes a blocked task with a value already on its stack, or an exception to raise. + pub fn make_ready(&mut self, task_id: TaskId, result: RunResult<()>, heap: &mut Heap) { + let task = self.get_task_mut(task_id); + debug_assert!(matches!(task.state, TaskState::Blocked(_))); + let old_state = mem::replace(&mut task.state, TaskState::Ready(result)); + old_state.drop_with(heap); + self.ready_queue.push_back(task_id); + } + + /// Takes the selected task's resume result exactly once, before executing its context. + pub fn take_resume_result(&mut self, task_id: TaskId) -> RunResult<()> { + match &mut self.get_task_mut(task_id).state { + TaskState::Ready(result) => mem::replace(result, Ok(())), + TaskState::Blocked(_) => panic!("cannot resume a blocked task"), + } + } + + /// Sets the current task. + pub fn set_current_task(&mut self, task_id: Option) { + self.current_task = task_id; + } + + /// Removes a task and releases its saved context and heap references. + /// Cancels tasks under any gather it is still blocked on, using an iterative walk + /// so deeply nested gathers cannot overflow the native stack during teardown. + pub fn cancel_task(&mut self, task_id: TaskId, heap: &mut HeapReader<'_>) { + let mut pending: SmallVec<[TaskId; 4]> = smallvec![task_id]; + while let Some(task_id) = pending.pop() { + self.cancel_one(task_id, heap, &mut pending); + } + } + + /// Cancels one task, queueing the tasks spawned under any gather it was + /// blocked on for [`Scheduler::cancel_task`] to drain. + /// + /// Dropping this task ahead of the children it queued is sound: each owns + /// an inc_ref on that same gather (see [`Scheduler::spawn`]). + fn cancel_one(&mut self, task_id: TaskId, heap: &mut HeapReader<'_>, pending: &mut SmallVec<[TaskId; 4]>) { + // No-op if the task has already been removed (idempotent — finalization + // sites may iterate task ids that include already-cancelled siblings). + let Some(task) = self.tasks.remove(&task_id) else { + return; + }; + + // The VM must discard this task's loaded context before activating another task. + if self.current_task == Some(task_id) { + self.current_task = None; + } + + if let Some(coroutine_id) = task.coroutine_id { + self.coroutine_to_task.remove(&coroutine_id); + } + + self.ready_queue.retain(|&id| id != task_id); + + // Blocked on a gather: queue the tasks spawned under it. An + // external future needs no extra teardown. + if let TaskState::Blocked(blocked_id) = task.state { + self.queue_gather_tasks(blocked_id, heap, pending); + } + + task.drop_with(heap); + } + + /// Queues every task spawned under the gather `root`, walking nested + /// gathers iteratively. + /// + /// A gather item can itself be a gather (`gather(gather(coro()))`), whose + /// tasks are just as orphaned as direct coroutine children if left in + /// `self.tasks` — they would keep running and then deliver a result to the + /// task cancelled here. External children *are* left alone: the owning + /// `Awaiter::GatherSlot` anchors them. + /// + /// Must run while the cancelled task still holds its `Blocked` inc_ref on + /// `root`, since the walk takes no references of its own: each nested + /// gather is kept alive by its parent's `items`, and the parent in turn by + /// the `Awaiter::GatherSlot` inc_ref that nested child holds. + fn queue_gather_tasks(&self, root: HeapId, heap: &HeapReader<'_>, pending: &mut SmallVec<[TaskId; 4]>) { + // Gathers nest as a tree — a gather may only be awaited once, so the + // walk cannot revisit a node and terminates. + let mut gathers: SmallVec<[HeapId; 4]> = smallvec![root]; + while let Some(gather_id) = gathers.pop() { + // Coroutine and external children land here too; only gathers have + // children of their own to walk. + let HeapReadOutput::GatherFuture(gather) = heap.read(gather_id) else { + continue; + }; + if let Some(awaited) = gather.get(heap).as_awaited() { + for child_id in awaited.pending_children.keys() { + match self.coroutine_to_task.get(child_id) { + Some(&task_id) => pending.push(task_id), + None => gathers.push(*child_id), + } + } + } + drop(gather); + } + } + + /// Whether this task still exists and is waiting for an awaitable to settle. + #[inline] + pub fn is_blocked(&self, task_id: TaskId) -> bool { + self.tasks + .get(&task_id) + .is_some_and(|task| matches!(task.state, TaskState::Blocked(_))) + } + + /// Number of tasks the scheduler still holds. + /// + /// Test-only: a task whose await has already failed must not stay parked, + /// and a finished run tears the scheduler down, so this count while + /// suspended is the only way a test can see one. + #[cfg(feature = "test-hooks")] + pub fn task_count(&self) -> usize { + self.tasks.len() + } + + /// Cleans up all scheduler resources: the pending-future inc_refs and + /// every remaining task (via [`Scheduler::cancel_task`]). + pub fn cleanup(&mut self, heap: &mut HeapReader<'_>) { + // Release the inc_refs the scheduler holds on each pending future. + for (_, future_id) in mem::take(&mut self.pending_externals) { + heap.dec_ref(future_id); + } + let task_ids: Vec = self.tasks.keys().copied().collect(); + for task_id in task_ids { + self.cancel_task(task_id, heap); + } + } +} + +impl Default for Scheduler { + fn default() -> Self { + Self::new() + } +} diff --git a/crates/bashkit-monty/src/codecs.rs b/crates/bashkit-monty/src/codecs.rs new file mode 100644 index 000000000..0b4b5c3d8 --- /dev/null +++ b/crates/bashkit-monty/src/codecs.rs @@ -0,0 +1,606 @@ +//! Text codec registry and implementations backing `str.encode()` and +//! `bytes.decode()`. +//! +//! Monty implements a fixed, small set of codecs (UTF-8, ASCII, UTF-16 and +//! UTF-32 families) rather than CPython's full `codecs`/`encodings` registry. +//! [`Codec::find`] resolves user-supplied encoding names using CPython's +//! normalization rules and alias table; [`Codec::encode`] / [`Codec::decode`] +//! implement the conversions with CPython-matching error handler semantics +//! and exception messages. Divergences are documented in +//! `limitations/encoding.md` — most notably the `surrogateescape` / +//! `surrogatepass` decode handlers, which would put lone surrogates in the +//! result and therefore raise `NotImplementedError` (Monty strings are strict +//! UTF-8). + +use std::{ + fmt::{self, Write}, + str, +}; + +use monty_types::ResourceTracker; +pub use monty_types::utf8_error_reason; + +use crate::{ + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + string_builder::StringBuilder, +}; + +/// A supported text codec, resolved from a user-supplied encoding name via +/// [`Codec::find`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Codec { + Utf8, + Ascii, + /// `None` is the bare `utf-16` variant: encode prepends a BOM, decode + /// consumes one (defaulting to little-endian when absent — see + /// `limitations/encoding.md`). `Some` variants never touch a BOM. + Utf16(Option), + /// Same BOM semantics as [`Codec::Utf16`], with 4-byte units. + Utf32(Option), +} + +/// Byte order for the UTF-16/UTF-32 codec families. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Endian { + Little, + Big, +} + +impl Codec { + /// Resolves an encoding name to a codec, applying CPython's name + /// normalization and the alias table from `Lib/encodings/aliases.py` + /// (restricted to the codecs Monty supports). Returns `None` for unknown + /// names — the caller raises `LookupError` with the *original* name. + pub(crate) fn find(name: &str) -> Option { + // Fast path for the exact spellings virtually all callers use — + // including the `"utf-8"` default of `str.encode`/`bytes.decode` — + // so the hot path skips `normalize_encoding`'s String allocation. + match name { + "utf-8" | "utf8" => Some(Self::Utf8), + "ascii" => Some(Self::Ascii), + "utf-16" => Some(Self::Utf16(None)), + "utf-32" => Some(Self::Utf32(None)), + _ => Self::find_normalized(name), + } + } + + /// Slow path of [`Codec::find`]: normalizes `name` (allocating) and + /// matches it against the normalized names and aliases. + fn find_normalized(name: &str) -> Option { + match normalize_encoding(name).as_str() { + "utf_8" | "utf8" | "utf" | "u8" | "cp65001" | "utf8_ucs2" | "utf8_ucs4" => Some(Self::Utf8), + "ascii" | "646" | "us" | "us_ascii" | "cp367" | "ibm367" | "csascii" | "ansi_x3.4_1968" + | "ansi_x3_4_1968" | "ansi_x3.4_1986" | "iso646_us" | "iso_646.irv_1991" | "iso_ir_6" => Some(Self::Ascii), + "utf_16" | "u16" | "utf16" => Some(Self::Utf16(None)), + "utf_16_le" | "utf_16le" | "unicodelittleunmarked" => Some(Self::Utf16(Some(Endian::Little))), + "utf_16_be" | "utf_16be" | "unicodebigunmarked" => Some(Self::Utf16(Some(Endian::Big))), + "utf_32" | "u32" | "utf32" => Some(Self::Utf32(None)), + "utf_32_le" | "utf_32le" => Some(Self::Utf32(Some(Endian::Little))), + "utf_32_be" | "utf_32be" => Some(Self::Utf32(Some(Endian::Big))), + _ => None, + } + } + + /// Encodes `s` to bytes. The `errors` handler name is validated lazily — + /// only consulted when a character actually can't be encoded, matching + /// CPython's `codecs.lookup_error` semantics. Only the ASCII codec can + /// fail: UTF-8 is the native representation, and every Monty string is + /// encodable as UTF-16/32 (no lone surrogates can exist). + /// + /// Like [`Codec::decode`], output is bounded by a small constant multiple + /// of the (already resource-tracked) input — ≤2x for UTF-16, ≤4x for + /// UTF-32, plus a BOM — so those paths need no tracked builder; only the + /// ASCII error handlers can amplify further, and they build through the + /// tracker. + pub(crate) fn encode(self, s: &str, errors: &str, tracker: &ResourceTracker) -> RunResult> { + match self { + Self::Utf8 => Ok(s.as_bytes().to_vec()), + Self::Ascii => encode_ascii(s, errors, tracker), + // Bare utf-16/utf-32 write a BOM and use little-endian (CPython + // uses the platform's native order — identical on all LE hosts). + Self::Utf16(endian) => Ok(encode_utf16(s, endian.unwrap_or(Endian::Little), endian.is_none())), + Self::Utf32(endian) => Ok(encode_utf32(s, endian.unwrap_or(Endian::Little), endian.is_none())), + } + } + + /// Decodes `bytes` to a string. The `errors` handler name is validated + /// lazily, as in [`Codec::encode`]. + /// + /// Every decode path bounds its output by a small constant multiple of + /// the (already resource-tracked) input — at most 4x, from + /// `backslashreplace`'s `\xNN` escape per byte — so plain `String` + /// accumulators are safe without `StringBuilder` tracking. + pub(crate) fn decode(self, bytes: &[u8], errors: &str) -> RunResult { + match self { + Self::Utf8 => decode_utf8(bytes, errors), + Self::Ascii => decode_ascii(bytes, errors), + Self::Utf16(Some(endian)) => decode_utf16(bytes, 0, endian, errors), + Self::Utf32(Some(endian)) => decode_utf32(bytes, 0, endian, errors), + // The bare variants consume a leading BOM and adopt its byte + // order; with no BOM, CPython assumes the platform's native order + // while Monty always uses little-endian for cross-platform + // determinism (see limitations/encoding.md). Error positions are + // offsets into the full input, so the payload start index is + // passed through rather than slicing the BOM off. + Self::Utf16(None) => match bytes { + [0xFF, 0xFE, ..] => decode_utf16(bytes, 2, Endian::Little, errors), + [0xFE, 0xFF, ..] => decode_utf16(bytes, 2, Endian::Big, errors), + _ => decode_utf16(bytes, 0, Endian::Little, errors), + }, + Self::Utf32(None) => match bytes { + [0xFF, 0xFE, 0x00, 0x00, ..] => decode_utf32(bytes, 4, Endian::Little, errors), + [0x00, 0x00, 0xFE, 0xFF, ..] => decode_utf32(bytes, 4, Endian::Big, errors), + _ => decode_utf32(bytes, 0, Endian::Little, errors), + }, + } + } +} + +/// Normalizes an encoding name for lookup, mirroring the combination of +/// CPython's C-level lower-casing and `encodings.normalize_encoding`: +/// ASCII-lowercase; collapse each run of non-alphanumeric characters to a +/// single `_` (dropping leading/trailing runs); keep `.` (needed for aliases +/// like `iso_646.irv_1990`); drop non-ASCII characters. +fn normalize_encoding(name: &str) -> String { + let mut out = String::with_capacity(name.len()); + let mut pending_sep = false; + for c in name.chars() { + if c.is_alphanumeric() || c == '.' { + if pending_sep && !out.is_empty() { + out.push('_'); + } + pending_sep = false; + if c.is_ascii() { + out.push(c.to_ascii_lowercase()); + } + } else { + pending_sep = true; + } + } + out +} + +// ============================================================================ +// Error handlers +// ============================================================================ + +/// CPython's built-in error handler names. Custom handlers +/// (`codecs.register_error`) don't exist in Monty — there is no `codecs` +/// module — so this set is closed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ErrorHandler { + Strict, + Ignore, + Replace, + Backslashreplace, + Xmlcharrefreplace, + Namereplace, + Surrogateescape, + Surrogatepass, +} + +impl ErrorHandler { + /// Resolves a handler name, raising CPython's + /// `LookupError: unknown error handler name '{name}'` for unknown names. + fn lookup(name: &str) -> RunResult { + match name { + "strict" => Ok(Self::Strict), + "ignore" => Ok(Self::Ignore), + "replace" => Ok(Self::Replace), + "backslashreplace" => Ok(Self::Backslashreplace), + "xmlcharrefreplace" => Ok(Self::Xmlcharrefreplace), + "namereplace" => Ok(Self::Namereplace), + "surrogateescape" => Ok(Self::Surrogateescape), + "surrogatepass" => Ok(Self::Surrogatepass), + _ => Err(ExcType::lookup_error_unknown_error_handler(name)), + } + } +} + +/// Lazily-resolved error handler: the name is only looked up (and validated) +/// on the first actual encode/decode error, matching CPython's lazy +/// `codecs.lookup_error` — `b'ok'.decode('ascii', 'bogus')` succeeds because +/// the handler is never needed. Caches the result so repeated errors don't +/// re-match the name. +struct LazyHandler<'a> { + name: &'a str, + cached: Option, +} + +impl<'a> LazyHandler<'a> { + fn new(name: &'a str) -> Self { + Self { name, cached: None } + } + + fn get(&mut self) -> RunResult { + if let Some(handler) = self.cached { + Ok(handler) + } else { + let handler = ErrorHandler::lookup(self.name)?; + self.cached = Some(handler); + Ok(handler) + } + } +} + +/// Applies a decode error handler to one undecodable unit `bad` (a maximal +/// UTF-8 subpart, a UTF-16/32 code unit, or a single non-ASCII byte), +/// appending any substitution to `out`. +/// +/// `is_surrogate` says whether `surrogatepass` would successfully decode this +/// unit to a lone surrogate in CPython: if so Monty raises +/// `NotImplementedError` (lone surrogates are unrepresentable), otherwise +/// `surrogatepass` re-raises the strict error exactly like CPython. +/// `strict_err` builds the codec-specific `UnicodeDecodeError`. +fn handle_decode_error( + handler: ErrorHandler, + bad: &[u8], + out: &mut String, + is_surrogate: bool, + strict_err: impl FnOnce() -> RunError, +) -> RunResult<()> { + match handler { + ErrorHandler::Strict => Err(strict_err()), + ErrorHandler::Ignore => Ok(()), + ErrorHandler::Replace => { + out.push('\u{FFFD}'); + Ok(()) + } + ErrorHandler::Backslashreplace => { + for &byte in bad { + write!(out, "\\x{byte:02x}").expect("writing to a String is infallible"); + } + Ok(()) + } + // Encode-only handlers: CPython's real callbacks raise TypeError when + // invoked for a decode error. + ErrorHandler::Xmlcharrefreplace | ErrorHandler::Namereplace => Err(ExcType::type_error_decode_error_callback()), + ErrorHandler::Surrogateescape => Err(ExcType::not_implemented_surrogate_handler_decode("surrogateescape")), + ErrorHandler::Surrogatepass => { + if is_surrogate { + Err(ExcType::not_implemented_surrogate_handler_decode("surrogatepass")) + } else { + Err(strict_err()) + } + } + } +} + +// ============================================================================ +// ASCII +// ============================================================================ + +/// Encodes `s` as ASCII bytes, applying `errors` to any non-ASCII characters. +/// +/// `ignore`, `replace`, `backslashreplace`, `xmlcharrefreplace`, and +/// `namereplace` substitute, while `strict`, `surrogateescape`, and +/// `surrogatepass` raise `UnicodeEncodeError` — the latter two only +/// special-case lone surrogates, which a Monty string (strict UTF-8) can +/// never contain, so they re-raise exactly like `strict`, matching CPython. +/// +/// Builds into a tracker-protected [`StringBuilder`] rather than a `Vec` — +/// every byte pushed is itself valid ASCII, so the accumulator is always valid +/// UTF-8 and `into_bytes()` at the end is free. The tracking matters because +/// `namereplace` amplifies a single character into up to ~90 bytes +/// (`\N{LONGEST UNICODE NAME...}`), so an untracked accumulator could grow +/// far past the memory limit before the final allocation was checked. +fn encode_ascii(s: &str, errors: &str, tracker: &ResourceTracker) -> RunResult> { + // Fast path for the overwhelmingly common all-ASCII case: `is_ascii` is + // SIMD-vectorized in std, and the output is byte-for-byte the (already + // tracked) input, so a bulk copy needs no StringBuilder. + if s.is_ascii() { + return Ok(s.as_bytes().to_vec()); + } + let mut handler = LazyHandler::new(errors); + let mut out = StringBuilder::with_capacity(s.len(), tracker)?; + let mut chars = s.chars().enumerate().peekable(); + while let Some((idx, c)) = chars.next() { + if c.is_ascii() { + out.push(c)?; + continue; + } + match handler.get()? { + ErrorHandler::Ignore => {} + ErrorHandler::Replace => out.push('?')?, + // A failed `write!` stashes the tracker error on the builder and + // short-circuits later writes; `finish_raw` below surfaces it. + ErrorHandler::Backslashreplace => { + let _ = write_backslash_escape(&mut out, c); + } + ErrorHandler::Xmlcharrefreplace => { + let _ = write!(out, "&#{};", c as u32); + } + ErrorHandler::Namereplace => { + // Characters without a Unicode name (e.g. C1 controls) fall + // back to backslash escapes, matching CPython. + let _ = match unicode_names2::name(c) { + Some(name) => write!(out, "\\N{{{name}}}"), + None => write_backslash_escape(&mut out, c), + }; + } + // surrogateescape/surrogatepass only substitute lone surrogates, + // which can't occur here, so they re-raise like strict. + ErrorHandler::Strict | ErrorHandler::Surrogateescape | ErrorHandler::Surrogatepass => { + // CPython reports a single position for a lone bad character, + // but merges a contiguous run of unencodable characters into + // one `position start-end` range. + let mut end = idx + 1; + while let Some(&(_, next_c)) = chars.peek() { + if next_c.is_ascii() { + break; + } + chars.next(); + end += 1; + } + return Err(ExcType::unicode_encode_error( + "ascii", + s, + c, + idx, + end, + "ordinal not in range(128)", + )); + } + } + } + Ok(out.finish_raw()?.into_bytes()) +} + +/// Writes the `backslashreplace` escape for a non-ASCII character: `\xNN` for +/// codepoints <= 0xFF, `\uNNNN` up to the BMP, `\UNNNNNNNN` beyond. Shared by +/// the `backslashreplace` handler and `namereplace`'s unnamed-character +/// fallback in [`encode_ascii`]. +fn write_backslash_escape(out: &mut impl fmt::Write, c: char) -> fmt::Result { + let code = c as u32; + if code <= 0xFF { + write!(out, "\\x{code:02x}") + } else if code <= 0xFFFF { + write!(out, "\\u{code:04x}") + } else { + write!(out, "\\U{code:08x}") + } +} + +/// Decodes `bytes` as ASCII text, applying `errors` to any byte >= 0x80. +/// `surrogatepass` re-raises like `strict` (with the ASCII codec it only +/// special-cases surrogate sequences in the UTF codecs), matching CPython. +fn decode_ascii(bytes: &[u8], errors: &str) -> RunResult { + // Fast path for the overwhelmingly common all-clean case: `is_ascii` is + // SIMD-vectorized in std, and all-ASCII bytes are valid UTF-8 as-is. + if bytes.is_ascii() { + return Ok(str::from_utf8(bytes) + .expect("all-ASCII bytes are valid UTF-8") + .to_owned()); + } + let mut handler = LazyHandler::new(errors); + let mut out = String::with_capacity(bytes.len()); + for (idx, &byte) in bytes.iter().enumerate() { + if byte.is_ascii() { + out.push(byte as char); + } else { + handle_decode_error(handler.get()?, &bytes[idx..=idx], &mut out, false, || { + ExcType::unicode_decode_error("ascii", bytes, idx, idx + 1, "ordinal not in range(128)") + })?; + } + } + Ok(out) +} + +// ============================================================================ +// UTF-8 +// ============================================================================ + +/// Decodes `bytes` as UTF-8, applying `errors` to each maximal invalid +/// subpart (the same "substitution of maximal subparts" policy CPython uses, +/// which `str::from_utf8`'s `error_len` reports directly — so `replace` +/// yields exactly one U+FFFD per subpart in both). +fn decode_utf8(bytes: &[u8], errors: &str) -> RunResult { + let mut handler = LazyHandler::new(errors); + let mut out = String::with_capacity(bytes.len()); + let mut pos = 0; + while pos < bytes.len() { + match str::from_utf8(&bytes[pos..]) { + Ok(valid) => { + out.push_str(valid); + break; + } + Err(err) => { + let bad_start = pos + err.valid_up_to(); + let bad_end = match err.error_len() { + Some(len) => bad_start + len, + None => bytes.len(), + }; + out.push_str(str::from_utf8(&bytes[pos..bad_start]).expect("prefix validated by from_utf8")); + let reason = utf8_error_reason(bytes[bad_start], err.error_len()); + // CPython's surrogatepass decodes a CESU-8 surrogate triple + // (ED A0..BF 80..BF) to a lone surrogate; it re-raises for + // any other invalid sequence. + let is_surrogate = is_cesu8_surrogate(&bytes[bad_start..]); + handle_decode_error( + handler.get()?, + &bytes[bad_start..bad_end], + &mut out, + is_surrogate, + || ExcType::unicode_decode_error("utf-8", bytes, bad_start, bad_end, reason), + )?; + pos = bad_end; + } + } + } + Ok(out) +} + +/// Returns true if `rest` starts with a complete CESU-8-encoded surrogate +/// (`ED A0..BF 80..BF`), the only invalid-UTF-8 shape CPython's +/// `surrogatepass` handler accepts. +fn is_cesu8_surrogate(rest: &[u8]) -> bool { + matches!(rest, [0xED, b1, b2, ..] if (0xA0..=0xBF).contains(b1) && (0x80..=0xBF).contains(b2)) +} + +// ============================================================================ +// UTF-16 / UTF-32 +// ============================================================================ + +/// Encodes `s` as UTF-16 in the given byte order, optionally prepending a +/// BOM (the bare `utf-16` codec writes one even for an empty string, +/// matching CPython). Infallible: every char has a UTF-16 encoding. +/// +/// The exact output size is computed up front (2 bytes per UTF-16 code unit, +/// at most 4 bytes per input char), so the untracked `Vec` is bounded by a +/// small constant multiple of the already-tracked input. +fn encode_utf16(s: &str, endian: Endian, with_bom: bool) -> Vec { + let units: usize = s.chars().map(char::len_utf16).sum::() + usize::from(with_bom); + let mut out = Vec::with_capacity(units * 2); + if with_bom { + push_u16(&mut out, 0xFEFF, endian); + } + let mut buf = [0u16; 2]; + for c in s.chars() { + for &unit in c.encode_utf16(&mut buf).iter() { + push_u16(&mut out, unit, endian); + } + } + out +} + +/// Encodes `s` as UTF-32 (4 bytes per char), optionally prepending a BOM. +/// Infallible; same size-bounding rationale as [`encode_utf16`]. +fn encode_utf32(s: &str, endian: Endian, with_bom: bool) -> Vec { + let mut out = Vec::with_capacity((s.chars().count() + usize::from(with_bom)) * 4); + if with_bom { + push_u32(&mut out, 0xFEFF, endian); + } + for c in s.chars() { + push_u32(&mut out, c as u32, endian); + } + out +} + +/// Decodes UTF-16 payload starting at byte index `start` (2 when a BOM was +/// consumed, so error positions include it, matching CPython). +/// +/// Error units follow CPython's taxonomy: a lone trailing byte is `truncated +/// data`; a high surrogate with fewer than 2 bytes left for its pair makes +/// the whole 2–3 byte tail ONE `unexpected end of data` unit; a high +/// surrogate followed by a non-low-surrogate unit is an `illegal UTF-16 +/// surrogate`; a lone low surrogate is an `illegal encoding`. +fn decode_utf16(bytes: &[u8], start: usize, endian: Endian, errors: &str) -> RunResult { + let codec = match endian { + Endian::Little => "utf-16-le", + Endian::Big => "utf-16-be", + }; + let mut handler = LazyHandler::new(errors); + let mut out = String::with_capacity(bytes.len()); + let mut i = start; + while i < bytes.len() { + if bytes.len() - i == 1 { + handle_decode_error(handler.get()?, &bytes[i..], &mut out, false, || { + ExcType::unicode_decode_error(codec, bytes, i, i + 1, "truncated data") + })?; + break; + } + let unit = read_u16(bytes, i, endian); + if !(0xD800..0xE000).contains(&unit) { + out.push(char::from_u32(u32::from(unit)).expect("non-surrogate BMP code unit is a valid char")); + i += 2; + } else if unit >= 0xDC00 { + // low surrogate with no preceding high surrogate + handle_decode_error(handler.get()?, &bytes[i..i + 2], &mut out, true, || { + ExcType::unicode_decode_error(codec, bytes, i, i + 2, "illegal encoding") + })?; + i += 2; + } else if bytes.len() - i < 4 { + // high surrogate but the input ends before its pair: the whole + // 2-3 byte tail is a single error unit (one U+FFFD under replace) + let end = bytes.len(); + handle_decode_error(handler.get()?, &bytes[i..end], &mut out, true, || { + ExcType::unicode_decode_error(codec, bytes, i, end, "unexpected end of data") + })?; + break; + } else { + let low = read_u16(bytes, i + 2, endian); + if (0xDC00..0xE000).contains(&low) { + let code = 0x10000 + ((u32::from(unit) - 0xD800) << 10) + (u32::from(low) - 0xDC00); + out.push(char::from_u32(code).expect("surrogate pair decodes to a valid char")); + i += 4; + } else { + handle_decode_error(handler.get()?, &bytes[i..i + 2], &mut out, true, || { + ExcType::unicode_decode_error(codec, bytes, i, i + 2, "illegal UTF-16 surrogate") + })?; + i += 2; + } + } + } + Ok(out) +} + +/// Decodes UTF-32 payload starting at byte index `start` (4 when a BOM was +/// consumed). Error units are single 4-byte code points (surrogate or +/// out-of-range values) or the truncated 1–3 byte tail. +fn decode_utf32(bytes: &[u8], start: usize, endian: Endian, errors: &str) -> RunResult { + let codec = match endian { + Endian::Little => "utf-32-le", + Endian::Big => "utf-32-be", + }; + let mut handler = LazyHandler::new(errors); + let mut out = String::with_capacity(bytes.len()); + let mut i = start; + while i < bytes.len() { + if bytes.len() - i < 4 { + let end = bytes.len(); + handle_decode_error(handler.get()?, &bytes[i..], &mut out, false, || { + ExcType::unicode_decode_error(codec, bytes, i, end, "truncated data") + })?; + break; + } + let code = read_u32(bytes, i, endian); + if let Some(c) = char::from_u32(code) { + out.push(c); + } else { + let (reason, is_surrogate) = if (0xD800..0xE000).contains(&code) { + ("code point in surrogate code point range(0xd800, 0xe000)", true) + } else { + ("code point not in range(0x110000)", false) + }; + handle_decode_error(handler.get()?, &bytes[i..i + 4], &mut out, is_surrogate, || { + ExcType::unicode_decode_error(codec, bytes, i, i + 4, reason) + })?; + } + i += 4; + } + Ok(out) +} + +/// Appends one UTF-16 code unit in the given byte order. +fn push_u16(out: &mut Vec, unit: u16, endian: Endian) { + out.extend_from_slice(&match endian { + Endian::Little => unit.to_le_bytes(), + Endian::Big => unit.to_be_bytes(), + }); +} + +/// Appends one UTF-32 code unit in the given byte order. +fn push_u32(out: &mut Vec, code: u32, endian: Endian) { + out.extend_from_slice(&match endian { + Endian::Little => code.to_le_bytes(), + Endian::Big => code.to_be_bytes(), + }); +} + +/// Reads the 2-byte code unit at `i` (caller guarantees bounds). +fn read_u16(bytes: &[u8], i: usize, endian: Endian) -> u16 { + let pair = [bytes[i], bytes[i + 1]]; + match endian { + Endian::Little => u16::from_le_bytes(pair), + Endian::Big => u16::from_be_bytes(pair), + } +} + +/// Reads the 4-byte code unit at `i` (caller guarantees bounds). +fn read_u32(bytes: &[u8], i: usize, endian: Endian) -> u32 { + let quad = [bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]; + match endian { + Endian::Little => u32::from_le_bytes(quad), + Endian::Big => u32::from_be_bytes(quad), + } +} diff --git a/crates/bashkit-monty/src/dump_format.rs b/crates/bashkit-monty/src/dump_format.rs new file mode 100644 index 000000000..64a5f7630 --- /dev/null +++ b/crates/bashkit-monty/src/dump_format.rs @@ -0,0 +1,519 @@ +//! Versioned framing for serialized interpreter state. +//! +//! A dump is one CBOR value — [`Dump`] — carrying both the interpreter +//! state and the session metadata a host must restore alongside it (script +//! name, type-check stubs), behind a `[MAGIC][DUMP_VERSION]` header. There is +//! exactly one dump shape, so hosts need no format knowledge beyond [`dump`] +//! and [`Dump::load`]; whether the session was idle or suspended is the +//! [`Session`] discriminant, not a separate tag. +//! +//! # Naming contract +//! +//! The payload is self-describing: structs are maps keyed by field name and +//! enums are keyed by variant name, so serde's derive evolves the schema on +//! its own. A dumped type may gain a field with `#[serde(default)]`, lose a +//! field, or have variants inserted anywhere, and older dumps still load. +//! Tuple structs and tuple variants are positional, so their fields may only +//! be appended. +//! The names themselves are the contract: renaming a serialized field or +//! variant needs `#[serde(alias = "old")]` (or a [`DUMP_VERSION`] bump), and +//! `#[serde(deny_unknown_fields)]` must never be added to a dumped type. + +use std::{convert::Infallible, error::Error, fmt, mem::size_of}; + +use minicbor_serde::{ + Deserializer, Serializer, + error::{DecodeError, EncodeError}, +}; +use monty_types::{ModuleStub, TypeCheckState}; +use serde::{Deserialize, Serialize, de::Error as _}; + +use crate::{ + dump_upgrade, + heap::Heap, + intern::Interns, + repl::{MontyRepl, ReplProgress}, + run_progress::RunProgress, +}; + +/// Prefix distinguishing Monty dumps from unframed CBOR data. +const MAGIC: &[u8; 6] = b"MONTY\0"; + +/// Version of the dump schema. +/// +/// The payload names its fields and variants, so adding a field with a default, +/// removing one or reordering them does not need a bump (see the module docs). +/// Bump for every release where +/// the *meaning* of serialized data changes: opcodes or their operand shapes, +/// `BuiltinsFunctions` order (its discriminants are bytecode operands), +/// `CmpOperator` values, the compiler's constant layout, how a dict or set key +/// hashes (entries persist their hash), or a semantic change to a stored value. +/// Frozen code is persisted too: incompatible changes to its Rust entry arguments or +/// private native helper contracts need compatibility handling or a bump. Compatible +/// source-body changes do not require one; restored sessions retain their captured code. +/// Older builds then reject the new dumps instead of misexecuting them, and this +/// build rejects dumps below [`MIN_SUPPORTED_DUMP_VERSION`]. +/// +/// Before bumping, check there's already been a bump since the last release - multiple bumps +/// between releases is unnecessary and can lead to confusion. +pub const DUMP_VERSION: u16 = 14; + +/// The oldest dump version this build loads. `Dump::load` runs `dump_upgrade` +/// over an older dump, rebuilding what the newer versions changed. +pub const MIN_SUPPORTED_DUMP_VERSION: u16 = 13; + +// The supported range must be non-empty, and must exclude zero +const _: () = assert!(MIN_SUPPORTED_DUMP_VERSION >= 1); +const _: () = assert!(MIN_SUPPORTED_DUMP_VERSION <= DUMP_VERSION); + +/// Number of bytes before the CBOR payload. +const HEADER_LEN: usize = MAGIC.len() + size_of::(); + +/// Initial payload capacity for [`dump`]. A fresh idle session dumps to ~800 +/// bytes and one suspended on a host call to ~2,400, so this never over-allocates +/// meaningfully and skips the first few `Vec` doublings. +const MIN_PAYLOAD_CAPACITY: usize = 1024; + +/// Serializes a live session and its metadata into a versioned dump, readable +/// by [`Dump::load`]. +/// +/// Takes the state by reference because dumping is read-only: the caller keeps +/// its session and can carry on feeding it. +/// +/// # Errors +/// Returns an error if serialization fails. +pub fn dump( + script_name: &str, + type_check: Option<&TypeCheckState>, + module_stubs: &[ModuleStub], + state: SessionRef<'_>, +) -> Result, DumpEncodeError> { + /// Borrowed mirror of [`Dump`]; serde encodes it identically. + #[derive(Serialize)] + struct DumpRef<'a> { + script_name: &'a str, + type_check: Option<&'a TypeCheckState>, + module_stubs: &'a [ModuleStub], + state: SessionRef<'a>, + } + + let mut bytes = Vec::with_capacity(HEADER_LEN + MIN_PAYLOAD_CAPACITY); + bytes.extend_from_slice(MAGIC); + bytes.extend_from_slice(&DUMP_VERSION.to_le_bytes()); + // the payload is written after the header in place: no second buffer to copy it into + let dump = DumpRef { + script_name, + type_check, + module_stubs, + state, + }; + dump.serialize(&mut Serializer::new(&mut bytes)) + .map_err(DumpEncodeError)?; + Ok(bytes) +} + +/// A complete REPL session snapshot: the interpreter state plus the +/// session-scoped context that lives outside it. +/// +/// The metadata travels with the state because a restored session is otherwise +/// silently downgraded — losing `script_name` corrupts tracebacks, and losing +/// `type_check` disables enforcement the parent asked for. +#[derive(Debug, Deserialize)] +pub struct Dump { + /// Script name used for tracebacks and type-check diagnostics. + pub script_name: String, + /// `Some` when the session was created with type checking enabled. + pub type_check: Option, + /// The stubs of the session's host-provided modules, whether or not it + /// type-checks, so a restored session checks against the same ones. + #[serde(default)] + pub module_stubs: Vec, + /// The interpreter state, and where it was paused. + pub state: Session, +} + +impl Dump { + /// Restores a session dumped by [`dump`]. + /// + /// # Snapshot trust + /// The caller must establish that the bytes are unmodified output from a trusted, + /// compatible Monty producer. Invalid snapshots have no correctness or availability + /// guarantees: loading or using them may panic, abort, hang, or produce wrong results, + /// but must not cause undefined behaviour in the host process. + /// Successful decoding does not authenticate or fully validate a snapshot. + /// The same contract applies to direct serde deserialization. + /// + /// Accepts [`MIN_SUPPORTED_DUMP_VERSION`]`..=`[`DUMP_VERSION`], upgrading a + /// dump older than [`DUMP_VERSION`] before returning it. + /// + /// # Errors + /// Returns [`DumpError`] for a dump this build cannot read. The version + /// variants name the bound the dump missed, so a host can tell a stale + /// snapshot from one written by a build it should be reading with. + pub fn load(bytes: &[u8]) -> Result { + let Some(header) = bytes.get(..HEADER_LEN) else { + return Err(DumpError::NotADump); + }; + let version = u16::from_le_bytes([header[MAGIC.len()], header[MAGIC.len() + 1]]); + if &header[..MAGIC.len()] != MAGIC { + Err(DumpError::NotADump) + } else if version < MIN_SUPPORTED_DUMP_VERSION { + Err(DumpError::VersionTooOld { + found: version, + min_supported: MIN_SUPPORTED_DUMP_VERSION, + }) + } else if version > DUMP_VERSION { + Err(DumpError::VersionTooNew { + found: version, + max_supported: DUMP_VERSION, + }) + } else { + let payload = &bytes[HEADER_LEN..]; + let mut deserializer = Deserializer::new(payload); + let mut value = + Self::deserialize(&mut deserializer).map_err(|err| DumpError::Payload(DumpDecodeError(err)))?; + // trailing bytes are rejected rather than ignored, so a padded dump + // cannot decode as the shorter valid one it starts with + if deserializer.into_decoder().position() == payload.len() { + if version < DUMP_VERSION + && let Some((heap, interns)) = value.state.heap_and_interns() + { + dump_upgrade::upgrade(version, heap, interns); + } + Ok(value) + } else { + Err(DumpError::Payload(DumpDecodeError::custom( + "trailing bytes after the payload", + ))) + } + } + } +} + +/// Where a dumped session was paused. Variants are encoded by name and mirrored +/// by [`SessionRef`] — keep the two sets of names in step. +/// +/// Both arms are boxed because they differ by hundreds of bytes inline; a +/// `Box` serializes exactly as `T`, so this does not change the wire form. +#[derive(Debug, Deserialize)] +pub enum Session { + /// Between feeds, ready for the next snippet. + Idle(Box), + /// Mid-feed, waiting on a resume. + Suspended(Box), + /// A one-shot [`crate::MontyRun`] execution paused at a suspension. Not a + /// repl, so it cannot be fed further — only resumed to completion. + Running(Box), +} + +impl Session { + /// The session heap and its interns, or `None` for a one-shot run that has completed. + fn heap_and_interns(&mut self) -> Option<(&mut Heap, &Interns)> { + match self { + Self::Idle(repl) => Some(repl.heap_and_interns()), + Self::Suspended(progress) => Some(progress.heap_and_interns()), + Self::Running(progress) => progress.heap_and_interns(), + } + } +} + +/// Borrowed counterpart of [`Session`] used when dumping, so a live session can +/// be serialized without moving the repl out of the host's own state. +#[derive(Debug, Serialize)] +pub enum SessionRef<'a> { + /// Between feeds, ready for the next snippet. + Idle(&'a MontyRepl), + /// Mid-feed, waiting on a resume. + Suspended(&'a ReplProgress), + /// A paused one-shot [`crate::MontyRun`] execution. + Running(&'a RunProgress), +} + +/// Why a dump could not be restored. +/// +/// The two version failures are separate variants because they need opposite +/// responses: a too-old dump is dead and its session must be rebuilt by +/// replaying feeds, while a too-new one is intact and wants a newer reader. +#[derive(Debug, PartialEq, Eq)] +pub enum DumpError { + /// Too short to hold a header, or missing the magic prefix. + NotADump, + /// Written by a build older than the oldest this one reads. + VersionTooOld { + /// Version the dump was written with. + found: u16, + /// Oldest version this build reads. + min_supported: u16, + }, + /// Written by a newer build, so the bytes are worth keeping — a build at or + /// above `found` reads them. + VersionTooNew { + /// Version the dump was written with. + found: u16, + /// Newest version this build reads. + max_supported: u16, + }, + /// A version this build reads, holding something it cannot load — reserved + /// for a compatibility mechanism and not produced today. `reason` names what + /// blocked it; the remedy matches [`Self::VersionTooOld`]. + Unsupported { + /// Version the dump was written with. + found: u16, + /// What this build could not load, for a host to log. + reason: String, + }, + /// Header was valid but the payload did not decode. + Payload(DumpDecodeError), +} + +impl fmt::Display for DumpError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NotADump => write!(f, "not a monty dump"), + Self::VersionTooOld { found, min_supported } => { + write!( + f, + "dump format version {found} is older than {min_supported}, the oldest this build reads" + ) + } + Self::VersionTooNew { found, max_supported } => { + write!( + f, + "dump format version {found} is newer than {max_supported}, the newest this build reads" + ) + } + Self::Unsupported { found, reason } => { + write!(f, "dump format version {found} is unsupported: {reason}") + } + Self::Payload(err) => write!(f, "malformed dump payload: {err}"), + } + } +} + +impl Error for DumpError {} + +/// Why a dump payload did not decode: a truncated or corrupt encoding, or a +/// value the interpreter refused to reconstruct. +/// +/// Wraps the codec's error so the public API does not name the codec. Two +/// errors are equal when they render the same — the codec offers no structured +/// comparison, and hosts only ever see the message. +#[derive(Debug)] +pub struct DumpDecodeError(DecodeError); + +impl DumpDecodeError { + /// Wraps a message about the payload, for checks that run after decoding. + fn custom(message: &'static str) -> Self { + Self(DecodeError::custom(message)) + } +} + +impl PartialEq for DumpDecodeError { + fn eq(&self, other: &Self) -> bool { + self.to_string() == other.to_string() + } +} + +impl Eq for DumpDecodeError {} + +impl fmt::Display for DumpDecodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +impl Error for DumpDecodeError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + Some(&self.0) + } +} + +/// Why [`dump`] could not serialize a session. Writing into memory cannot run +/// out of space, so this only surfaces a `Serialize` impl refusing a value. +#[derive(Debug)] +pub struct DumpEncodeError(EncodeError); + +impl fmt::Display for DumpEncodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +impl Error for DumpEncodeError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + Some(&self.0) + } +} + +#[cfg(test)] +mod tests { + use std::str::FromStr; + + use monty_types::{BuiltinsFunctions, ExcType, MontyType, TypeCheckingFormat}; + use serde::Serialize; + use strum::VariantNames; + + use super::DUMP_VERSION; + use crate::{ + bytecode::opcode_fingerprint, expressions::comparison_operators_fingerprint, heap::HeapId, types::Type, + }; + + /// If a component changes incompatibly, bump `DUMP_VERSION` before updating its + /// expected fingerprint. Compatible changes only require a fingerprint update. + /// + /// NB this test is not exhaustive of all possible compatibility issues, it just helps + /// catch the obvious ones! + #[test] + fn serialized_components_match_dump_version() { + assert_eq!( + opcode_fingerprint(), + 0xa78a_9e6c_3fab_abed, + "opcodes changed for dump version {DUMP_VERSION}, actual: {}", + grouped_hex(opcode_fingerprint()) + ); + assert_eq!( + comparison_operators_fingerprint(), + 0x8ecc_d26b_160d_9c0b, + "comparison operators changed for dump version {DUMP_VERSION}, actual: {}", + grouped_hex(comparison_operators_fingerprint()) + ); + // `VariantNames` keeps the `#[strum(disabled)]` variants that `EnumString` + // drops, so the counts below cover every serialized variant once the + // disabled ones are supplied by hand. Asserted rather than assumed, so a + // strum upgrade that changed it says so instead of quietly narrowing the guard. + assert!(Type::VARIANTS.contains(&"instance")); + assert!(MontyType::VARIANTS.contains(&"exception")); + + let type_names = serde_variant_names( + Type::VARIANTS, + &[ + Type::Instance(HeapId::from_index(0)), + Type::Exception(ExcType::ValueError), + ], + ); + assert_eq!( + variant_name_fingerprint(&type_names), + 0x578d_38b1_7715_f9a1, + "Type variants changed for dump version {DUMP_VERSION}, actual: {}", + grouped_hex(variant_name_fingerprint(&type_names)) + ); + let monty_type_names = serde_variant_names(MontyType::VARIANTS, &[MontyType::Exception(ExcType::ValueError)]); + assert_eq!( + variant_name_fingerprint(&monty_type_names), + 0xa95a_cc16_8f6c_5e31, + "MontyType variants changed for dump version {DUMP_VERSION}, actual: {}", + grouped_hex(variant_name_fingerprint(&monty_type_names)) + ); + // Builtin discriminants are `CallBuiltinFunction` operands, so the enum + // is append-only: a new builtin goes after the last variant. + assert_eq!( + variant_order_fingerprint(BuiltinsFunctions::VARIANTS), + 0xcdd8_09b1_2adc_3852, + "BuiltinsFunctions variants changed for dump version {DUMP_VERSION}, actual: {}", + grouped_hex(variant_order_fingerprint(BuiltinsFunctions::VARIANTS)) + ); + } + + /// Formats an integer as hex with underscores between four-digit groups. + fn grouped_hex(n: u64) -> String { + let mut s = format!("{n:x}"); + for i in (1..s.len()).rev().skip(3).step_by(4) { + s.insert(i, '_'); + } + format!("0x{s}") + } + + /// FNV-1a over variant names in declaration order. + /// + /// `BuiltinsFunctions` discriminants are bytecode operands, so inserting a + /// variant rewrites what older dumps execute rather than failing the version + /// check. Appending leaves this unchanged for every existing variant; + /// inserting or reordering does not. + fn variant_order_fingerprint(variants: &[&str]) -> u64 { + fnv1a(variants) + } + + /// FNV-1a over variant names in sorted order. + /// + /// `Type` and `MontyType` are encoded by variant name inside a `Dump`, so + /// order is free but a rename or removal breaks older dumps: fix it with + /// `#[serde(alias)]` or bump `DUMP_VERSION`. Adding a variant only needs + /// the expected hash updated. + fn variant_name_fingerprint(names: &[String]) -> u64 { + let mut sorted = names.to_vec(); + sorted.sort_unstable(); + fnv1a(&sorted) + } + + /// FNV-1a over a sequence of names, each terminated by a separator. + fn fnv1a(names: &[impl AsRef]) -> u64 { + const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + const PRIME: u64 = 0x0100_0000_01b3; + + let mut hash = OFFSET_BASIS; + for name in names { + for byte in name.as_ref().as_bytes() { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(PRIME); + } + hash ^= 0xff; + hash = hash.wrapping_mul(PRIME); + } + hash + } + + /// The names serde writes for every variant of an enum, read back from the + /// encoded form rather than taken from strum, whose `#[strum(serialize)]` + /// spelling can stay put while the Rust name serde uses changes. `disabled` + /// supplies the `#[strum(disabled)]` variants `EnumString` refuses to parse. + fn serde_variant_names(strum_names: &[&str], disabled: &[T]) -> Vec { + let parsed: Vec = strum_names.iter().filter_map(|name| T::from_str(name).ok()).collect(); + assert_eq!( + parsed.len() + disabled.len(), + strum_names.len(), + "every variant must be covered" + ); + parsed + .iter() + .chain(disabled) + .map(|variant| encoded_variant_name(&minicbor_serde::to_vec(variant).unwrap())) + .collect() + } + + /// The variant name at the front of an encoded enum value: a bare text string + /// for a unit variant, or the single key of the map wrapping a payload. + fn encoded_variant_name(bytes: &[u8]) -> String { + let text = if bytes[0] == 0xa1 { &bytes[1..] } else { bytes }; + let (len, start) = match text[0] { + header @ 0x60..=0x77 => (usize::from(header - 0x60), 1), + 0x78 => (usize::from(text[1]), 2), + header => panic!("expected a text string, got CBOR header {header:#x}"), + }; + String::from_utf8(text[start..start + len].to_vec()).unwrap() + } + + /// `TypeCheckingFormat` reaches the dump schema through + /// `monty_types::TypeCheckState` and serializes by variant name, so the + /// names are compared in sorted order: renaming one needs `#[serde(alias)]` + /// or a `DUMP_VERSION` bump, adding one only needs this list updated. + #[test] + fn type_checking_format_variants_match_dump_version() { + let mut variants = serde_variant_names::(TypeCheckingFormat::VARIANTS, &[]); + variants.sort_unstable(); + assert_eq!( + variants, + [ + "Azure", + "Concise", + "Full", + "Github", + "Gitlab", + "Json", + "JsonLines", + "Pylint", + "Rdjson" + ], + "TypeCheckingFormat variants changed for dump version {DUMP_VERSION}" + ); + } +} diff --git a/crates/bashkit-monty/src/dump_upgrade.rs b/crates/bashkit-monty/src/dump_upgrade.rs new file mode 100644 index 000000000..c1f83431e --- /dev/null +++ b/crates/bashkit-monty/src/dump_upgrade.rs @@ -0,0 +1,24 @@ +//! Upgrades applied as `Dump::load` reads a dump older than `DUMP_VERSION`, so +//! `MIN_SUPPORTED_DUMP_VERSION` can stay below it. +//! +//! An upgrade fits a change that alters what stored data *means* while the old +//! data still decodes and holds everything needed to rebuild the new form. A +//! change to one value's stored shape is a `#[serde(from)]` shim on that type +//! instead; bytecode, operand layouts and persisted hashes need the floor raised. +//! +//! Rules every upgrade follows: +//! - It branches on the header version, never on the data's shape, and current +//! data is never touched. +//! - It runs inside `Dump::load`, before any code: nothing on the live heap or +//! VM records that a session was upgraded. +//! - It is tested against a fixture the *older* build wrote, which must never be +//! regenerated (see `tests/dump_compat.rs`). + +use crate::{heap::Heap, intern::Interns, modules::dataclasses}; + +/// Runs every upgrade a dump written at `version` needs over its decoded heap. +pub(crate) fn upgrade(version: u16, heap: &mut Heap, interns: &Interns) { + if version <= dataclasses::LEGACY_DUMP_VERSION { + dataclasses::upgrade_legacy_classes(heap, interns); + } +} diff --git a/crates/bashkit-monty/src/exception_private.rs b/crates/bashkit-monty/src/exception_private.rs new file mode 100644 index 000000000..5cae69b87 --- /dev/null +++ b/crates/bashkit-monty/src/exception_private.rs @@ -0,0 +1,3067 @@ +use std::{ + borrow::Cow, + fmt::{self, Display, Write}, +}; + +use monty_types::{ExcData, JsonErrorData, MontyException, StackFrame, UnicodeErrorData}; +use smallvec::smallvec; + +use crate::{ + args::ArgValues, + bytecode::{CallResult, VM}, + defer_drop, + fstring::{FormatError, ascii_escape}, + heap::{DropWithContext, HeapData, HeapRead}, + intern::{Interns, StaticStrings, StringId}, + parse::CodeRange, + py_value::PyValue, + source_map::{SourceMap, StackFrameExt}, + types::{ + PyTrait, Type, allocate_tuple, + long_int::INT_MAX_STR_DIGITS, + str::{StringRepr, allocate_string, string_repr_fmt}, + }, + value::{EitherStr, Value}, +}; + +/// Result type alias for operations that can produce a runtime error. +pub type RunResult = Result; + +pub use monty_types::{ExcType, unicode_decode_error_msg}; + +/// Crate-internal error constructors on [`ExcType`]. +/// +/// `ExcType` itself lives in `monty-types`; these constructors build +/// interpreter-side [`RunError`]s (which carry raw stack frames), so they +/// stay in `monty` as a `pub(crate)` extension trait with default bodies. +/// Import the trait to call them as `ExcType::type_error(...)`. +pub(crate) trait ExcTypeExt: Sized { + /// Creates an exception instance from an exception type and arguments, + /// handling constructor calls like `ValueError('message')`. + fn call(self, vm: &mut VM<'_>, args: ArgValues) -> RunResult; + + /// Creates an AttributeError for when an attribute is not found (GET operation). + /// + /// Sets `hide_caret: true` because CPython doesn't show carets for attribute GET errors. + #[must_use] + fn attribute_error(type_name: impl Display, attr: &str) -> RunError { + let exc = SimpleException::new_msg( + ExcType::AttributeError, + format!("'{type_name}' object has no attribute '{attr}'"), + ); + RunError::Exc(ExceptionRaise { + exc, + frame: None, + snippet_frame: None, + hide_caret: true, // CPython doesn't show carets for attribute GET errors + }) + } + + /// Creates an AttributeError for an unknown *method*, releasing the + /// arguments the call has already evaluated. + /// + /// Prefer this over [`attribute_error`](Self::attribute_error) anywhere the + /// arguments are already owned: that one releases nothing, so calling it from + /// a `py_call_attr` fall-through leaks a reference per call — something + /// sandboxed code can repeat in a loop. + #[must_use] + fn attribute_error_method(type_name: impl Display, attr: &EitherStr, args: ArgValues, vm: &mut VM<'_>) -> RunError { + args.drop_with(vm); + Self::attribute_error(type_name, attr.as_str(vm.interns)) + } + + /// Creates an AttributeError for a missing attribute on a class object. + /// + /// Matches CPython's wording for type objects: `type object 'Foo' has no + /// attribute 'nope'` (instances use [`Self::attribute_error`] instead). + /// Sets `hide_caret: true` because CPython doesn't show carets for attribute GET errors. + #[must_use] + fn attribute_error_type(class_name: &str, attr: &str) -> RunError { + let exc = SimpleException::new_msg( + ExcType::AttributeError, + format!("type object '{class_name}' has no attribute '{attr}'"), + ); + RunError::Exc(ExceptionRaise { + exc, + frame: None, + snippet_frame: None, + hide_caret: true, // CPython doesn't show carets for attribute GET errors + }) + } + + /// Creates an AttributeError for attribute assignment on types that don't support it. + /// + /// Matches CPython's format for setting attributes on built-in types. + #[must_use] + fn attribute_error_no_setattr(type_: &str, attr_name: &str) -> RunError { + SimpleException::new_msg( + ExcType::AttributeError, + format!("'{type_}' object has no attribute '{attr_name}' and no __dict__ for setting new attributes"), + ) + .into() + } + + /// The `AttributeError` for assigning to a read-only data attribute such as `complex.real`. + #[must_use] + fn attribute_error_readonly() -> RunError { + SimpleException::new_msg(ExcType::AttributeError, "readonly attribute").into() + } + + /// Creates an AttributeError for a missing module attribute. + /// + /// Matches CPython's format: `AttributeError: module 'name' has no attribute 'attr'` + /// Sets `hide_caret: true` because CPython doesn't show carets for attribute GET errors. + #[must_use] + fn attribute_error_module(module_name: &str, attr_name: &str) -> RunError { + let exc = SimpleException::new_msg( + ExcType::AttributeError, + format!("module '{module_name}' has no attribute '{attr_name}'"), + ); + RunError::Exc(ExceptionRaise { + exc, + frame: None, + snippet_frame: None, + hide_caret: true, // CPython doesn't show carets for attribute GET errors + }) + } + + #[must_use] + fn type_error_not_sub(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not subscriptable")).into() + } + + /// Creates the TypeError for subscripting a type that defines no + /// `__class_getitem__`: `type 'int' is not subscriptable`. + #[must_use] + fn type_error_type_not_subscriptable(type_: &str) -> RunError { + Self::type_error(format!("type '{type_}' is not subscriptable")) + } + + /// Creates the TypeError for subscripting a `types.GenericAlias` again + /// (`list[int][str]`), `repr` being the alias's own. + #[must_use] + fn type_error_not_generic_class(repr: &str) -> RunError { + Self::type_error(format!("{repr} is not a generic class")) + } + + /// Creates the ValueError `dict.update()` raises for a pair of the wrong + /// length: `dictionary update sequence element #1 has length 3; 2 is required`. + #[must_use] + fn value_error_update_sequence_length(index: usize, length: usize) -> RunError { + SimpleException::new_msg( + ExcType::ValueError, + format!("dictionary update sequence element #{index} has length {length}; 2 is required"), + ) + .into() + } + + /// Creates the TypeError for `typing.Union[()]`. + #[must_use] + fn union_of_no_types() -> RunError { + Self::type_error("Cannot take a Union of no types.") + } + + /// Creates the TypeError for `typing.Optional[a, b]`, `repr` being the + /// tuple's. + #[must_use] + fn optional_requires_single_type(repr: &str) -> RunError { + Self::type_error(format!("typing.Optional requires a single type. Got {repr}.")) + } + + /// Creates the TypeError `isinstance()` raises for a `types.GenericAlias` + /// second argument, which CPython refuses to check against. + #[must_use] + fn isinstance_parameterized_generic() -> RunError { + Self::type_error("isinstance() argument 2 cannot be a parameterized generic") + } + + /// Creates the TypeError for an ordering comparison (`<`, `<=`, `>`, `>=`) + /// between values whose types define no ordering, e.g. `1 < 'a'` or two + /// instances of a user class without comparison dunders. + /// + /// Matches CPython's format: + /// `TypeError: '{op}' not supported between instances of '{left}' and '{right}'` + #[must_use] + fn type_error_ordering(operator: &str, left_type: &str, right_type: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("'{operator}' not supported between instances of '{left_type}' and '{right_type}'"), + ) + .into() + } + + /// Creates a TypeError for awaiting a non-awaitable object. + /// + /// Matches CPython's format: `TypeError: '{type}' object can't be awaited` + #[must_use] + fn object_not_awaitable(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object can't be awaited")).into() + } + + /// Creates the canonical `RuntimeError: cannot reuse already awaited coroutine`, + /// raised on direct re-await and on cross-gather coroutine reuse. + #[must_use] + fn cannot_reuse_already_awaited_coroutine() -> RunError { + SimpleException::new_msg(ExcType::RuntimeError, "cannot reuse already awaited coroutine").into() + } + + /// `ValueError: generator already executing` — a generator advanced from + /// inside its own step, e.g. by an `os.walk` `onerror` callback. + #[must_use] + fn generator_already_executing() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "generator already executing").into() + } + + /// Creates a TypeError for item assignment on types that don't support it. + /// + /// Matches CPython's format: `TypeError: '{type}' object does not support item assignment` + #[must_use] + fn type_error_not_sub_assignment(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("'{type_}' object does not support item assignment"), + ) + .into() + } + + /// Creates a TypeError for unhashable types when calling `hash()`. + /// + /// This matches Python 3.14's error message: `TypeError: unhashable type: 'list'` + #[must_use] + fn type_error_unhashable(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("unhashable type: '{type_}'")).into() + } + + /// Creates a TypeError for unhashable types used as dict keys. + /// + /// This matches Python 3.14's error message: + /// `TypeError: cannot use 'list' as a dict key (unhashable type: 'list')` + #[must_use] + fn type_error_unhashable_dict_key(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("cannot use '{type_}' as a dict key (unhashable type: '{type_}')"), + ) + .into() + } + + /// Creates a TypeError for an unhashable value used as a set element. + #[must_use] + fn type_error_unhashable_set_element(element_type: &str, unhashable_type: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("cannot use '{element_type}' as a set element (unhashable type: '{unhashable_type}')"), + ) + .into() + } + + /// Creates a KeyError for a missing dict key. + /// + /// For string keys, uses the raw string value without extra quoting. + /// If the key's string conversion fails (e.g. huge LongInt exceeding + /// `INT_MAX_STR_DIGITS`), falls back to the type name so that a + /// `KeyError` is always raised rather than a spurious `ValueError`. + fn key_error(key: &Value, vm: &mut VM<'_>) -> RunError { + let key_str = match key.py_str(vm) { + Ok(key_value) => { + // `key_value` is a heap `str` `Value`; extract its text and drop it. + defer_drop!(key_value, vm); + if let Ok(s) = key_value.to_str(vm) { + s.to_owned() + } else { + format!("<{}>", key.py_type_name(vm)) + } + } + Err(_) => format!("<{}>", key.py_type_name(vm)), + }; + SimpleException::new_msg(ExcType::KeyError, key_str).into() + } + + /// Creates a KeyError for popping from an empty set. + /// + /// Matches CPython's error format: `KeyError: 'pop from an empty set'` + #[must_use] + fn key_error_pop_empty_set() -> RunError { + SimpleException::new_msg(ExcType::KeyError, "pop from an empty set").into() + } + + /// Creates a TypeError for when a function receives the wrong number of arguments. + /// + /// Matches CPython's error format exactly: + /// - For 1 expected arg: `{name}() takes exactly one argument ({actual} given)` + /// - For N expected args: `{name} expected {expected} arguments, got {actual}` + /// + /// # Arguments + /// * `name` - The function name (e.g., "len" for builtins, "list.append" for methods) + /// * `expected` - Number of expected arguments + /// * `actual` - Number of arguments actually provided + #[must_use] + fn type_error_arg_count(name: &str, expected: usize, actual: usize) -> RunError { + if expected == 1 { + // CPython: "len() takes exactly one argument (2 given)" + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() takes exactly one argument ({actual} given)"), + ) + .into() + } else { + // CPython: "insert expected 2 arguments, got 1" + SimpleException::new_msg( + ExcType::TypeError, + format!("{name} expected {expected} arguments, got {actual}"), + ) + .into() + } + } + + /// Creates a TypeError for when a method that takes no arguments receives some. + /// + /// Matches CPython's format: `{name}() takes no arguments ({actual} given)` + /// + /// # Arguments + /// * `name` - The method name (e.g., "dict.keys") + /// * `actual` - Number of arguments actually provided + #[must_use] + fn type_error_no_args(name: &str, actual: usize) -> RunError { + // CPython: "dict.keys() takes no arguments (1 given)" + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() takes no arguments ({actual} given)"), + ) + .into() + } + + /// Creates a TypeError for when a function receives fewer arguments than required. + /// + /// Matches CPython's format: `{name} expected at least {min} argument, got {actual}` + /// + /// # Arguments + /// * `name` - The function name (e.g., "get", "pop") + /// * `min` - Minimum number of required arguments + /// * `actual` - Number of arguments actually provided + #[must_use] + fn type_error_at_least(name: &str, min: usize, actual: usize) -> RunError { + // CPython: "get expected at least 1 argument, got 0" + let plural = if min == 1 { "" } else { "s" }; + SimpleException::new_msg( + ExcType::TypeError, + format!("{name} expected at least {min} argument{plural}, got {actual}"), + ) + .into() + } + + /// Creates a TypeError for when a function receives more arguments than allowed. + /// + /// Matches CPython's `PyArg_UnpackTuple` format: + /// - `{name} expected at most {max} argument, got {actual}` (singular when max=1) + /// - `{name} expected at most {max} arguments, got {actual}` (plural otherwise) + /// + /// # Arguments + /// * `name` - The function name (e.g., "get", "pop") + /// * `max` - Maximum number of allowed arguments + /// * `actual` - Number of arguments actually provided + #[must_use] + fn type_error_at_most(name: &str, max: usize, actual: usize) -> RunError { + let plural = if max == 1 { "" } else { "s" }; + SimpleException::new_msg( + ExcType::TypeError, + format!("{name} expected at most {max} argument{plural}, got {actual}"), + ) + .into() + } + + /// Creates a TypeError for a `startswith`/`endswith` affix argument that is + /// neither the expected string type nor a tuple. + /// + /// Matches CPython: `{method} first arg must be {expected} or a tuple of {expected}, not {type}` + /// (`expected` is `str` for `str` methods, `bytes` for `bytes` methods). + #[must_use] + fn type_error_affix_arg(method: &str, expected: &str, type_name: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("{method} first arg must be {expected} or a tuple of {expected}, not {type_name}"), + ) + .into() + } + + /// Creates a TypeError for a non-string element in a `startswith`/`endswith` + /// affix tuple. + /// + /// Matches CPython: `tuple for {method} must only contain {expected}, not {type}`. + /// Raised lazily while matching — elements after a successful match are never checked. + #[must_use] + fn type_error_affix_tuple_item(method: &str, expected: &str, type_name: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("tuple for {method} must only contain {expected}, not {type_name}"), + ) + .into() + } + + /// Creates a TypeError for too many arguments to a method or named function. + /// + /// Matches CPython's format for method-style calls: + /// `{name}() takes at most {max} argument ({actual} given)` (singular when max=1) + /// `{name}() takes at most {max} arguments ({actual} given)` (plural otherwise) + /// + /// Both C parsers insert `keyword ` before `argument` when the call passed + /// no positionals at all (`nargs == 0` in `vgetargskeywords` / + /// `vgetargskeywordsfast_impl`), so pass `all_keyword` accordingly: + /// `fspath() takes at most 1 keyword argument (2 given)`. + /// + /// Use this instead of `type_error_at_most` for methods and type constructors that + /// CPython formats with parentheses, e.g. `now()`, `timezone()`, `expandtabs()`. + #[must_use] + fn type_error_method_at_most(name: &str, max: usize, actual: usize, all_keyword: bool) -> RunError { + let kind = if all_keyword { "keyword " } else { "" }; + let plural = if max == 1 { "" } else { "s" }; + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() takes at most {max} {kind}argument{plural} ({actual} given)"), + ) + .into() + } + + /// `PyArg_ParseTuple`'s wording for a fixed arity, which it uses whenever + /// min == max: `{name}() takes exactly {n} argument ({actual} given)` + /// (plural for `n != 1`; the digit, unlike `METH_O`'s `exactly one`). + #[must_use] + fn type_error_method_exact(name: &str, n: usize, actual: usize) -> RunError { + let plural = if n == 1 { "" } else { "s" }; + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() takes exactly {n} argument{plural} ({actual} given)"), + ) + .into() + } + + /// Creates a TypeError for too few arguments to a `PyArg_ParseTuple` call: + /// `{name}() takes at least {min} argument(s) ({actual} given)`. Unlike + /// [`type_error_at_least_positional`] there is no `positional` qualifier — + /// these functions accept no keywords, so CPython never distinguishes. + #[must_use] + fn type_error_method_at_least(name: &str, min: usize, actual: usize) -> RunError { + let plural = if min == 1 { "" } else { "s" }; + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() takes at least {min} argument{plural} ({actual} given)"), + ) + .into() + } + + /// Creates a TypeError for too few positional arguments to a method-style call. + /// + /// Matches CPython's format used by methods like `str.replace`: + /// `{name}() takes at least {min} positional argument ({actual} given)` (singular when min=1) + /// `{name}() takes at least {min} positional arguments ({actual} given)` (plural otherwise) + /// + /// Distinct from [`type_error_at_least`] which uses CPython's + /// `PyArg_UnpackTuple` wording (no parens, no "positional"). Emitted by + /// `FromArgs` for any struct with required positional-only fields, + /// matching CPython's C-method `_PyArg_UnpackKeywords` dispatch. + #[must_use] + fn type_error_at_least_positional(name: &str, min: usize, actual: usize) -> RunError { + let plural = if min == 1 { "" } else { "s" }; + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() takes at least {min} positional argument{plural} ({actual} given)"), + ) + .into() + } + + /// Creates the bespoke `map()` arity error that CPython hard-codes. + /// + /// CPython's `map()` uses a single fixed message regardless of whether + /// 0 or 1 args were given: `map() must have at least two arguments.` + /// (note the trailing period). We mirror it here so `map()` / `map(f)` + /// match byte-for-byte rather than falling through to the generic + /// "missing N required positional arguments" wording the macro would + /// otherwise emit. + #[must_use] + fn type_error_map_arity() -> RunError { + SimpleException::new_msg(ExcType::TypeError, "map() must have at least two arguments.".to_owned()).into() + } + + /// Creates a TypeError for exact-arity functions reporting too many *or* too few. + /// + /// Matches CPython's `PyArg_UnpackTuple` wording for fixed-arity callables + /// (e.g. `sorted`): + /// `{name} expected {exact} argument, got {actual}` (singular when exact=1) + /// `{name} expected {exact} arguments, got {actual}` (plural otherwise) + /// + /// Use this for the macro's `expected_exact` attribute. + #[must_use] + fn type_error_expected_exact(name: &str, exact: usize, actual: usize) -> RunError { + let plural = if exact == 1 { "" } else { "s" }; + SimpleException::new_msg( + ExcType::TypeError, + format!("{name} expected {exact} argument{plural}, got {actual}"), + ) + .into() + } + + /// Creates a TypeError for missing positional arguments. + /// + /// Matches CPython's format: `{name}() missing {count} required positional argument(s): 'a' and 'b'` + #[must_use] + fn type_error_missing_positional_with_names(name: &str, missing_names: &[&str]) -> RunError { + SimpleException::new_msg(ExcType::TypeError, Self::missing_positional_msg(name, missing_names)).into() + } + + /// Message body for [`type_error_missing_positional_with_names`], exposed + /// separately so `args/bind_python.rs` can attach a call position to the same + /// CPython-exact wording. + #[must_use] + fn missing_positional_msg(name: &str, missing_names: &[&str]) -> String { + let count = missing_names.len(); + let names_str = format_param_names(missing_names); + if count == 1 { + format!("{name}() missing 1 required positional argument: {names_str}") + } else { + format!("{name}() missing {count} required positional arguments: {names_str}") + } + } + + /// Creates a TypeError for missing keyword-only arguments. + /// + /// Matches CPython's format: `{name}() missing {count} required keyword-only argument(s): 'a' and 'b'` + #[must_use] + fn type_error_missing_kwonly_with_names(name: &str, missing_names: &[&str]) -> RunError { + let count = missing_names.len(); + let names_str = format_param_names(missing_names); + if count == 1 { + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() missing 1 required keyword-only argument: {names_str}"), + ) + .into() + } else { + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() missing {count} required keyword-only arguments: {names_str}"), + ) + .into() + } + } + + /// Creates a TypeError for too many positional arguments to a callable whose + /// positional count is a range (some positional parameters have defaults). + /// + /// Matches CPython's pure-Python `def` wording: when `min == max` it emits + /// `{name}() takes {max} positional argument(s) but {actual} was/were given`; + /// otherwise `{name}() takes from {min} to {max} positional arguments but + /// {actual} were given` (always-plural "arguments" in the range form). Both + /// get the `(and N keyword-only argument(s))` suffix when `kwonly_given > 0`. + /// Used by `FromArgs` structs marked `py_def` and by user `def` bindings. + #[must_use] + fn type_error_too_many_positional_range( + name: &str, + min: usize, + max: usize, + actual: usize, + kwonly_given: usize, + ) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + Self::too_many_positional_range_msg(name, min, max, actual, kwonly_given), + ) + .into() + } + + /// Message body for [`type_error_too_many_positional_range`], exposed + /// separately so `args/bind_python.rs` can attach a call position to the same + /// CPython-exact wording. + #[must_use] + fn too_many_positional_range_msg(name: &str, min: usize, max: usize, actual: usize, kwonly_given: usize) -> String { + let takes = if min == max { + // `max == 0` still reads "0 positional arguments" (plural) in CPython. + let takes_word = if max == 1 { "argument" } else { "arguments" }; + format!("{max} positional {takes_word}") + } else { + format!("from {min} to {max} positional arguments") + }; + if kwonly_given > 0 { + // CPython includes keyword-only args in the "given" part when present + let given_word = if actual == 1 { "argument" } else { "arguments" }; + let kwonly_word = if kwonly_given == 1 { "argument" } else { "arguments" }; + format!( + "{name}() takes {takes} but {actual} positional {given_word} (and {kwonly_given} keyword-only {kwonly_word}) were given" + ) + } else { + let was_were = if actual == 1 { "was" } else { "were" }; + format!("{name}() takes {takes} but {actual} {was_were} given") + } + } + + /// Creates a TypeError for positional-only parameter passed as keyword. + /// + /// Matches CPython's format: `{name}() got some positional-only arguments passed as keyword arguments: '{param}'` + #[must_use] + fn type_error_positional_only(name: &str, param: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() got some positional-only arguments passed as keyword arguments: '{param}'"), + ) + .into() + } + + /// Creates a TypeError for duplicate argument. + /// + /// Matches CPython's format: `{name}() got multiple values for argument '{param}'` + #[must_use] + fn type_error_duplicate_arg(name: &str, param: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() got multiple values for argument '{param}'"), + ) + .into() + } + + /// Creates a TypeError for duplicate keyword argument. + /// + /// Matches CPython's format: `{name}() got multiple values for keyword argument '{key}'` + #[must_use] + fn type_error_multiple_values(name: &str, key: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() got multiple values for keyword argument '{key}'"), + ) + .into() + } + + /// Creates a TypeError for when a positional argument conflicts with a keyword argument + /// of the same name in a C-implemented type constructor. + /// + /// Matches CPython's `PyArg_ParseTupleAndKeywords` format: + /// `argument for function given by name ('{key}') and position ({pos})` + /// + /// The position is 1-indexed, matching CPython's convention. The `func_descriptor` is + /// typically `"function"` for most C types (like `datetime`), matching CPython's generic + /// wording for `PyArg_ParseTupleAndKeywords`. + #[must_use] + fn type_error_positional_keyword_conflict(func_descriptor: &str, key: &str, pos: usize) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("argument for {func_descriptor} given by name ('{key}') and position ({pos})"), + ) + .into() + } + + /// Creates a TypeError for unexpected keyword argument. + /// + /// Matches CPython's format: `{name}() got an unexpected keyword argument '{key}'` + #[must_use] + fn type_error_unexpected_keyword(name: &str, key: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() got an unexpected keyword argument '{key}'"), + ) + .into() + } + + /// Creates a TypeError for unexpected keyword argument in C-implemented types. + /// + /// Matches CPython's `PyArg_ParseTupleAndKeywords` format: + /// `this function got an unexpected keyword argument '{key}'` + #[must_use] + fn type_error_c_unexpected_keyword(key: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("this function got an unexpected keyword argument '{key}'"), + ) + .into() + } + + /// Creates a TypeError for too many arguments to a C-implemented type. + /// + /// Matches CPython's `PyArg_ParseTupleAndKeywords` format: + /// `function takes at most {max} arguments ({actual} given)` + #[must_use] + fn type_error_c_at_most(max: usize, actual: usize) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("function takes at most {max} arguments ({actual} given)"), + ) + .into() + } + + /// Variant of [`type_error_c_at_most`] used by C constructors that explicitly + /// say "positional arguments" (e.g. `datetime`): + /// `function takes at most {max} positional arguments ({actual} given)` + #[must_use] + fn type_error_c_at_most_positional(max: usize, actual: usize) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("function takes at most {max} positional arguments ({actual} given)"), + ) + .into() + } + + /// Hybrid wording used by C constructors that mix positional-or-keyword + /// slots with keyword-only slots (e.g. `datetime`, where `fold` is + /// keyword-only). CPython's `PyArg_ParseTupleAndKeywords` emits two + /// distinct messages depending on whether the caller could conceivably + /// have meant the overflow args to fill the keyword-only tail: + /// + /// - `actual <= max_total`: the extra positionals *could* have filled the + /// trailing keyword-only slots, so the error pins blame on positional + /// overflow specifically — `function takes at most {max_pos} positional + /// arguments ({actual} given)`. + /// - `actual > max_total`: there is no slot of any kind for the extras, + /// so the error reports the total slot count without the "positional" + /// qualifier — `function takes at most {max_total} arguments ({actual} + /// given)`. + /// + /// `max_pos` is the number of positional-or-keyword slots; `max_total` + /// adds the trailing keyword-only slot count. When `max_total == max_pos` + /// (no kw-only fields) this collapses to [`type_error_c_at_most_positional`]. + #[must_use] + fn type_error_c_at_most_positional_or_total(max_pos: usize, max_total: usize, actual: usize) -> RunError { + if actual > max_total && max_total > max_pos { + Self::type_error_c_at_most(max_total, actual) + } else { + Self::type_error_c_at_most_positional(max_pos, actual) + } + } + + /// Creates a TypeError for a missing required argument in a C-implemented type. + /// + /// Matches CPython's `PyArg_ParseTupleAndKeywords` format: + /// `function missing required argument '{arg_name}' (pos {pos})` + #[must_use] + fn type_error_c_missing_required(arg_name: &str, pos: usize) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("function missing required argument '{arg_name}' (pos {pos})"), + ) + .into() + } + + /// Creates a TypeError for a missing required argument in a C-implemented type, + /// with a function name prefix. + /// + /// Matches CPython's format for types like `timezone`: + /// `{name}() missing required argument '{arg_name}' (pos {pos})` + #[must_use] + fn type_error_c_missing_required_named(name: &str, arg_name: &str, pos: usize) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() missing required argument '{arg_name}' (pos {pos})"), + ) + .into() + } + + /// Named positional-overflow wording used by clinic functions with + /// keyword-only slots (e.g. `os.stat`/`os.mkdir`): `{name}() takes + /// {exactly|at most} {max} positional argument{s} ({actual} given)` — + /// "exactly" when every positional param is required, and `takes no + /// positional arguments` when there are none (`DirEntry.is_dir`). + #[must_use] + fn type_error_named_positional(name: &str, max: usize, actual: usize, exact: bool) -> RunError { + let message = if max == 0 { + // `_PyArg_UnpackKeywords` drops the count for keyword-only signatures. + format!("{name}() takes no positional arguments") + } else { + let qualifier = if exact { "exactly" } else { "at most" }; + let plural = if max == 1 { "" } else { "s" }; + format!("{name}() takes {qualifier} {max} positional argument{plural} ({actual} given)") + }; + SimpleException::new_msg(ExcType::TypeError, message).into() + } + + /// Creates a TypeError matching the `os` module's `path_t` converter: + /// `{func}: {arg} should be {accepted}, not {type}` — `accepted` is the + /// per-function accepted-types phrase (e.g. `string, bytes or os.PathLike`). + #[must_use] + fn type_error_os_path(func: &str, arg: &str, accepted: &str, type_name: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("{func}: {arg} should be {accepted}, not {type_name}"), + ) + .into() + } + + /// Creates `FileNotFoundError: [Errno 2] No such file or directory: '{path}'`, + /// as raised by `os.chdir('')` without consulting the host. + #[must_use] + fn file_not_found_error(path: &str) -> RunError { + SimpleException::new_msg( + ExcType::FileNotFoundError, + format!("[Errno 2] No such file or directory: {}", StringRepr(path)), + ) + .into() + } + + /// Creates `NotADirectoryError: [Errno 20] Not a directory: '{path}'`, as + /// raised by `os.chdir` when the host's stat result is not a directory. + #[must_use] + fn not_a_directory_error(path: &str) -> RunError { + SimpleException::new_msg( + ExcType::NotADirectoryError, + format!("[Errno 20] Not a directory: {}", StringRepr(path)), + ) + .into() + } + + /// Creates `genericpath._check_arg_types`'s TypeError for an `os.path` + /// argument that is neither `str` nor `bytes`: + /// `{func}() argument must be str, bytes, or os.PathLike object, not '{type}'` + #[must_use] + fn type_error_path_argument(func: &str, type_name: &str) -> RunError { + Self::type_error(format!( + "{func}() argument must be str, bytes, or os.PathLike object, not '{type_name}'" + )) + } + + /// Creates `genericpath._check_arg_types`'s TypeError for `os.path` + /// arguments mixing `str` and `bytes`: + /// `Can't mix strings and bytes in path components` + #[must_use] + fn type_error_mixed_path_components() -> RunError { + Self::type_error("Can't mix strings and bytes in path components") + } + + /// Creates the `os.fspath` TypeError, also raised by pure-Python `os` + /// functions that call `fspath` internally (e.g. `os.makedirs`): + /// `expected str, bytes or os.PathLike object, not {type}`. + /// + /// `bytes`, which CPython accepts and Monty refuses, gets the phrase + /// narrowed to what Monty takes, as the `os` path converter does. + #[must_use] + fn type_error_fspath(type_name: &str) -> RunError { + let accepted = if type_name == "bytes" { + "str or os.PathLike" + } else { + "str, bytes or os.PathLike" + }; + SimpleException::new_msg( + ExcType::TypeError, + format!("expected {accepted} object, not {type_name}"), + ) + .into() + } + + /// Creates the `dir_fd` converter TypeError: + /// `argument should be integer or None, not {type}` + #[must_use] + fn type_error_dir_fd(type_name: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("argument should be integer or None, not {type_name}"), + ) + .into() + } + + /// Creates the fd converter's OverflowError for fds above C `int` range: + /// `fd is greater than maximum` (CPython's `_fd_converter`). + #[must_use] + fn overflow_fd_maximum() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "fd is greater than maximum").into() + } + + /// Creates the fd converter's OverflowError for fds below C `int` range: + /// `fd is less than minimum` (CPython's `_fd_converter`). + #[must_use] + fn overflow_fd_minimum() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "fd is less than minimum").into() + } + + /// Creates `OSError: [Errno 9] Bad file descriptor`, naming the fd when + /// the call does (`os.stat(fd)` does, `os.listdir(fd)` does not). Every + /// fd is closed in the sandbox, so this is what an int path fails with. + #[must_use] + fn bad_file_descriptor(fd: Option<&str>) -> RunError { + let msg = match fd { + Some(fd) => format!("[Errno 9] Bad file descriptor: {fd}"), + None => "[Errno 9] Bad file descriptor".to_owned(), + }; + SimpleException::new_msg(ExcType::OSError, msg).into() + } + + /// Creates the NotImplementedError CPython raises when an `os` argument is + /// unsupported on the platform (`argument_unavailable_error`): + /// `{func}: {arg} unavailable on this platform`, or just + /// `{arg} unavailable on this platform` when `func` is `None`. + /// Monty raises it for `dir_fd`/`follow_symlinks`, which it never supports. + #[must_use] + fn not_implemented_os_arg(func: Option<&str>, arg: &str) -> RunError { + let msg = match func { + Some(func) => format!("{func}: {arg} unavailable on this platform"), + None => format!("{arg} unavailable on this platform"), + }; + Self::not_implemented(msg).into() + } + + /// Creates a TypeError for a missing required argument without a position, + /// as raised by hand-written vectorcall fast paths like `enumerate`: + /// `{name}() missing required argument '{arg_name}'` + #[must_use] + fn type_error_missing_required_no_pos(name: &str, arg_name: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() missing required argument '{arg_name}'"), + ) + .into() + } + + /// Creates a TypeError for a keyword rejected by a hand-written vectorcall + /// fast path (CPython's `enumerate` wording, distinct from the parser + /// families' "unexpected keyword argument"): + /// `'{key}' is an invalid keyword argument for {name}()` + #[must_use] + fn type_error_invalid_keyword_argument(name: &str, key: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("'{key}' is an invalid keyword argument for {name}()"), + ) + .into() + } + + /// Creates a TypeError matching CPython's `_PyArg_BadArgument` + /// positional-style wording: `{name}() argument {pos} must be + /// {expected}, not {got}`. + /// + /// Used by the `#[derive(FromArgs)]` macro when the struct opts into + /// `bad_arg` errors — emitted in place of the inner [`FromValue`] + /// failure so the caller sees the same wording as CPython's C-implemented + /// functions (e.g. `strftime() argument 1 must be str, not None`). + /// + /// The `got` type label should come from `Type::cpython_arg_name` so + /// that `NoneType` becomes `"None"` to match CPython's special case. + /// + /// [`FromValue`]: crate::args::FromValue + #[must_use] + fn type_error_bad_arg_pos(name: &str, pos: usize, expected: &str, got: impl fmt::Display) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() argument {pos} must be {expected}, not {got}"), + ) + .into() + } + + /// Creates a TypeError matching CPython's `_PyArg_BadArgument` + /// named-style wording: `{name}() argument '{arg_name}' must be + /// {expected}, not {got}`. + /// + /// CPython uses this form for C-implemented functions that register + /// their arguments by name (`open`, `str.encode`, `bytes.decode`, …). + /// Sibling to [`type_error_bad_arg_pos`]; pick the variant matching the + /// CPython output for the function being modelled. + #[must_use] + fn type_error_bad_arg_named(name: &str, arg_name: &str, expected: &str, got: impl fmt::Display) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() argument '{arg_name}' must be {expected}, not {got}"), + ) + .into() + } + + /// Creates a TypeError for **kwargs argument that is not a mapping. + /// + /// Matches CPython's format: `{name}() argument after ** must be a mapping, not {type_name}` + #[must_use] + fn type_error_kwargs_not_mapping(name: &str, type_name: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("{name}() argument after ** must be a mapping, not {type_name}"), + ) + .into() + } + + /// Creates a TypeError for `{**x}` dict-literal unpacking where `x` is not a mapping. + /// + /// Matches CPython's format: `'{type_name}' object is not a mapping` + /// + /// Note: this differs from [`type_error_kwargs_not_mapping`] which is used for + /// function-call `**kwargs` and includes the function name in the message. + #[must_use] + fn type_error_not_mapping(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not a mapping")).into() + } + + /// Creates a TypeError for **kwargs with non-string keys. + /// + /// Matches CPython exactly: `keywords must be strings`, unqualified — the + /// call machinery raises before the callee is entered, so no name is shown. + #[must_use] + fn type_error_kwargs_nonstring_key() -> RunError { + SimpleException::new_msg(ExcType::TypeError, "keywords must be strings").into() + } + + /// Creates a TypeError for an invalid `tzinfo` argument. + /// + /// Matches CPython: `tzinfo argument must be None or of a tzinfo subclass, not type 'int'` + #[must_use] + fn type_error_tzinfo(ty: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("tzinfo argument must be None or of a tzinfo subclass, not type '{ty}'"), + ) + .into() + } + + /// Creates a simple TypeError with a custom message. + #[must_use] + fn type_error(msg: impl fmt::Display) -> RunError { + SimpleException::new_msg(ExcType::TypeError, msg).into() + } + + /// Creates the TypeError raised when a `with` statement's context expression + /// does not implement the context-manager protocol. + /// + /// Matches CPython 3.14's wording, which names the specific missing dunder: + /// `__exit__` when the protocol check fails outright (`BeforeWith`'s + /// [`py_is_context_manager`](crate::types::PyTrait::py_is_context_manager) + /// gate), `__enter__` when a user class defines `__exit__` but not + /// `__enter__`. + #[must_use] + fn type_error_not_context_manager(type_name: impl Display, missing_dunder: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!( + "'{type_name}' object does not support the context manager protocol (missed {missing_dunder} method)" + ), + ) + .into() + } + + /// Creates a TypeError for `__init__` returning a value other than `None`. + /// + /// Matches CPython's format: `TypeError: __init__() should return None, not '{type}'` + #[must_use] + fn type_error_init_return(type_name: impl Display) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("__init__() should return None, not '{type_name}'"), + ) + .into() + } + + /// `ValueError: mapping pattern checks duplicate key ()`: two keys of + /// one mapping pattern compared equal at run time (`case {A: x, B: y}` with + /// `A == B`), as CPython's `MATCH_KEYS` reports it. + fn value_error_duplicate_mapping_key(key: &Value, vm: &mut VM<'_>) -> RunError { + let repr = match key.py_repr(vm) { + Ok(repr_value) => { + defer_drop!(repr_value, vm); + repr_value + .to_str(vm) + .map_or_else(|_| format!("<{}>", key.py_type_name(vm)), str::to_owned) + } + Err(err) => return err, + }; + SimpleException::new_msg( + ExcType::ValueError, + format!("mapping pattern checks duplicate key ({repr})"), + ) + .into() + } + + /// Creates a generic `ValueError` with a custom message. + fn value_error(msg: impl fmt::Display) -> RunError { + SimpleException::new_msg(ExcType::ValueError, msg).into() + } + + /// Creates a generic `IndexError` with a custom message. + fn index_error(msg: impl fmt::Display) -> RunError { + SimpleException::new_msg(ExcType::IndexError, msg).into() + } + + /// `random.seed()` / `random.Random()` given something other than + /// `None`, an int, a float, a `str` or `bytes`. + fn random_seed_type() -> RunError { + Self::type_error("The only supported seed types are:\nNone, int, float, str, bytes, and bytearray.") + } + + /// The `OverflowError` `time.sleep()` raises for a length past the roughly + /// 292 years `PyTime_t` can represent: `timestamp out of range for C PyTime_t`. + #[must_use] + fn sleep_too_long() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "timestamp out of range for C PyTime_t").into() + } + + /// The `OverflowError` the `time` conversion functions raise for epoch + /// seconds outside the range a broken-down time can hold: + /// `timestamp out of range for platform time_t`. + #[must_use] + fn timestamp_out_of_range() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "timestamp out of range for platform time_t").into() + } + + /// `time.mktime()`'s `OverflowError` for a wall clock it cannot place on + /// the epoch: `mktime argument out of range`. + #[must_use] + fn mktime_out_of_range() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "mktime argument out of range").into() + } + + /// The `TypeError` the `time` conversion functions raise for a time tuple of + /// the wrong length: `{name}(): illegal time tuple argument`. + #[must_use] + fn illegal_time_tuple(name: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("{name}(): illegal time tuple argument")).into() + } + + /// Creates a TypeError for bytes() constructor with invalid type. + /// + /// Matches CPython's format: `TypeError: cannot convert '{type}' object to bytes` + #[must_use] + fn type_error_bytes_init(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("cannot convert '{type_}' object to bytes")).into() + } + + /// Creates a TypeError for calling a non-callable type. + /// + /// Matches CPython's format: `TypeError: cannot create '{type}' instances` + #[must_use] + fn type_error_not_callable(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("cannot create '{type_}' instances")).into() + } + + /// Creates a TypeError for calling a non-callable object. + /// + /// Matches CPython's format: `TypeError: '{type}' object is not callable` + #[must_use] + fn type_error_not_callable_object(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not callable")).into() + } + + /// Creates a TypeError for non-iterable type in list/tuple/etc constructors. + /// + /// Matches CPython's format: `TypeError: '{type}' object is not iterable` + #[must_use] + fn type_error_not_iterable(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not iterable")).into() + } + + /// Creates the ValueError `itertools.islice(it, stop)` raises for a `stop` + /// that is neither `None` nor an index — the two-argument wording, which + /// names the stop argument specifically. + #[must_use] + fn islice_bad_stop() -> RunError { + Self::value_error("Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.") + } + + /// Creates the ValueError `itertools.islice` raises for a bad `start` or + /// `stop` in the three-or-more argument form, where CPython stops naming + /// which of them was at fault. + #[must_use] + fn islice_bad_indices() -> RunError { + Self::value_error("Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.") + } + + /// Creates the ValueError `itertools.batched` raises when `n` is below one. + #[must_use] + fn batched_bad_n() -> RunError { + Self::value_error("n must be at least one") + } + + /// Creates the ValueError `itertools.batched(..., strict=True)` raises when + /// the source runs out part-way through a batch. + #[must_use] + fn batched_incomplete() -> RunError { + Self::value_error("batched(): incomplete batch") + } + + /// Creates the ValueError the combinatoric `itertools` constructors raise + /// for a negative `r`. + #[must_use] + fn combinatoric_negative_r() -> RunError { + Self::value_error("r must be non-negative") + } + + /// Creates the TypeError `itertools.permutations` raises for an `r` that is + /// neither `None` nor an `int` — it checks the type rather than `__index__`. + #[must_use] + fn permutations_bad_r() -> RunError { + Self::type_error("Expected int as r") + } + + /// Creates the RuntimeError a `tee` raises when one of its iterators is + /// stepped from inside the source read of another. + #[must_use] + fn tee_reentered() -> RunError { + SimpleException::new_msg(ExcType::RuntimeError, "cannot re-enter the tee iterator").into() + } + + /// Creates the ValueError `itertools.tee` raises for a negative `n`. + #[must_use] + fn tee_negative_n() -> RunError { + Self::value_error("n must be >= 0") + } + + /// Creates the ValueError `itertools.product` raises for a negative `repeat`. + #[must_use] + fn product_negative_repeat() -> RunError { + Self::value_error("repeat argument cannot be negative") + } + + /// Creates the OverflowError `itertools.product` raises when `repeat` puts + /// its index array beyond what a `Py_ssize_t` can address. + #[must_use] + fn product_repeat_too_large() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "repeat argument too large").into() + } + + /// Creates the message-less `MemoryError` CPython raises when an allocation + /// is too large to attempt at all, rather than merely too large to fit the + /// sandbox's budget — `combinations_with_replacement('a', 2**62)`. + #[must_use] + fn allocation_too_large() -> RunError { + SimpleException::new(ExcType::MemoryError, None).into() + } + + /// Creates the ValueError `itertools.islice` raises for a non-positive or + /// non-integer `step`. + #[must_use] + fn islice_bad_step() -> RunError { + Self::value_error("Step for islice() must be a positive integer or None.") + } + + /// Creates the TypeError `functools.partial()` raises when called with no + /// positional argument, so there is no callable to wrap. + #[must_use] + fn partial_needs_argument() -> RunError { + Self::type_error("type 'partial' takes at least one argument") + } + + /// Creates the TypeError `functools.partial()` raises for a first argument + /// that is not callable. + #[must_use] + fn partial_not_callable() -> RunError { + Self::type_error("the first argument must be callable") + } + + /// Creates the TypeError `collections.defaultdict()` raises for a + /// `default_factory` that is neither callable nor `None` — raised both when + /// constructing one and when `deepcopy` rebuilds the factory. + #[must_use] + fn defaultdict_factory_not_callable() -> RunError { + Self::type_error("first argument must be callable or None") + } + + /// Creates a TypeError for the right operand of `in` / `not in` supporting + /// neither `__contains__` nor iteration. + /// + /// Matches CPython's format: `TypeError: argument of type '{type}' is not a + /// container or iterable` + #[must_use] + fn type_error_not_container(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("argument of type '{type_}' is not a container or iterable"), + ) + .into() + } + + /// Creates a TypeError for a class opting out of `in` with + /// `__contains__ = None`. + /// + /// Matches CPython's `slot_sq_contains` format: `TypeError: '{type}' object + /// is not a container` — deliberately distinct from + /// [`type_error_not_container`], which covers a type that never had + /// `__contains__` at all. + #[must_use] + fn type_error_object_not_container(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not a container")).into() + } + + /// Creates a TypeError when `next()` receives a non-iterator. + /// + /// Matches CPython's format: `TypeError: '{type}' object is not an iterator` + #[must_use] + fn type_error_not_iterator(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not an iterator")).into() + } + + /// Creates a TypeError for a user `__iter__` returning a non-iterator. + /// + /// Matches CPython's format: `TypeError: iter() returned non-iterator of type '{type}'` + #[must_use] + fn type_error_iter_returned_non_iterator(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("iter() returned non-iterator of type '{type_}'"), + ) + .into() + } + + /// Creates a TypeError for non-iterable type in PEP 448 `*value` literal unpack. + /// + /// Used when `[*expr]`, `(*expr,)` literal unpack encounters a non-iterable — distinct + /// from [`type_error_not_iterable`] because CPython uses a different message for this context. + /// + /// Matches CPython's format: `TypeError: Value after * must be an iterable, not {type}` + #[must_use] + fn type_error_value_after_star(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("Value after * must be an iterable, not {type_}"), + ) + .into() + } + + /// Creates a TypeError for int() constructor with invalid type. + /// + /// Matches CPython's format: `TypeError: int() argument must be a string, a bytes-like object or a real number, not '{type}'` + #[must_use] + fn type_error_int_conversion(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("int() argument must be a string, a bytes-like object or a real number, not '{type_}'"), + ) + .into() + } + + /// Reports an absent rounding or truncation hook without coercing the operand. + #[must_use] + fn type_error_missing_numeric_dunder(type_: &str, dunder: &str) -> RunError { + Self::type_error(format!("type {type_} doesn't define {dunder} method")) + } + + /// Reports an invalid result from an integer conversion hook. + #[must_use] + fn type_error_non_int_return(dunder: &str, type_: &str) -> RunError { + Self::type_error(format!("{dunder} returned non-int (type {type_})")) + } + + /// Reports a non-numeric argument to a real-valued math function. + #[must_use] + fn type_error_not_real_number(type_: &str) -> RunError { + Self::type_error(format!("must be real number, not {type_}")) + } + + /// Creates a TypeError for float() constructor with invalid type. + /// + /// Matches CPython's format: `TypeError: float() argument must be a string or a real number, not '{type}'` + #[must_use] + fn type_error_float_conversion(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("float() argument must be a string or a real number, not '{type_}'"), + ) + .into() + } + + /// Creates a ValueError for negative count in bytes(). + /// + /// Matches CPython's format: `ValueError: negative count` + #[must_use] + fn value_error_negative_bytes_count() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "negative count").into() + } + + /// Creates the `ValueError` CPython's float-to-string conversion raises for a + /// precision above `MAX_FLOAT_PRECISION` (`INT_MAX - 1024`). + /// + /// Matches CPython's format: `ValueError: precision too big` + #[must_use] + fn value_error_precision_too_big() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "precision too big").into() + } + + /// Creates a TypeError for isinstance() arg 2. + /// + /// Matches CPython's format: `TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union` + #[must_use] + fn isinstance_arg2_error() -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + "isinstance() arg 2 must be a type, a tuple of types, or a union", + ) + .into() + } + + /// Creates a TypeError for invalid exception type in except clause. + /// + /// Matches CPython's format: `TypeError: catching classes that do not inherit from BaseException is not allowed` + #[must_use] + fn except_invalid_type_error() -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + "catching classes that do not inherit from BaseException is not allowed", + ) + .into() + } + + /// Creates a ValueError for range() step argument being zero. + /// + /// Matches CPython's format: `ValueError: range() arg 3 must not be zero` + #[must_use] + fn value_error_range_step_zero() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "range() arg 3 must not be zero").into() + } + + /// Creates a ValueError for slice step being zero. + /// + /// Matches CPython's format: `ValueError: slice step cannot be zero` + #[must_use] + fn value_error_slice_step_zero() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "slice step cannot be zero").into() + } + + /// Creates a TypeError for slice indices that are not integers or None. + /// + /// Matches CPython's format: `TypeError: slice indices must be integers or None or have an __index__ method` + #[must_use] + fn type_error_slice_indices() -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + "slice indices must be integers or None or have an __index__ method", + ) + .into() + } + + /// Creates a RuntimeError for dict mutation during iteration. + /// + /// Matches CPython's format: `RuntimeError: dictionary changed size during iteration` + #[must_use] + fn runtime_error_dict_changed_size() -> RunError { + SimpleException::new_msg(ExcType::RuntimeError, "dictionary changed size during iteration").into() + } + + /// Creates a RuntimeError for a dict whose keys were replaced mid-iteration. + /// + /// CPython's second iteration guard: the size never changed, but a delete + /// plus an insert renumbered the table under the cursor. + /// + /// Matches CPython's format: `RuntimeError: dictionary keys changed during iteration` + #[must_use] + fn runtime_error_dict_changed_keys() -> RunError { + SimpleException::new_msg(ExcType::RuntimeError, "dictionary keys changed during iteration").into() + } + + /// Creates a TypeError for `reversed()` on a non-reversible object. + /// + /// Matches CPython's format: `TypeError: '{type}' object is not reversible` + #[must_use] + fn type_error_not_reversible(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("'{type_}' object is not reversible")).into() + } + + /// Creates a RuntimeError for set mutation during iteration. + /// + /// Matches CPython's format: `RuntimeError: Set changed size during iteration` + #[must_use] + fn runtime_error_set_changed_size() -> RunError { + SimpleException::new_msg(ExcType::RuntimeError, "Set changed size during iteration").into() + } + + /// Creates a TypeError for functions that don't accept keyword arguments. + /// + /// Matches CPython's `PyArg_NoKeywords` format: `TypeError: {name}() takes + /// no keyword arguments`. CPython checks keywords before the positional + /// count, so a no-argument method given only a kwarg reports this rather + /// than `(0 given)`. + #[must_use] + fn type_error_no_kwargs(name: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("{name}() takes no keyword arguments")).into() + } + + /// Creates a NotImplementedError for functions that don't accept keyword arguments. + #[must_use] + fn kwargs_not_implemented(name: &str) -> RunError { + SimpleException::new_msg( + ExcType::NotImplementedError, + format!("{name}() does not yet support keyword arguments"), + ) + .into() + } + + /// A `_csv.Error` with the given message. + fn csv_error(msg: impl fmt::Display) -> RunError { + SimpleException::new_msg(ExcType::CsvError, msg).into() + } + + /// The `_csv.Error` for a dialect name that is not registered. + fn csv_unknown_dialect() -> RunError { + Self::csv_error("unknown dialect") + } + + /// A trapped `decimal` signal: the class plus C `_decimal`'s list of conditions, + /// `[]`. + fn decimal_signal(exc_type: ExcType, message: String) -> RunError { + SimpleException::new_msg(exc_type, message).into() + } + + /// The `TypeError` for an operand a `decimal` method cannot convert implicitly. + fn decimal_conversion(type_name: &str) -> RunError { + Self::type_error(format!("conversion from {type_name} to Decimal is not supported")) + } + + /// The `TypeError` for a `context` argument that is not a `decimal.Context`. + fn decimal_optional_context() -> RunError { + Self::type_error("optional argument must be a context") + } + + /// The `TypeError` for a rounding mode that is not one of the eight `ROUND_*` strings. + fn decimal_invalid_rounding() -> RunError { + Self::type_error( + "valid values for rounding are:\n [ROUND_CEILING, ROUND_FLOOR, ROUND_UP, ROUND_DOWN,\n \ + ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,\n ROUND_05UP]", + ) + } + + /// The `KeyError` for a `flags` / `traps` key that is not one of the nine signals. + fn decimal_invalid_signal() -> RunError { + SimpleException::new_msg( + ExcType::KeyError, + "valid values for signals are:\n [InvalidOperation, FloatOperation, DivisionByZero,\n \ + Overflow, Underflow, Subnormal, Inexact, Rounded,\n Clamped]", + ) + .into() + } + + /// The `KeyError` for a dict assigned to `flags` / `traps` without exactly the nine signals. + fn decimal_invalid_signal_dict() -> RunError { + SimpleException::new_msg(ExcType::KeyError, "invalid signal dict").into() + } + + /// Unpacking a sequence of the wrong length: `not enough values to unpack + /// (expected 2, got 1)` or `too many values to unpack (expected 2, got 3)`. + fn unpack_size_error(expected: usize, actual: usize) -> RunError { + let message = if actual < expected { + format!("not enough values to unpack (expected {expected}, got {actual})") + } else { + format!("too many values to unpack (expected {expected}, got {actual})") + }; + SimpleException::new_msg(ExcType::ValueError, message).into() + } + + /// C's `PyArg_ParseTuple` arity error for a fixed-arity method: `function takes + /// exactly 2 arguments (1 given)`. + fn type_error_function_exact(expected: usize, actual: usize) -> RunError { + let plural = if expected == 1 { "argument" } else { "arguments" }; + Self::type_error(format!("function takes exactly {expected} {plural} ({actual} given)")) + } + + /// Creates an IndexError for list index out of range (getitem). + /// + /// Matches CPython's format: `IndexError('list index out of range')` + #[must_use] + fn list_index_error() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "list index out of range").into() + } + + /// Creates an IndexError for list assignment index out of range (setitem). + /// + /// Matches CPython's format: `IndexError('list assignment index out of range')` + #[must_use] + fn list_assignment_index_error() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "list assignment index out of range").into() + } + + /// Creates an IndexError for tuple index out of range. + /// + /// Matches CPython's format: `IndexError('tuple index out of range')` + #[must_use] + fn tuple_index_error() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "tuple index out of range").into() + } + + /// Creates an IndexError for string index out of range. + /// + /// Matches CPython's format: `IndexError('string index out of range')` + #[must_use] + fn str_index_error() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "string index out of range").into() + } + + /// Creates an IndexError for bytes index out of range. + /// + /// Matches CPython's format: `IndexError('index out of range')` + #[must_use] + fn bytes_index_error() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "index out of range").into() + } + + /// Creates an IndexError for range index out of range. + /// + /// Matches CPython's format: `IndexError('range object index out of range')` + #[must_use] + fn range_index_error() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "range object index out of range").into() + } + + /// Creates an IndexError for `re.Match` group index out of range. + /// + /// Matches CPython's format: `IndexError('no such group')` + #[must_use] + fn re_match_group_index_error() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "no such group").into() + } + + /// Creates a TypeError for subscripting a sequence with a non-integer key. + /// + /// CPython words this per type: `list indices must be integers or slices, not str` + /// for `list`, `tuple` and `range`, the same with `byte` for `bytes`, and + /// `string indices must be integers, not 'str'` for `str`. + #[must_use] + fn type_error_indices(container: Type, index_type: &str) -> RunError { + let message = match container { + Type::Str => format!("string indices must be integers, not '{index_type}'"), + Type::Bytes => format!("byte indices must be integers or slices, not {index_type}"), + _ => format!("{container} indices must be integers or slices, not {index_type}"), + }; + SimpleException::new_msg(ExcType::TypeError, message).into() + } + + /// Creates a NameError for accessing a free variable (nonlocal/closure) before it's assigned. + /// + /// Matches CPython's format: `NameError: cannot access free variable 'x' where it is not + /// associated with a value in enclosing scope` + #[must_use] + fn name_error_free_variable(name: &str) -> SimpleException { + SimpleException::new_msg( + ExcType::NameError, + format!("cannot access free variable '{name}' where it is not associated with a value in enclosing scope"), + ) + } + + /// Creates a NameError for accessing an undefined variable. + /// + /// Matches CPython's format: `NameError: name 'x' is not defined` + #[must_use] + fn name_error(name: &str) -> SimpleException { + let mut msg = format!("name '{name}' is not defined"); + // add the same suffix as cpython, but only for the modules supported by Monty + if matches!(name, "asyncio" | "sys" | "typing" | "types" | "re" | "json") { + write!(&mut msg, ". Did you forget to import '{name}'?").unwrap(); + } + SimpleException::new_msg(ExcType::NameError, msg) + } + + /// Creates an UnboundLocalError for accessing a local variable before assignment. + /// + /// Matches CPython's format: `UnboundLocalError: cannot access local variable 'x' where it is not associated with a value` + #[must_use] + fn unbound_local_error(name: &str) -> SimpleException { + SimpleException::new_msg( + ExcType::UnboundLocalError, + format!("cannot access local variable '{name}' where it is not associated with a value"), + ) + } + + /// Creates `ModuleNotFoundError: No module named 'name'`, with + /// `; 'parent' is not a package` when a dotted import failed below a + /// module (see `StandardLib::missing_module`). + /// Sets `hide_caret: true` because CPython doesn't show carets for module not found errors. + #[must_use] + fn module_not_found_error(module_name: &str, parent: Option<&str>) -> RunError { + let msg = match parent { + Some(parent) => format!("{}; '{parent}' is not a package", no_module_named(module_name)), + None => no_module_named(module_name), + }; + let exc = SimpleException::new_msg(ExcType::ModuleNotFoundError, msg); + RunError::Exc(ExceptionRaise { + exc, + frame: None, + snippet_frame: None, + hide_caret: true, // CPython doesn't show carets for module not found errors + }) + } + + /// Creates a NotImplementedError for an unimplemented Python feature. + /// + /// For syntax Monty cannot parse ("The monty syntax parser does not yet support + /// {feature}") and for runtime features it refuses rather than approximates (a + /// `@dataclass` body it cannot honour). Reserve it for "Monty has not built this + /// yet" — a call CPython would also reject belongs in the matching CPython type. + #[must_use] + fn not_implemented(msg: impl fmt::Display) -> SimpleException { + SimpleException::new_msg(ExcType::NotImplementedError, msg) + } + + /// Reports a host call rejected by a synchronous VM boundary; the traceback identifies the caller. + #[must_use] + fn not_implemented_synchronous_call(kind: &str, name: &str) -> SimpleException { + Self::not_implemented(format!("{kind} '{name}' cannot suspend in this synchronous context")) + } + + /// Creates a ZeroDivisionError for division by zero. + /// + /// Matches CPython 3.14's format: `ZeroDivisionError('division by zero')` + #[must_use] + fn zero_division() -> SimpleException { + SimpleException::new_msg(ExcType::ZeroDivisionError, "division by zero") + } + + /// Creates an OverflowError for an int too large for an index-sized integer. + /// + /// This is CPython's `PyNumber_AsSsize_t` wording, used wherever a count or + /// size goes through `__index__` (repetition counts, `bytes(n)`) — unlike + /// [`Self::overflow_c_ssize_t`], which is `PyLong_AsSsize_t`'s. + #[must_use] + fn overflow_index_sized_int() -> SimpleException { + SimpleException::new_msg(ExcType::OverflowError, "cannot fit 'int' into an index-sized integer") + } + + /// Creates an IndexError for when an integer index is too large to fit in i64. + /// + /// Matches CPython's format: `IndexError: cannot fit 'int' into an index-sized integer` + #[must_use] + fn index_error_int_too_large() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "cannot fit 'int' into an index-sized integer").into() + } + + /// [`Self::index_error_int_too_large`] for a value that supplied the index + /// through `__index__`. + /// + /// CPython names the object it asked, not the `int` it got back, so an + /// instance reports its own class here. + #[must_use] + fn index_error_cannot_fit(type_name: &str) -> RunError { + SimpleException::new_msg( + ExcType::IndexError, + format!("cannot fit '{type_name}' into an index-sized integer"), + ) + .into() + } + + /// Creates an ImportError for when a name cannot be imported from a module. + /// + /// Matches CPython's format for built-in modules: + /// `ImportError: cannot import name 'name' from 'module' (unknown location)` + /// + /// Sets `hide_caret: true` because CPython doesn't show carets for import errors. + #[must_use] + fn cannot_import_name(name: &str, module_name: &str) -> RunError { + let exc = SimpleException::new_msg( + ExcType::ImportError, + format!("cannot import name '{name}' from '{module_name}' (unknown location)"), + ); + RunError::Exc(ExceptionRaise { + exc, + frame: None, + snippet_frame: None, + hide_caret: true, + }) + } + + /// Creates a ValueError when an integer is too large to convert to a decimal string. + /// + /// Matches CPython 3.11+'s `sys.int_max_str_digits` error message. + #[must_use] + fn value_error_int_too_large_for_str() -> RunError { + SimpleException::new_msg( + ExcType::ValueError, + format!( + "Exceeds the limit ({INT_MAX_STR_DIGITS} digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit" + ), + ) + .into() + } + + /// Creates a ValueError when a decimal string has too many digits for `int()` conversion. + /// + /// Includes the actual digit count to help users diagnose the issue. + #[must_use] + fn value_error_int_str_too_large(digit_count: usize) -> RunError { + SimpleException::new_msg( + ExcType::ValueError, + format!( + "Exceeds the limit ({INT_MAX_STR_DIGITS} digits) for integer string conversion: value has {digit_count} digits; use sys.set_int_max_str_digits() to increase the limit" + ), + ) + .into() + } + + /// Creates a ValueError for `int()` when a string cannot be parsed as an integer. + /// + /// Matches CPython's format: `invalid literal for int() with base {N}: '...'`. + /// `base` is the base the caller passed (0 included, before auto-detection); + /// the caller provides the value pre-formatted (e.g. via `StringRepr`). + #[must_use] + fn value_error_invalid_literal_for_int(base: u32, value: impl fmt::Display) -> RunError { + SimpleException::new_msg( + ExcType::ValueError, + format!("invalid literal for int() with base {base}: {value}"), + ) + .into() + } + + /// Creates a ValueError for an `int()` base outside `{0} ∪ 2..=36`. + /// + /// Matches CPython's message: `int() base must be >= 2 and <= 36, or 0`. + #[must_use] + fn value_error_int_base_range() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "int() base must be >= 2 and <= 36, or 0").into() + } + + /// Creates a TypeError for `int(base=N)` with no value to convert. + /// + /// Matches CPython's message: `int() missing string argument`. Raised + /// before the base is validated, matching `long_new_impl`'s ordering. + #[must_use] + fn type_error_int_missing_string_argument() -> RunError { + SimpleException::new_msg(ExcType::TypeError, "int() missing string argument").into() + } + + /// Creates a TypeError for `int(x, base)` where `x` is not str/bytes. + /// + /// Matches CPython's message: `int() can't convert non-string with explicit base`. + #[must_use] + fn type_error_int_non_string_with_base() -> RunError { + SimpleException::new_msg(ExcType::TypeError, "int() can't convert non-string with explicit base").into() + } + + /// Creates a ValueError for negative shift count in bitwise shift operations. + /// + /// Matches CPython's format: `ValueError: negative shift count` + #[must_use] + fn value_error_negative_shift_count() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "negative shift count").into() + } + + /// Creates an OverflowError when converting values to C ssize_t (i64) for operations like length checks. + /// + /// Matches CPython's format: `OverflowError: Python int too large to convert to C ssize_t` + /// Note: CPython uses this message because it tries to convert to ssize_t for the shift amount. + #[must_use] + fn overflow_c_ssize_t() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "Python int too large to convert to C ssize_t").into() + } + + /// Creates the OverflowError for an argument clinic converts to `uint64_t` + /// (`random.getrandbits`), which CPython names differently from `ssize_t`. + #[must_use] + fn overflow_c_uint64() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "Python int too large for C uint64_t").into() + } + + /// Creates an OverflowError when a Python int doesn't fit into a C `int` (i32). + /// + /// Matches CPython's format: `OverflowError: Python int too large to convert to C int` + /// Used by builtins (e.g. `bytes.hex`) that parse arguments via the `i` format code. + #[must_use] + fn overflow_c_int() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "Python int too large to convert to C int").into() + } + + /// Creates an OverflowError when a Python int doesn't fit into a C `long` (i64). + /// + /// Matches CPython's format: `OverflowError: Python int too large to convert to C long` + /// CPython's `i` format code converts through C long first, so ints beyond + /// i64 report this even for C-int parameters (e.g. `datetime.date(2**100, 1, 1)`). + #[must_use] + fn overflow_c_long() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "Python int too large to convert to C long").into() + } + + /// `OverflowError: Python int too large for C unsigned long`, from Argument + /// Clinic's `unsigned_long` converter on an int beyond `u64`. + #[must_use] + fn overflow_c_unsigned_long() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "Python int too large for C unsigned long").into() + } + + /// `ValueError: Cannot convert negative int`, which the unsigned Argument + /// Clinic converters raise before checking an int's width. + #[must_use] + fn value_error_negative_int() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "Cannot convert negative int").into() + } + + /// Creates the TypeError for three-argument `pow()` with a non-integer operand and no + /// float among them: `unsupported operand type(s) for ** or pow(): '{base}', '{exp}', '{modulus}'`. + #[must_use] + fn ternary_pow_type_error(base: impl Display, exp: impl Display, modulus: impl Display) -> RunError { + Self::type_error(format!( + "unsupported operand type(s) for ** or pow(): '{base}', '{exp}', '{modulus}'" + )) + } + + /// Creates a TypeError for unsupported binary operations. + /// + /// For `+` or `+=` with str/list on the left side, uses CPython's special format: + /// `can only concatenate {type} (not "{other}") to {type}` + /// + /// For other cases, uses the generic format: + /// `unsupported operand type(s) for {op}: '{left}' and '{right}'` + #[must_use] + fn binary_type_error(op: &str, lhs_type: Type, lhs_name: impl Display, rhs_name: impl Display) -> RunError { + let message = if (op == "+" || op == "+=") && matches!(lhs_type, Type::Deque) { + // CPython hardcodes the bare "deque" here even though tp_name is the + // qualified "collections.deque", so this can't share the branch below. + format!("can only concatenate deque (not \"{rhs_name}\") to deque") + } else if (op == "+" || op == "+=") && matches!(lhs_type, Type::Str | Type::List) { + format!("can only concatenate {lhs_name} (not \"{rhs_name}\") to {lhs_name}") + } else { + format!("unsupported operand type(s) for {op}: '{lhs_name}' and '{rhs_name}'") + }; + SimpleException::new_msg(ExcType::TypeError, message).into() + } + + /// Reports an invalid repetition count after both multiplication implementations decline. + #[must_use] + fn type_error_sequence_repeat(type_name: impl Display) -> RunError { + Self::type_error(format!("can't multiply sequence by non-int of type '{type_name}'")) + } + + /// Float power slots reject a modulus before coercing the other operands. + #[must_use] + fn type_error_pow_modulo() -> RunError { + Self::type_error("pow() 3rd argument not allowed unless all arguments are integers") + } + + /// Creates a TypeError for unsupported unary operations. + /// + /// Uses CPython's format: `bad operand type for unary {op}: '{type}'` + #[must_use] + fn unary_type_error(op: &str, value_type: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("bad operand type for unary {op}: '{value_type}'"), + ) + .into() + } + + /// Creates a TypeError for functions that require an integer argument. + /// + /// Matches CPython's format: `TypeError: '{type}' object cannot be interpreted as an integer` + #[must_use] + fn type_error_not_integer(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("'{type_}' object cannot be interpreted as an integer"), + ) + .into() + } + + /// The `TypeError` CPython's `_PyTime_FromSecondsObject` raises for a + /// non-numeric length (`time.sleep`): `'{type}' object cannot be + /// interpreted as an integer or float`. + #[must_use] + fn type_error_not_integer_or_float(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("'{type_}' object cannot be interpreted as an integer or float"), + ) + .into() + } + + /// Creates a ZeroDivisionError for zero raised to a negative power. + /// + /// Matches CPython's format: `ZeroDivisionError: zero to a negative power` + /// Note: CPython uses the same message for both int and float zero ** negative. + #[must_use] + fn zero_negative_power() -> RunError { + SimpleException::new_msg(ExcType::ZeroDivisionError, "zero to a negative power").into() + } + + /// The `ZeroDivisionError` for `0j ** w` with a negative or non-real `w`. + #[must_use] + fn zero_division_complex_power() -> RunError { + SimpleException::new_msg(ExcType::ZeroDivisionError, "zero to a negative or complex power").into() + } + + /// The `ValueError` for three-argument `pow()` with a complex operand. + #[must_use] + fn value_error_complex_modulo() -> RunError { + Self::value_error("complex modulo") + } + + /// Creates a generic `OverflowError` with a custom message. + #[must_use] + fn overflow_error(msg: impl fmt::Display) -> RunError { + SimpleException::new_msg(ExcType::OverflowError, msg).into() + } + + /// Creates an OverflowError for exponents that are too large. + /// + /// Matches CPython's format: `OverflowError: exponent too large` + #[must_use] + fn overflow_exponent_too_large() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "exponent too large").into() + } + + /// Creates an OverflowError when an integer cannot be represented as a float. + #[must_use] + fn overflow_int_to_float() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "int too large to convert to float").into() + } + + /// Creates the OverflowError raised when a math function overflows on a finite input. + #[must_use] + fn overflow_math_range() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "math range error").into() + } + + /// Creates the OverflowError raised when a float power overflows. + /// + /// CPython reports C's `ERANGE` through `strerror`, whose wording depends on the host libc; + /// Monty always uses glibc's so sandboxed code sees the same message on every platform. + #[must_use] + fn overflow_float_pow() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "(34, 'Numerical result out of range')").into() + } + + /// Creates the OverflowError raised when `int / int` has a quotient beyond the float range. + #[must_use] + fn overflow_int_division_to_float() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "integer division result too large for a float").into() + } + + /// Creates the OverflowError raised when converting an infinite float to an integer. + #[must_use] + fn overflow_float_infinity_to_integer() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "cannot convert float infinity to integer").into() + } + + /// Creates the ValueError raised when converting NaN to an integer. + #[must_use] + fn value_error_float_nan_to_integer() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "cannot convert float NaN to integer").into() + } + + /// Creates a ValueError for a zero modulus passed to `pow`. + #[must_use] + fn value_error_pow_modulus_zero() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "pow() 3rd argument cannot be 0").into() + } + + /// Creates a ValueError for a negative exponent passed to modular `pow`. + #[must_use] + fn value_error_pow_negative_exponent() -> RunError { + SimpleException::new_msg( + ExcType::ValueError, + "pow() 2nd argument cannot be negative when 3rd argument specified", + ) + .into() + } + + /// Creates a TypeError for str.join() when an item is not a string. + /// + /// Matches CPython's format: `TypeError: sequence item {index}: expected str instance, {type} found` + #[must_use] + fn type_error_join_item(index: usize, item_type: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("sequence item {index}: expected str instance, {item_type} found"), + ) + .into() + } + + /// Creates a TypeError for str.join() when the argument is not iterable. + /// + /// Matches CPython's format: `TypeError: can only join an iterable` + #[must_use] + fn type_error_join_not_iterable() -> RunError { + SimpleException::new_msg(ExcType::TypeError, "can only join an iterable").into() + } + + /// Creates a ValueError for str.index()/str.rindex() when substring is not found. + /// + /// Matches CPython's format: `ValueError: substring not found` + #[must_use] + fn value_error_substring_not_found() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "substring not found").into() + } + + /// Creates a ValueError for str.partition()/str.rpartition() with empty separator. + /// + /// Matches CPython's format: `ValueError: empty separator` + #[must_use] + fn value_error_empty_separator() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "empty separator").into() + } + + /// Creates a TypeError for fillchar argument that is not a single character. + /// + /// Matches CPython's format: `TypeError: The fill character must be exactly one character long` + #[must_use] + fn type_error_fillchar_must_be_single_char() -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + "The fill character must be exactly one character long", + ) + .into() + } + + /// Creates a StopIteration exception for when an iterator is exhausted. + /// + /// Matches CPython's format: `StopIteration` + #[must_use] + fn stop_iteration() -> RunError { + SimpleException::new_none(ExcType::StopIteration).into() + } + + /// Creates a ValueError for list.index() when item is not found. + /// + /// Matches CPython's format: `ValueError: list.index(x): x not in list` + #[must_use] + fn value_error_not_in_list() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "list.index(x): x not in list").into() + } + + /// Creates a ValueError for tuple.index() when item is not found. + /// + /// Matches CPython's format: `ValueError: tuple.index(x): x not in tuple` + #[must_use] + fn value_error_not_in_tuple() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "tuple.index(x): x not in tuple").into() + } + + /// Creates a ValueError for list.remove() when item is not found. + /// + /// Matches CPython's format: `ValueError: list.remove(x): x not in list` + #[must_use] + fn value_error_remove_not_in_list() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "list.remove(x): x not in list").into() + } + + /// Creates an IndexError for popping from an empty list. + /// + /// Matches CPython's format: `IndexError: pop from empty list` + #[must_use] + fn index_error_pop_empty_list() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "pop from empty list").into() + } + + /// Creates an IndexError for list.pop(index) with invalid index. + /// + /// Matches CPython's format: `IndexError: pop index out of range` + #[must_use] + fn index_error_pop_out_of_range() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "pop index out of range").into() + } + + /// Creates a KeyError for popping from an empty dict. + /// + /// Matches CPython's format: `KeyError: 'popitem(): dictionary is empty'` + #[must_use] + fn key_error_popitem_empty_dict() -> RunError { + SimpleException::new_msg(ExcType::KeyError, "'popitem(): dictionary is empty'").into() + } + + /// Creates a LookupError for unknown encoding. + /// + /// Matches CPython's format: `LookupError: unknown encoding: {encoding}` + #[must_use] + fn lookup_error_unknown_encoding(encoding: &str) -> RunError { + SimpleException::new_msg(ExcType::LookupError, format!("unknown encoding: {encoding}")).into() + } + + /// Creates a TypeError for `str(s, encoding=...)` with a str object. + /// + /// Matches CPython's message: `decoding str is not supported`. + #[must_use] + fn type_error_decoding_str_not_supported() -> RunError { + SimpleException::new_msg(ExcType::TypeError, "decoding str is not supported").into() + } + + /// Creates a TypeError for `str(x, encoding=...)` with a non-bytes object. + /// + /// Matches CPython's format: `decoding to str: need a bytes-like object, {type} found`. + #[must_use] + fn type_error_decoding_need_bytes(type_: impl Display) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("decoding to str: need a bytes-like object, {type_} found"), + ) + .into() + } + + /// Creates a TypeError for `bytes(s)` with a str source and no encoding. + /// + /// Matches CPython's message: `string argument without an encoding`. + #[must_use] + fn type_error_string_without_encoding() -> RunError { + SimpleException::new_msg(ExcType::TypeError, "string argument without an encoding").into() + } + + /// Creates a TypeError for `bytes(x, encoding=...)` with a non-str source. + /// + /// Matches CPython's message: `encoding without a string argument`. + #[must_use] + fn type_error_encoding_without_string() -> RunError { + SimpleException::new_msg(ExcType::TypeError, "encoding without a string argument").into() + } + + /// Creates a TypeError for `bytes(x, errors=...)` with a non-str source. + /// + /// Matches CPython's message: `errors without a string argument`. + #[must_use] + fn type_error_errors_without_string() -> RunError { + SimpleException::new_msg(ExcType::TypeError, "errors without a string argument").into() + } + + /// Creates a TypeError for `sum()` rejecting a str/bytes `start` value. + /// + /// Matches CPython: `sum() can't sum {kind} [use {join}.join(seq) instead]` + /// — `("strings", "''")` for str, `("bytes", "b''")` for bytes. + #[must_use] + fn type_error_sum_start(kind: &str, join: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("sum() can't sum {kind} [use {join}.join(seq) instead]"), + ) + .into() + } + + /// Creates a UnicodeEncodeError for a run of `start..end` consecutive + /// characters (character indices, not byte offsets) of `object` — the + /// full string being encoded — that can't be represented in the target + /// `codec`. `first_char` is the character at `start`, used for the + /// single-character message form. + /// + /// Matches CPython's format, which differs for a single character vs. a run: + /// `UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in + /// position 1: ordinal not in range(128)` or `... can't encode characters + /// in position 1-2: ordinal not in range(128)`. + #[must_use] + fn unicode_encode_error( + codec: &str, + object: &str, + first_char: char, + start: usize, + end: usize, + reason: &str, + ) -> RunError { + // Callers must pass a non-empty range; checked in debug builds only so + // a wrong caller can't panic the VM in release (it gets a garbled + // message position instead, which is harmless). + debug_assert!( + end > start, + "unicode_encode_error: end ({end}) must be > start ({start})" + ); + let msg = if end - start == 1 { + format!( + "'{codec}' codec can't encode character '{}' in position {start}: {reason}", + ascii_escape(&first_char.to_string()) + ) + } else { + let last = end - 1; + format!("'{codec}' codec can't encode characters in position {start}-{last}: {reason}") + }; + SimpleException::new_msg(ExcType::UnicodeEncodeError, msg) + .with_data(UnicodeErrorData::encode(codec, object, start, end, reason)) + .into() + } + + /// Creates a UnicodeDecodeError for the undecodable byte range `start..end` + /// (byte offsets into `object` — the full input being decoded). + /// + /// Matches CPython's format, which differs for a single byte vs. a run: + /// `UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 6: + /// ordinal not in range(128)` or `'utf-8' codec can't decode bytes in + /// position 0-1: unexpected end of data`. + #[must_use] + fn unicode_decode_error(codec: &str, object: &[u8], start: usize, end: usize, reason: &str) -> RunError { + // Defensive `get`: `start` always indexes a real byte for the errors + // Monty produces, but a wrong caller must not be able to panic the VM. + let first_byte = object.get(start).copied().unwrap_or(0); + SimpleException::new_msg( + ExcType::UnicodeDecodeError, + unicode_decode_error_msg(codec, first_byte, start, end, reason), + ) + .with_data(UnicodeErrorData::decode(codec, object, start, end, reason)) + .into() + } + + /// Creates a ValueError for subsequence not found in bytes/str. + /// + /// Matches CPython's format: `ValueError: subsection not found` + #[must_use] + fn value_error_subsequence_not_found() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "subsection not found").into() + } + + /// Creates a LookupError for unknown error handler. + /// + /// Matches CPython's format: `LookupError: unknown error handler name '{name}'` + #[must_use] + fn lookup_error_unknown_error_handler(name: &str) -> RunError { + SimpleException::new_msg(ExcType::LookupError, format!("unknown error handler name '{name}'")).into() + } + + /// Creates a TypeError for an encode-only error handler (`xmlcharrefreplace`, + /// `namereplace`) invoked for a decode error. + /// + /// Matches CPython's format: `TypeError: don't know how to handle + /// UnicodeDecodeError in error callback` + #[must_use] + fn type_error_decode_error_callback() -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + "don't know how to handle UnicodeDecodeError in error callback", + ) + .into() + } + + /// Creates a NotImplementedError for a decode error handler that would + /// produce lone surrogates (`surrogateescape` always; `surrogatepass` when + /// the input actually contains an encoded surrogate). + /// + /// CPython's handlers put lone surrogates (e.g. U+DC80–U+DCFF for + /// `surrogateescape`) in the resulting string. Monty strings are strict + /// UTF-8 and cannot represent lone surrogates, so these cases cannot be + /// supported — see `limitations/encoding.md`. + #[must_use] + fn not_implemented_surrogate_handler_decode(handler: &str) -> RunError { + SimpleException::new_msg( + ExcType::NotImplementedError, + format!( + "the '{handler}' error handler is not supported by Monty for decoding: \ + Monty strings cannot contain the lone surrogate characters it produces" + ), + ) + .into() + } + + /// Creates a `re.PatternError` for an invalid regex pattern or unsupported regex feature. + /// + /// Matches CPython's exception type: `re.PatternError: {message}` + #[must_use] + fn re_pattern_error(msg: impl fmt::Display) -> RunError { + SimpleException::new_msg(ExcType::RePatternError, msg).into() + } + + /// Creates a `json.JSONDecodeError` with CPython-compatible location suffix, + /// formatted as `{message}: line {line} column {column} (char {index})`. + /// + /// The fields also travel in a structured [`JsonErrorData`] payload + /// (with `doc` capped) so hosts can rebuild the real `json.JSONDecodeError` + /// with its `msg`/`doc`/`pos`/`lineno`/`colno` attributes. + /// + /// # Arguments + /// + /// * `message` - The bare error message, without the location suffix + /// * `doc` - The document being parsed (CPython's `exc.doc`) + /// * `line` - 1-based line of the error (CPython's `exc.lineno`) + /// * `column` - 1-based column of the error (CPython's `exc.colno`) + /// * `index` - Character index of the error in `doc` (CPython's `exc.pos`) + #[must_use] + fn json_decode_error(message: &str, doc: &[u8], line: usize, column: usize, index: usize) -> RunError { + SimpleException::new_msg( + ExcType::JsonDecodeError, + format!("{message}: line {line} column {column} (char {index})"), + ) + .with_data(JsonErrorData::build(message, doc, index, line, column)) + .into() + } + + /// Creates a `tomllib.TOMLDecodeError`, formatted as CPython does: + /// `{message} (at line {line}, column {column})`, or `(at end of document)` + /// when `at_end` (the caller knows from the byte offset whether `index` + /// reached the end of `doc`, so the document is not rescanned). + /// + /// `doc` is the `\r\n`-normalised source and `index` a character offset into + /// it; the five fields travel in the same [`JsonErrorData`] payload as + /// `json.JSONDecodeError`, since the two exceptions define the same attributes. + #[must_use] + fn toml_decode_error(message: &str, doc: &str, index: usize, line: usize, column: usize, at_end: bool) -> RunError { + let location = if at_end { + "end of document".to_owned() + } else { + format!("line {line}, column {column}") + }; + SimpleException::new_msg(ExcType::TomlDecodeError, format!("{message} (at {location})")) + .with_data(JsonErrorData::build(message, doc.as_bytes(), index, line, column)) + .into() + } + + /// Creates the `TypeError` used by `tomllib.loads()` for non-`str` input. + /// + /// Matches CPython's format: `Expected str object, not '{type}'` + #[must_use] + fn toml_loads_type_error(type_: &str) -> RunError { + SimpleException::new_msg(ExcType::TypeError, format!("Expected str object, not '{type_}'")).into() + } + + /// Creates the `TypeError` used by `tomllib.load()` for a text-mode file. + /// + /// Matches CPython's message: ``File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')` `` + #[must_use] + fn toml_load_text_mode_error() -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + "File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`", + ) + .into() + } + + /// Creates the `TypeError` used by `json.loads()` for unsupported input types. + /// + /// Matches CPython's format: + /// `the JSON object must be str, bytes or bytearray, not {type}` + #[must_use] + fn json_loads_type_error(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("the JSON object must be str, bytes or bytearray, not {type_}"), + ) + .into() + } + + /// Creates the `ValueError` used by `json.dumps()` for circular containers. + /// + /// Matches CPython's format: `Circular reference detected` + #[must_use] + fn json_circular_reference_error() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "Circular reference detected").into() + } + + /// Creates the `TypeError` used by `json.dumps()` for unsupported object types. + /// + /// Matches CPython's format: + /// `Object of type {type} is not JSON serializable` + #[must_use] + fn json_not_serializable_error(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("Object of type {type_} is not JSON serializable"), + ) + .into() + } + + /// Creates the `TypeError` used by `json.dumps()` for unsupported dict keys. + /// + /// Matches CPython's format: + /// `keys must be str, int, float, bool or None, not {type}` + #[must_use] + fn json_invalid_key_error(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("keys must be str, int, float, bool or None, not {type_}"), + ) + .into() + } + + /// Creates the `ValueError` used by `json.dumps(..., allow_nan=False)`. + /// + /// Matches CPython's format: + /// `Out of range float values are not JSON compliant: {value}` + #[must_use] + fn json_nan_error(value: &str) -> RunError { + SimpleException::new_msg( + ExcType::ValueError, + format!("Out of range float values are not JSON compliant: {value}"), + ) + .into() + } + + /// `AttributeError: attribute 'X' of 'Y' objects is not writable`. + /// + /// CPython distinguishes a read-only C-level attribute (`deque.maxlen`) from an + /// attribute that simply does not exist, which gets + /// [`attribute_error_no_setattr`](ExcType::attribute_error_no_setattr) instead. + #[must_use] + fn attribute_error_not_writable(attr_name: &str, type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::AttributeError, + format!("attribute '{attr_name}' of '{type_}' objects is not writable"), + ) + .into() + } + + /// Creates a TypeError for slice indices that are not integers, where `None` + /// is *not* accepted either. + /// + /// Used by `index()`-style bounds (`deque.index`), which — unlike real slicing — + /// treat an explicit `None` as a bad argument rather than "use the default". + /// Matches CPython's format: `TypeError: slice indices must be integers or have an __index__ method` + #[must_use] + fn type_error_slice_indices_no_none() -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + "slice indices must be integers or have an __index__ method", + ) + .into() + } + + /// `RuntimeError: deque mutated during iteration`. + /// + /// Monty tracks a per-deque mutation counter, mirroring CPython's internal + /// state, so any structural change during iteration invalidates the iterator + /// — including `rotate()` and a length-preserving `append()`/`popleft()` pair, + /// which a bare length check would miss. + #[must_use] + fn runtime_error_deque_mutated() -> RunError { + SimpleException::new_msg(ExcType::RuntimeError, "deque mutated during iteration").into() + } + + /// Creates an IndexError for a user `__eq__` mutating a deque during + /// `deque.remove` — CPython quirkily raises IndexError there, with the + /// same message its RuntimeError sibling uses. + #[must_use] + fn index_error_deque_mutated() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "deque mutated during iteration").into() + } + + /// `IndexError: deque index out of range` — indexing or assigning out of bounds. + #[must_use] + fn index_error_deque_out_of_range() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "deque index out of range").into() + } + + /// `IndexError: pop from an empty deque` — shared by `pop()` and `popleft()`. + #[must_use] + fn index_error_pop_from_empty_deque() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "pop from an empty deque").into() + } + + /// `IndexError: deque already at its maximum size` — `insert()` into a full deque. + #[must_use] + fn index_error_deque_full() -> RunError { + SimpleException::new_msg(ExcType::IndexError, "deque already at its maximum size").into() + } + + /// `ValueError: deque.remove(x): x not in deque`. + #[must_use] + fn value_error_deque_remove() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "deque.remove(x): x not in deque").into() + } + + /// `ValueError: deque.index(x): x not in deque`. + #[must_use] + fn value_error_deque_index() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "deque.index(x): x not in deque").into() + } + + /// `ValueError: maxlen must be non-negative`. + #[must_use] + fn value_error_maxlen_negative() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "maxlen must be non-negative").into() + } + + /// `TypeError: an integer is required` — a non-integer `maxlen`. + #[must_use] + fn type_error_integer_required() -> RunError { + SimpleException::new_msg(ExcType::TypeError, "an integer is required").into() + } + + /// `TypeError: 'X' object cannot be interpreted as an integer`. + #[must_use] + fn type_error_not_an_integer(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("'{type_}' object cannot be interpreted as an integer"), + ) + .into() + } + + /// `TypeError: sequence index must be integer, not 'X'` — deque indexing with a + /// slice or other non-integer key. + #[must_use] + fn type_error_sequence_index(type_: &str) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("sequence index must be integer, not '{type_}'"), + ) + .into() + } + + /// `TypeError: deque() takes at most 2 arguments (N given)` — CPython's own + /// wording, which no `FromArgs` style reproduces. + #[must_use] + fn type_error_deque_too_many_args(given: usize) -> RunError { + SimpleException::new_msg( + ExcType::TypeError, + format!("deque() takes at most 2 arguments ({given} given)"), + ) + .into() + } +} + +impl ExcTypeExt for ExcType { + /// Allocates an exception for constructors like `ValueError('message')`. + /// Currently supports zero or one string argument. + fn call(self, vm: &mut VM<'_>, args: ArgValues) -> RunResult { + defer_drop!(args, vm); + let exc = match args { + ArgValues::Empty => Ok(SimpleException::new_none(self)), + ArgValues::One(value) => match value.py_value(vm) { + PyValue::Str(string) => Ok(SimpleException::new_msg(self, string.as_str(vm))), + _ => Err(RunError::internal( + "exceptions can only be called with zero or one string argument", + )), + }, + _ => Err(RunError::internal( + "exceptions can only be called with zero or one string argument", + )), + }?; + let heap_id = vm.heap.allocate(HeapData::Exception(exc)); + Ok(Value::Ref(heap_id)) + } +} + +/// Simple lightweight representation of an exception. +/// +/// This is used for performance reasons for common exception patterns. +/// Exception messages use `String` for owned storage. +#[derive(Debug, Clone, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) struct SimpleException { + exc_type: ExcType, + arg: Option, + /// Structured payload (e.g. unicode-error constructor fields), carried + /// through catch/re-raise so it reaches the public `MontyException` when + /// the exception escapes the sandbox. + data: ExcData, +} + +impl fmt::Display for SimpleException { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.py_repr_fmt(f) + } +} +impl From for SimpleException { + fn from(mut exc: MontyException) -> Self { + Self { + exc_type: exc.exc_type(), + data: exc.take_data(), + arg: exc.into_message(), + } + } +} + +impl SimpleException { + /// Creates a new exception with the given type and optional argument message. + #[must_use] + pub fn new(exc_type: ExcType, arg: Option) -> Self { + Self { + exc_type, + arg, + data: ExcData::None, + } + } + + /// Creates a new exception with the given type and argument message. + #[must_use] + pub fn new_msg(exc_type: ExcType, arg: impl fmt::Display) -> Self { + Self { + exc_type, + arg: Some(arg.to_string()), + data: ExcData::None, + } + } + + /// Creates a new exception with the given type and no argument message. + #[must_use] + pub fn new_none(exc_type: ExcType) -> Self { + Self { + exc_type, + arg: None, + data: ExcData::None, + } + } + + /// Attaches a structured payload — see [`ExcData`]. + #[must_use] + pub fn with_data(mut self, data: ExcData) -> Self { + self.data = data; + self + } + + #[must_use] + pub fn exc_type(&self) -> ExcType { + self.exc_type + } + + #[must_use] + pub fn arg(&self) -> Option<&String> { + self.arg.as_ref() + } + + /// str() for an exception + #[must_use] + pub fn py_str(&self) -> String { + match (self.exc_type, &self.arg) { + // KeyError expecificaly uses repr of the key for str(exc) + (ExcType::KeyError, Some(exc)) => StringRepr(exc).to_string(), + (_, Some(arg)) => arg.to_owned(), + (_, None) => String::new(), + } + } +} + +impl<'h> HeapRead<'h, SimpleException> { + pub(crate) fn py_type(&self, vm: &VM<'h>) -> Type { + Type::Exception(self.get(vm.heap).exc_type) + } +} + +impl SimpleException { + /// Returns the exception formatted as Python would repr it. + pub fn py_repr_fmt(&self, f: &mut impl Write) -> fmt::Result { + let type_str: &'static str = self.exc_type.into(); + write!(f, "{type_str}(")?; + + if let Some(arg) = &self.arg { + string_repr_fmt(arg, f)?; + } + + f.write_char(')') + } + + /// Records a position in committed code; propagation supplies the frame name. + pub(crate) fn with_position(self, position: CodeRange) -> ExceptionRaise { + ExceptionRaise { + exc: self, + frame: Some(RawStackFrame::from_position(position)), + snippet_frame: None, + hide_caret: false, + } + } + + /// Resolves a rejected snippet's location before its provisional intern IDs are discarded. + /// Caller frames are still collected from the VM as the error propagates. + pub(crate) fn with_snippet_position(self, position: CodeRange, source: &str) -> ExceptionRaise { + let mut frame = StackFrame::from_position(position, "", &mut SourceMap::new(source)); + frame.preview_line = None; + frame.hide_caret = matches!(self.exc_type, ExcType::ImportError | ExcType::ModuleNotFoundError); + ExceptionRaise { + snippet_frame: Some(Box::new(frame)), + ..self.into() + } + } +} + +impl<'h> HeapRead<'h, SimpleException> { + /// Gets an attribute from this exception. + /// + /// Handles the `.args` attribute by allocating a tuple containing the message. + /// Returns `None` for all other attributes. + pub fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> Option { + // Fast path: interned strings can be matched by ID + let is_args = attr + .static_string(vm.interns) + .map_or_else(|| attr.as_str(vm.interns) == "args", |ss| ss == StaticStrings::Args); + + if is_args { + // Construct tuple with 0 or 1 elements based on whether arg exists + let elements = if let Some(arg_str) = &self.get(vm.heap).arg { + smallvec![allocate_string(arg_str.as_str(), vm.heap)] + } else { + smallvec![] + }; + Some(CallResult::Value(allocate_tuple(elements, vm.heap))) + } else { + None + } + } +} + +/// A raised exception with optional stack frame for traceback. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ExceptionRaise { + pub exc: SimpleException, + /// Innermost executed frame, with callers linked as parents. + pub frame: Option, + /// Resolved innermost location of a rejected snippet, independent of its discarded intern IDs. + pub snippet_frame: Option>, + /// Whether to hide the caret marker when creating the stack frame. + /// + /// CPython doesn't show carets for attribute GET errors, but does show them + /// for attribute SET errors. This flag allows error creators to specify + /// whether the caret should be hidden. + pub hide_caret: bool, +} + +impl From for ExceptionRaise { + fn from(exc: SimpleException) -> Self { + Self { + exc, + frame: None, + snippet_frame: None, + hide_caret: false, + } + } +} + +impl From for ExceptionRaise { + fn from(exc: MontyException) -> Self { + Self { + exc: exc.into(), + frame: None, + snippet_frame: None, + hide_caret: false, + } + } +} + +impl ExceptionRaise { + /// Adds a caller's frame as the outermost frame in the traceback chain. + /// + /// This is used when an exception propagates up through call frames. + /// The new frame becomes the ultimate parent (displayed first in traceback, + /// since tracebacks show "most recent call last"). + /// + /// Special case: If the innermost frame has no name yet (created with `with_position`), + /// this sets its name instead of creating a new parent. This happens when the error + /// is raised from a namespace lookup - the initial frame has the position but not + /// the function name, which gets filled in as the error propagates. + pub(crate) fn add_caller_frame(&mut self, position: CodeRange, name: StringId) { + self.add_caller_frame_inner(position, name, false); + } + + fn add_caller_frame_inner(&mut self, position: CodeRange, name: StringId, hide_caret: bool) { + if let Some(ref mut frame) = self.frame { + // If innermost frame has no name, set it instead of adding a parent + // This handles errors from namespace lookups which create nameless frames + if frame.frame_name.is_none() { + frame.frame_name = Some(name); + frame.hide_caret = hide_caret; + return; + } + // Find the outermost frame (the one with no parent) and add the new frame as its parent + let mut current = frame; + while current.parent.is_some() { + current = current.parent.as_mut().unwrap(); + } + let mut new_frame = RawStackFrame::new(position, name, None); + new_frame.hide_caret = hide_caret; + current.parent = Some(Box::new(new_frame)); + } else { + // No frame yet - create one + let mut new_frame = RawStackFrame::new(position, name, None); + new_frame.hide_caret = hide_caret; + self.frame = Some(new_frame); + } + } + + /// Converts this exception to a `MontyException` for the public API. + /// + /// Uses `Interns` to resolve `StringId` references to actual strings. + /// Extracts preview lines from the source code for traceback display. + /// Converts this exception into a public `MontyException`, expanding each + /// stack frame's raw byte offsets into lines/columns/preview text via a + /// caller-provided source lookup. + /// + /// The caller must supply `source_for` so that frames whose `CodeRange` + /// points into a *different* source than the one currently executing can + /// still be resolved. In particular, REPL tracebacks can interleave + /// frames from multiple snippets (e.g. calling into a function defined + /// in an earlier feed); resolving those byte offsets against only the + /// current snippet's source would produce wrong line/column/caret + /// information. `source_for` is called per unique filename encountered + /// in the traceback and its result is cached, so each source is scanned + /// at most once regardless of how many frames share it. + #[must_use] + pub fn into_python_exception<'s>( + self, + interns: &'s Interns, + source_for: impl Fn(&str) -> Option<&'s str>, + ) -> MontyException { + // Per-filename SourceMap cache. Typical tracebacks touch 1-3 unique + // filenames so a tiny `Vec` beats a HashMap on both allocations and + // lookup cost. + let mut cache: Vec<(StringId, SourceMap<'s>)> = Vec::new(); + let mut traceback = self + .frame + .map(|frame| { + let mut frames = Vec::new(); + let mut current = Some(&frame); + while let Some(f) = current { + let fname_id = f.position.filename; + // An `eval()` / `exec()` snippet resolves against its own + // recorded source, never the host's, and prints no source + // line: CPython has nothing to read back for ``. + let eval_source = interns.eval_source(fname_id); + let sm_idx = if let Some(i) = cache.iter().position(|(k, _)| *k == fname_id) { + i + } else { + let src = + eval_source.unwrap_or_else(|| source_for(interns.get_filename(fname_id)).unwrap_or("")); + cache.push((fname_id, SourceMap::new(src))); + cache.len() - 1 + }; + let mut stack_frame = StackFrame::from_raw(f, interns, &mut cache[sm_idx].1); + if eval_source.is_some() { + stack_frame.preview_line = None; + } + frames.push(stack_frame); + current = f.parent.as_deref(); + } + // Reverse so outermost frame is first (Python's "most recent call last" ordering) + frames.reverse(); + frames + }) + .unwrap_or_default(); + if let Some(frame) = self.snippet_frame { + traceback.push(*frame); + } + + MontyException::with_traceback(self.exc.exc_type, self.exc.arg, traceback).with_data(self.exc.data) + } +} + +/// A stack frame for traceback information. +/// +/// Stores position information and optional function name as StringId. +/// The actual name string must be looked up externally when formatting the traceback. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct RawStackFrame { + pub position: CodeRange, + /// The name of the frame (function name StringId, or None for module-level code). + pub frame_name: Option, + pub parent: Option>, + /// Whether to hide the caret marker in the traceback for this frame. + /// + /// Set to `true` for: + /// - `raise` statements (CPython doesn't show carets for raise) + /// - `AttributeError` on attribute access (CPython doesn't show carets for these) + pub hide_caret: bool, +} + +impl RawStackFrame { + pub(crate) fn new(position: CodeRange, frame_name: StringId, parent: Option<&Self>) -> Self { + Self { + position, + frame_name: Some(frame_name), + parent: parent.map(|p| Box::new(p.clone())), + hide_caret: false, + } + } + + fn from_position(position: CodeRange) -> Self { + Self { + position, + frame_name: None, + parent: None, + hide_caret: false, + } + } + + /// Creates a new frame for a raise statement (no caret will be shown). + pub(crate) fn from_raise(position: CodeRange, frame_name: StringId) -> Self { + Self { + position, + frame_name: Some(frame_name), + parent: None, + hide_caret: true, + } + } +} + +/// Runtime error types that can occur during execution. +/// +/// Three variants: +/// - `Internal`: Bug in interpreter implementation (static message) +/// - `Exc`: Python exception that can be caught by try/except (when implemented) +/// - `UncatchableExc`: Python exception from a resource limit or host abort +/// +/// `Clone` is implemented so an error can be cached for later re-raising +/// (e.g. a failed `GatherFuture` replaying the same exception on every +/// re-await). Inner data is shallow-clonable: `Cow<'static, str>` is cheap, +/// and `ExceptionRaise` already derives `Clone`. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) enum RunError { + /// Internal interpreter error - indicates a bug in Monty, not user code. + Internal(Cow<'static, str>), + /// Catchable Python exception (e.g., ValueError, TypeError). + Exc(ExceptionRaise), + /// Uncatchable Python exception from a resource limit or host abort. + /// + /// Displays a normal traceback but bypasses `try`/`except` blocks. + UncatchableExc(ExceptionRaise), +} + +impl From for RunError { + fn from(exc: ExceptionRaise) -> Self { + Self::Exc(exc) + } +} + +impl From for RunError { + fn from(exc: SimpleException) -> Self { + Self::Exc(exc.into()) + } +} + +impl From for RunError { + fn from(exc: MontyException) -> Self { + Self::Exc(exc.into()) + } +} + +impl From for RunError { + fn from(err: FormatError) -> Self { + let exc_type = match &err { + FormatError::Overflow(_) => ExcType::OverflowError, + FormatError::InvalidAlignment(_) | FormatError::ValueError(_) => ExcType::ValueError, + }; + Self::Exc(SimpleException::new_msg(exc_type, err).into()) + } +} + +impl From for RunError { + /// Converts a `fmt::Error` into a `RunError`. + /// + /// In practice, writing to a `String` buffer never fails, so `fmt::Error` only + /// arises from our explicit error returns (e.g. INT_MAX_STR_DIGITS checks in + /// `py_repr_fmt`). This impl exists so `write!()?` in `py_repr_fmt` auto-converts + /// when the method returns `RunResult<()>`. + fn from(err: fmt::Error) -> Self { + Self::internal(format!("unexpected formatting error: {err}")) + } +} + +impl RunError { + /// Whether this is a catchable `exc_type`, matching only `Exc` so an uncatchable + /// host or resource error is never swallowed by a guard that expects one. + pub(crate) fn is_catchable(&self, exc_type: ExcType) -> bool { + matches!(self, Self::Exc(raise) if raise.exc.exc_type() == exc_type) + } + + /// Whether this is a catchable `StopIteration` from `__next__`. + /// + /// Matching only `Exc` prevents uncatchable errors being mistaken for exhaustion. + pub(crate) fn is_stop_iteration(&self) -> bool { + matches!(self, Self::Exc(raise) if matches!(raise.exc.exc_type(), ExcType::StopIteration)) + } + + /// Wraps a host exception so it builds a traceback but bypasses `except`. + pub(crate) fn uncatchable(exc: MontyException) -> Self { + Self::UncatchableExc(exc.into()) + } + + /// Converts this runtime error to a `MontyException` for the public API. + /// + /// Internal errors are converted to `RuntimeError` exceptions with no traceback. + /// Converts this runtime error into a public `MontyException`. + /// + /// `source_for` is consulted per unique filename referenced by the + /// traceback — see [`ExceptionRaise::into_python_exception`] for why + /// this is a lookup rather than a single source string. + #[must_use] + pub fn into_python_exception<'s>( + self, + interns: &'s Interns, + source_for: impl Fn(&str) -> Option<&'s str>, + ) -> MontyException { + match self { + Self::Exc(exc) | Self::UncatchableExc(exc) => exc.into_python_exception(interns, source_for), + Self::Internal(err) => MontyException::runtime_error(format!("Internal error in monty: {err}")), + } + } + + pub fn internal(msg: impl Into>) -> Self { + Self::Internal(msg.into()) + } +} + +/// CPython's `ModuleNotFoundError` message for `module_name`. +fn no_module_named(module_name: &str) -> String { + format!("No module named '{module_name}'") +} + +/// Formats a list of parameter names for error messages, matching CPython's +/// `format_missing` joining (note the Oxford comma for three or more names). +/// +/// Examples: +/// - `["a"]` -> `'a'` +/// - `["a", "b"]` -> `'a' and 'b'` +/// - `["a", "b", "c"]` -> `'a', 'b', and 'c'` +fn format_param_names(names: &[&str]) -> String { + match names.len() { + 0 => String::new(), + 1 => format!("'{}'", names[0]), + 2 => format!("'{}' and '{}'", names[0], names[1]), + _ => { + let last = names.last().unwrap(); + let rest: Vec<_> = names[..names.len() - 1].iter().map(|n| format!("'{n}'")).collect(); + format!("{}, and '{last}'", rest.join(", ")) + } + } +} diff --git a/crates/bashkit-monty/src/expressions.rs b/crates/bashkit-monty/src/expressions.rs new file mode 100644 index 000000000..275ae1d94 --- /dev/null +++ b/crates/bashkit-monty/src/expressions.rs @@ -0,0 +1,1110 @@ +#[cfg(test)] +use strum::IntoEnumIterator; + +use crate::{ + args::{ArgExprs, Signature}, + builtins::Builtins, + fstring::FStringPart, + intern::{BytesId, LongIntId, StringId}, + namespace::NamespaceId, + parse::{CodeRange, ParsedSignature, Try}, + value::{EitherStr, Marker}, +}; + +/// Indicates which namespace a variable reference belongs to. +/// +/// This is determined at prepare time based on Python's scoping rules: +/// - Variables assigned in a function are Local (unless declared `global`) +/// - Variables only read (not assigned) that exist at module level are Global +/// - The `global` keyword explicitly marks a variable as Global +/// - Variables declared `nonlocal` or implicitly captured from enclosing scopes +/// are accessed through Cells +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +pub enum NameScope { + /// Variable is in the current frame's local namespace (assigned somewhere in this function). + /// + /// If accessed before assignment, raises `UnboundLocalError`. + #[default] + #[serde(rename = "L")] + Local, + /// Variable is in the module-level global namespace. + #[serde(rename = "G")] + Global, + /// Variable accessed through a cell (heap-allocated container). + /// + /// Used for both: + /// - Variables captured from enclosing scopes (free variables) + /// - Variables in this function that are captured by nested functions (cell variables) + /// + /// The namespace slot contains `Value::Ref(cell_id)` pointing to a `HeapData::Cell`. + /// Access requires dereferencing through the cell. + #[serde(rename = "C")] + Cell, + /// Comprehension target stored in isolated operand-stack storage. + /// + /// The namespace ID is a comprehension-local slot ID. The compiler stores + /// uncaptured targets directly and gives captured targets a stable cell. + #[serde(rename = "V")] + CompVar, + /// Top-level name of an `eval()` / `exec()` snippet that runs with a locals + /// dict or dict globals: resolved by name at runtime through the frame's + /// namespace. The namespace ID is the session global slot for the name (a + /// scratch slot under dict globals) so the slot-globals tail of the lookup + /// reuses the `LoadGlobal` machinery. + #[serde(rename = "N")] + Name, +} + +/// Identifies where an enclosing scope stores a cell captured by a callable. +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +pub enum CaptureSource { + /// Cell reference stored in an ordinary enclosing-frame namespace slot. + Namespace(NamespaceId), + /// Cell reference stored in an active comprehension's stable stack slot. + CompVar(u16), +} + +/// An identifier (variable or function name) with source location and scope information. +/// +/// The name is stored as a `StringId` which indexes into the string interner. +/// To get the actual string, look it up in the `Interns` storage. +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +pub struct Identifier { + #[serde(rename = "P")] + pub position: CodeRange, + /// Interned name ID - look up in Interns to get the actual string. + #[serde(rename = "N")] + pub name_id: StringId, + #[serde(rename = "I")] + opt_namespace_id: Option, + /// Which namespace this identifier refers to (determined at prepare time) + #[serde(rename = "S")] + pub scope: NameScope, +} + +impl Identifier { + /// Creates a new identifier with unknown scope (to be resolved during prepare phase). + pub fn new(name_id: StringId, position: CodeRange) -> Self { + Self { + name_id, + position, + opt_namespace_id: None, + scope: NameScope::Local, + } + } + + /// Creates a new identifier with resolved namespace index and explicit scope. + pub fn new_with_scope(name_id: StringId, position: CodeRange, namespace_id: NamespaceId, scope: NameScope) -> Self { + Self { + name_id, + position, + opt_namespace_id: Some(namespace_id), + scope, + } + } + + pub fn namespace_id(&self) -> NamespaceId { + self.opt_namespace_id + .expect("Identifier not prepared with namespace_id") + } +} + +/// A dotted-import component and its full path for `ModuleNotFoundError` messages. +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +pub struct Submodule { + /// The attribute name (`b`). + pub name: StringId, + /// The path through this component (`a.b`). + pub path: StringId, +} + +/// One entry of an `import` statement, with its dotted components and binding target. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ImportName { + /// The top-level module to load (`a` for `import a.b`). + pub module_name: StringId, + /// The further components of a dotted name, in order. + pub submodules: Vec, + /// Whether the statement binds the top-level module (`import a.b` binds + /// `a`) rather than the last component (`import a.b as x` binds `a.b`). + pub binds_top_level: bool, + /// The binding target — the alias if provided, otherwise the module name + /// (or its top-level package when dotted). + /// After the prepare phase, this includes the resolved namespace slot. + pub binding: Identifier, +} + +/// Target of a function call expression. +/// +/// Represents a callable that can be either: +/// - A builtin function or exception resolved at parse time (`print`, `len`, `ValueError`, etc.) +/// - A name that will be looked up in the namespace at runtime (for callable variables) +/// +/// Separate from Value to allow deriving Clone without Value's Clone restrictions. +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +pub enum Callable { + /// A builtin function like `print`, `len`, `str`, etc. + Builtin(Builtins), + /// A name to be looked up in the namespace at runtime (e.g., `x` in `x = len; x('abc')`). + Name(Identifier), +} + +/// An item in a list, tuple, or set literal. +/// +/// PEP 448 allows any number of `*expr` unpack items to appear alongside +/// regular values in list/tuple/set literals (e.g., `[1, *a, 2]`). +/// This enum represents either a plain value or an iterable to be unpacked. +/// +/// Used in `Expr::List`, `Expr::Tuple`, and `Expr::Set` to represent each +/// element of the literal. When the fast path is taken (no unpack items), +/// only `Value` variants are present and the compiler emits a single +/// `BuildList`/`BuildTuple`/`BuildSet` instruction. When any `Unpack` item +/// is present, the compiler emits `Build*(0)` followed by per-item +/// `ListAppend`/`SetAdd` and `ListExtend`/`SetExtend` instructions. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) enum SequenceItem { + /// A plain expression value in the literal. + Value(ExprLoc), + /// An `*expr` unpack — the iterable is expanded in-place. + Unpack(ExprLoc), +} + +/// An item in a dict literal. +/// +/// PEP 448 allows `**expr` unpack items to appear alongside normal key:value +/// pairs in dict literals (e.g., `{'a': 1, **d, 'b': 2}`). Duplicate keys +/// from later items silently overwrite earlier ones (unlike `**kwargs` in +/// function calls, where duplicates raise `TypeError`). +/// +/// Used in `Expr::Dict`. When no `Unpack` items are present the compiler +/// emits a single `BuildDict` instruction. Otherwise it emits `BuildDict(0)` +/// followed by per-item `DictSetItem` and `DictUpdate` instructions. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) enum DictItem { + /// A plain `key: value` pair. + Pair(ExprLoc, ExprLoc), + /// A `**expr` unpack — the mapping is merged in-place, later keys win. + Unpack(ExprLoc), +} + +/// An expression in the AST. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum Expr { + Literal(Literal), + Builtin(Builtins), + Name(Identifier), + /// Function call expression. + /// + /// The `callable` can be a Builtin, ExcType (resolved at parse time), or a Name + /// that will be looked up in the namespace at runtime. + Call { + callable: Callable, + /// ArgExprs is relatively large and would require Box anyway since it uses ExprLoc, so keep Expr small + /// by using a box here + args: Box, + }, + /// Method call on an object (e.g., `obj.method(args)`). + /// + /// The object expression is evaluated first, then the method is looked up + /// and called with the given arguments. Supports chained attribute access + /// like `a.b.c.method()`. + AttrCall { + object: Box, + attr: EitherStr, + /// same as above for Box + args: Box, + }, + /// Expression call (e.g., `(lambda x: x + 1)(5)` or `get_func()(args)`). + /// + /// Calls an arbitrary expression as a callable. The callable expression + /// is evaluated first, then called with the given arguments. + IndirectCall { + /// The expression that evaluates to a callable. + callable: Box, + args: Box, + }, + /// Attribute access expression (e.g., `point.x` or `a.b.c`). + /// + /// Retrieves the value of an attribute from an object. For dataclasses, + /// this returns the field value. For other types, this may trigger + /// special attribute handling. Supports chained attribute access. + AttrGet { + object: Box, + attr: EitherStr, + }, + Op { + left: Box, + op: Operator, + right: Box, + }, + CmpOp { + left: Box, + op: CmpOperator, + right: Box, + }, + /// Chain comparison expression: `a < b < c < d` + /// + /// Unlike single comparisons, chain comparisons evaluate intermediate values + /// only once and short-circuit on the first false result. Compiled to bytecode + /// that uses stack manipulation (Dup, Rot) rather than temporary variables, + /// avoiding namespace pollution. + ChainCmp { + /// The leftmost operand in the chain. + left: Box, + /// Sequence of (operator, operand) pairs: `[(op1, b), (op2, c), ...]` + comparisons: Vec<(CmpOperator, ExprLoc)>, + }, + /// List literal: `[a, *b, c]` + /// + /// Each element is a `SequenceItem` which may be a plain value or an `*unpack`. + /// When no unpack items are present (common case), the compiler emits a single + /// `BuildList(N)`. When any unpack is present it emits `BuildList(0)` followed + /// by per-item `ListAppend`/`ListExtend` instructions. + List(Vec), + /// Tuple literal: `(a, *b, c)` or `a, *b, c` + /// + /// Same compilation strategy as `List` but ends with `ListToTuple`. + Tuple(Vec), + Subscript { + object: Box, + index: Box, + }, + /// Slice literal expression from `x[start:stop:step]` syntax. + /// + /// Each component is optional (None means use the default for that position). + /// This expression creates a `slice` object when evaluated. + Slice { + lower: Option>, + upper: Option>, + step: Option>, + }, + /// Dict literal: `{'a': 1, **d, 'b': 2}` + /// + /// Each element is a `DictItem` which may be a plain `key: value` pair or a `**unpack`. + /// When no unpack items are present the compiler emits `BuildDict(N)`. Otherwise it + /// emits `BuildDict(0)` followed by per-item `DictSetItem`/`DictUpdate` instructions. + /// Duplicate keys from later items silently overwrite earlier ones. + Dict(Vec), + /// Set literal expression: `{1, *a, 2}`. + /// + /// Note: `{}` is always a dict, not an empty set. Use `set()` for empty sets. + /// Compilation strategy mirrors `List` but uses `SetAdd`/`SetExtend`. + Set(Vec), + /// Unary `not` expression - evaluates to the boolean negation of the operand's truthiness. + Not(Box), + /// Unary minus expression - negates a numeric value. + UnaryMinus(Box), + /// Unary plus expression - returns value as-is for numbers, converts bools to int. + UnaryPlus(Box), + /// Unary bitwise NOT expression - inverts all bits of an integer. + UnaryInvert(Box), + /// Await expression - suspends execution until the awaited value resolves. + /// + /// Can await `ExternalFuture`, `Coroutine`, or `GatherFuture` values. + /// Raises `TypeError` for non-awaitable values. + /// Unlike standard Python, `await` is allowed at module level (like Jupyter notebooks). + Await(Box), + /// F-string expression containing literal and interpolated parts. + /// + /// At evaluation time, each part is processed in sequence: + /// - Literal parts are used directly + /// - Interpolation parts have their expression evaluated, converted, and formatted + /// + /// The results are concatenated to produce the final string. + FString(Vec), + /// Conditional expression (ternary operator): `body if test else orelse` + /// + /// Only one of body/orelse is evaluated based on the truthiness of test. + /// This implements short-circuit evaluation - the branch not taken is never executed. + IfElse { + test: Box, + body: Box, + orelse: Box, + }, + /// List comprehension: `[elt for target in iter if cond...]` + /// + /// Builds a new list by iterating and optionally filtering. Loop variables + /// are scoped to the comprehension and do not leak to the enclosing scope. + ListComp { + elt: Box, + generators: Vec, + /// Lexical target slots captured by callables in this comprehension. + captured_slots: Vec, + }, + /// Set comprehension: `{elt for target in iter if cond...}` + /// + /// Builds a new set by iterating and optionally filtering. Duplicate values + /// are deduplicated. Loop variables are scoped to the comprehension. + SetComp { + elt: Box, + generators: Vec, + /// Lexical target slots captured by callables in this comprehension. + captured_slots: Vec, + }, + /// Dict comprehension: `{key: value for target in iter if cond...}` + /// + /// Builds a new dict by iterating and optionally filtering. Later values + /// overwrite earlier ones for duplicate keys. Loop variables are scoped + /// to the comprehension. + DictComp { + key: Box, + value: Box, + generators: Vec, + /// Lexical target slots captured by callables in this comprehension. + captured_slots: Vec, + }, + /// Raw lambda expression from the parser, before preparation. + /// + /// This variant is produced during parsing and contains unprepared data. + /// During the prepare phase, it gets converted to `Expr::Lambda` with a + /// fully prepared `PreparedFunctionDef`. + LambdaRaw { + /// The interned `` name ID. + name_id: StringId, + /// The parsed lambda signature (parameters and defaults). + signature: ParsedSignature, + /// The lambda body expression (not yet prepared). + body: Box, + }, + /// Lambda expression: `lambda args: body` (prepared form). + /// + /// A lambda is an anonymous function that returns a single expression. + /// It's compiled identically to a regular function, but with the name `` + /// and an implicit return of the body expression. The resulting function value + /// stays on the stack as an expression result (not stored to a name). + Lambda { + /// The prepared function definition containing signature, body, and closure info. + /// The body is wrapped as `[Node::Return(body_expr)]` during preparation. + func_def: Box, + }, + /// Named expression (walrus operator): `(target := value)` + /// + /// Evaluates `value`, assigns it to `target`, and returns the value as the + /// expression result. The target is treated as an assignment for scope analysis, + /// so it creates a local binding in the enclosing scope. + /// + /// Per PEP 572, in comprehensions the target binds in the enclosing scope, + /// not the comprehension's implicit scope. + Named { + target: Identifier, + value: Box, + }, +} + +/// Target for tuple unpacking - a name, attribute, subscript, nested tuple or +/// starred target. +/// +/// Supports recursive structures like `(a, b), c` or `a, (b, c)`. +/// Also supports starred targets like `first, *rest = [1, 2, 3, 4]`. +/// Used in assignment statements, for loop targets, and comprehension targets. +/// +/// `Attr` and `Subscript` mirror the same-named [`AssignTarget`] variants and +/// compile to the same stores, so `self.x, self.y = pair` behaves as the two +/// single-target assignments would. Comprehension targets are the exception: +/// their leaves live on the operand stack as comp-var slots, so only names +/// reach that path (`prepare` rejects the rest). +/// +/// Their expressions are boxed: `Node::For` and `Node::With` embed a target +/// inline, so an inline `ExprLoc` here would grow every `Node`. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum UnpackTarget { + /// Single identifier: `a` + Name(Identifier), + /// Nested tuple: `(a, b)` - can contain further nested tuples + Tuple { + /// The targets to unpack into (can be names or nested tuples) + targets: Vec, + /// Source position covering all targets (for error caret placement) + position: CodeRange, + }, + /// Starred target: `*rest` - captures remaining values into a list. + /// + /// Only one starred target is allowed per unpacking level. + Starred(Box), + /// Attribute target: `obj.attr`. + Attr { + /// Expression evaluating to the object whose attribute is being set. + object: Box, + /// The attribute name. + attr: EitherStr, + /// Position of the full attribute expression (for traceback carets). + position: CodeRange, + }, + /// Subscript target: `container[index]`. + Subscript { + /// Expression evaluating to the container object. + container: Box, + /// Expression evaluating to the index/key. + index: Box, + /// Position of the full subscript expression (for traceback carets). + position: CodeRange, + }, +} + +/// One `case` clause of a [`Node::Match`]: its pattern, optional guard and body. +/// +/// Generic over the node type so it rides the same Raw -> Prepared pipeline as +/// [`Try`]. The pattern's capture names are resolved to slots during prepare, +/// like any other assignment target. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct MatchCase { + pub pattern: Pattern, + /// `case PATTERN if GUARD:` - evaluated only after the pattern matches and + /// its names are bound, so a failing guard still leaves the captures bound. + pub guard: Option, + pub body: Vec, + /// Source range of the pattern (the `case` header's caret range). + pub position: CodeRange, +} + +/// A structural pattern inside a `case` clause (PEP 634). +/// +/// The shapes mirror `ast.pattern`; the compiler lowers them following +/// CPython's `codegen_pattern_*` so capture bindings happen only once the whole +/// pattern has matched. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum Pattern { + /// `case 1:` / `case 'x':` / `case Color.RED:` - matches when `subject == value`. + Value(ExprLoc), + /// `case None:` / `case True:` / `case False:` - matches by identity. + Singleton(ExprLoc), + /// `case [a, *rest, b]:` - matches a sequence (not `str`/`bytes`) of the right length. + Sequence { + /// Sub-patterns in order; at most one may be [`Pattern::Star`]. + patterns: Vec, + position: CodeRange, + }, + /// `case {'k': v, **rest}:` - matches a mapping containing every key. + Mapping { + /// Key expressions (literals or dotted names), paired with `patterns`. + keys: Vec, + /// One sub-pattern per key, matched against the looked-up values. + patterns: Vec, + /// `**rest`: bound to a new `dict` of the entries the keys did not consume. + rest: Option, + position: CodeRange, + }, + /// `case Point(0, y=1):` - `isinstance` check plus attribute sub-patterns. + Class { + /// Expression evaluating to the class (a name or dotted name). + cls: ExprLoc, + /// Positional sub-patterns, resolved through the class's `__match_args__`. + patterns: Vec, + /// Keyword attribute names, paired with `kwd_patterns`. + kwd_attrs: Vec, + kwd_patterns: Vec, + position: CodeRange, + }, + /// `*name` / `*_` inside a sequence pattern; captures the surplus items as a `list`. + Star { + name: Option, + position: CodeRange, + }, + /// `case x:` (capture), `case _:` (wildcard) or `case PATTERN as x:`. + /// + /// `pattern: None` is the bare capture/wildcard form; `name: None` with no + /// pattern is the `_` wildcard. + As { + pattern: Option>, + name: Option, + position: CodeRange, + }, + /// `case 1 | 2 | x:` - alternatives tried left to right; all must bind the same names. + Or { patterns: Vec, position: CodeRange }, +} + +impl Pattern { + /// The source range of the pattern, for diagnostics and traceback carets. + #[must_use] + pub fn position(&self) -> CodeRange { + match self { + Self::Value(expr) | Self::Singleton(expr) => expr.position, + Self::Sequence { position, .. } + | Self::Mapping { position, .. } + | Self::Class { position, .. } + | Self::Star { position, .. } + | Self::As { position, .. } + | Self::Or { position, .. } => *position, + } + } + + /// Whether this is the bare `_` wildcard, which matches anything and binds nothing. + #[must_use] + pub fn is_wildcard(&self) -> bool { + matches!( + self, + Self::As { + pattern: None, + name: None, + .. + } + ) + } + + /// Whether this is `*_`: a starred wildcard inside a sequence pattern. + #[must_use] + pub fn is_star_wildcard(&self) -> bool { + matches!(self, Self::Star { name: None, .. }) + } +} + +/// Target of a single assignment step within a chained assignment. +/// +/// Chained assignments (`a = b[i] = obj.x = expr`) evaluate `expr` once and +/// then assign the resulting value to each target in left-to-right order. +/// `AssignTarget` captures just the target portion of each of the usual +/// single-target assignment node variants (`Assign`, `SubscriptAssign`, +/// `AttrAssign`, `UnpackAssign`) so they can share a common list in +/// `Node::ChainAssign` without embedding a dummy source expression. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum AssignTarget { + /// Simple name target: `a`. + Name(Identifier), + /// Subscript target: `container[index]`. + Subscript { + /// Expression evaluating to the container object. + target: ExprLoc, + /// Expression evaluating to the index/key. + index: ExprLoc, + /// Position of the full subscript expression (for traceback carets). + target_position: CodeRange, + }, + /// Attribute target: `obj.attr`. + Attr { + /// Expression evaluating to the object whose attribute is being set. + object: ExprLoc, + /// The attribute name. + attr: EitherStr, + /// Position of the full attribute expression (for traceback carets). + target_position: CodeRange, + }, + /// Tuple/list unpacking target: `a, b` or `[a, *rest]`. + Unpack { + /// The individual unpack targets (can be names, starred, or nested tuples). + targets: Vec, + /// Source position covering all targets (for error caret placement). + targets_position: CodeRange, + }, +} + +/// A generator clause in a comprehension: `for target in iter [if cond1] [if cond2]...` +/// +/// Represents one `for` clause with zero or more `if` filters. Multiple generators +/// create nested iteration (the rightmost varies fastest). +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Comprehension { + /// Loop variable - either single identifier or tuple unpacking pattern. + pub target: UnpackTarget, + /// Iterable expression to loop over. + pub iter: ExprLoc, + /// Zero or more filter conditions (all must be truthy for the element to be included). + pub ifs: Vec, +} + +impl Expr { + pub fn is_none(&self) -> bool { + matches!(self, Self::Literal(Literal::None)) + } +} + +/// Represents values that can be produced purely from the parser/prepare pipeline. +/// +/// Const values are intentionally detached from the runtime heap so we can keep +/// parse-time transformations (constant folding, namespace seeding, etc.) free from +/// reference-count semantics. Only once execution begins are these literals turned +/// into real `Value`s that participate in the interpreter's runtime rules. +/// +/// Note: unlike the AST `Constant` type, we store tuples only as expressions since they +/// can't always be recorded as constants. +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +pub enum Literal { + Ellipsis, + None, + Bool(bool), + Int(i64), + Float(f64), + /// An imaginary literal such as `2j`, holding its imaginary part (the real + /// part is always zero). It has no constant-pool form: the compiler emits a + /// `complex()` constructor call, since a complex value lives on the heap. + Complex(f64), + /// An interned string literal. The StringId references the string in the Interns table. + Str(StringId), + /// An interned bytes literal. The BytesId references the bytes in the Interns table. + Bytes(BytesId), + /// An interned long integer literal. The `LongIntId` references the value in the Interns table. + /// Used for integer literals that exceed the i64 range. + LongInt(LongIntId), + /// A marker value (e.g., typing constructs like Any, Optional, etc.). + Marker(Marker), +} + +/// An expression with its source location. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ExprLoc { + pub position: CodeRange, + pub expr: Expr, +} + +impl ExprLoc { + pub fn new(position: CodeRange, expr: Expr) -> Self { + Self { position, expr } + } +} + +/// An AST node parameterized by the function definition type. +/// +/// This generic enum represents statements in both parsed and prepared forms: +/// - `Node` (aka `ParseNode`): Output of the parser, contains unprepared function bodies +/// - `Node` (aka `PreparedNode`): Output of prepare phase, has resolved names +/// +/// Some variants (`Pass`, `Global`, `Nonlocal`) only appear in parsed form and are filtered +/// out during the prepare phase. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum Node { + /// No-op statement. Only present in parsed form, filtered out during prepare. + Pass, + Expr(ExprLoc), + Return(Option), + Raise(Option), + Assert { + test: ExprLoc, + msg: Option, + }, + Assign { + target: Identifier, + object: ExprLoc, + }, + /// Tuple unpacking assignment (e.g., `a, b = some_tuple` or `(a, b), c = nested`). + /// + /// The right-hand side is evaluated, then unpacked into the targets in order. + /// Supports nested unpacking like `(a, b), c = ((1, 2), 'x')`. + UnpackAssign { + /// The targets to unpack into (can be names or nested tuples) + targets: Vec, + /// Source position covering all targets (for error message caret placement) + targets_position: CodeRange, + object: ExprLoc, + }, + OpAssign { + target: Identifier, + op: Operator, + /// The right-hand side value of the augmented assignment (e.g., `1` in `x += 1`). + value: ExprLoc, + }, + /// Augmented subscript assignment (e.g., `totals[key] += value` or `a[0][1] += 1`). + /// + /// This evaluates the container expression and index exactly once, then performs the + /// inplace operation on the current item before storing the result back. + /// Limiting duplicate evaluation is important because index expressions may + /// have side effects and CPython only evaluates them once. + /// The `target` is an arbitrary expression evaluating to the container — it can be + /// a simple name, a nested subscript (`a[0]`), or an attribute access (`obj.field`). + SubscriptOpAssign { + target: ExprLoc, + index: ExprLoc, + op: Operator, + /// The right-hand side value of the augmented assignment (e.g., `1` in `a[0] += 1`). + value: ExprLoc, + /// Position of the subscript expression (e.g., `totals[key]`) for traceback carets. + target_position: CodeRange, + }, + /// Subscript assignment (e.g., `lst[0] = value` or `a[0][1] = value`). + /// + /// The `target` is an arbitrary expression evaluating to the container — it can be + /// a simple name, a nested subscript (`a[0]`), or an attribute access (`obj.field`). + SubscriptAssign { + target: ExprLoc, + index: ExprLoc, + value: ExprLoc, + /// Position of the subscript expression (e.g., `lst[10]`) for traceback carets. + target_position: CodeRange, + }, + /// Augmented attribute assignment (e.g., `point.x += 1` or `a.b.c -= 5`). + /// + /// Evaluates the object expression once, loads the attribute, performs the + /// inplace operation with the right-hand side, then stores the result back. + /// The `object` is an arbitrary expression — it can be a name, a subscript, + /// or a chained attribute access. + AttrOpAssign { + object: ExprLoc, + attr: EitherStr, + op: Operator, + value: ExprLoc, + /// Position of the attribute expression (e.g., `point.x`) for traceback carets. + target_position: CodeRange, + }, + /// Attribute assignment (e.g., `point.x = 5` or `a.b.c = 5`). + /// + /// Assigns a value to an attribute on an object. For mutable dataclasses, + /// this sets the field value. Returns an error for immutable objects. + /// Supports chained attribute access on the left-hand side. + AttrAssign { + object: ExprLoc, + attr: EitherStr, + target_position: CodeRange, + value: ExprLoc, + }, + /// Chained assignment (e.g., `a = b = c = value` or `a = lst[i] = obj.x = value`). + /// + /// Python evaluates the right-hand side exactly once and then assigns the resulting + /// value to each target in left-to-right source order. The compiler realises this + /// by evaluating `object`, duplicating its value on the stack before each non-final + /// target's store, and letting the final target consume the remaining copy. + /// + /// Only emitted when there are two or more targets; single-target assignments still + /// use the simpler `Assign`/`UnpackAssign`/`SubscriptAssign`/`AttrAssign` variants + /// so the hot path stays flat. + ChainAssign { + /// Targets to assign to, in left-to-right source order. + targets: Vec, + /// The right-hand side expression, evaluated exactly once. + object: ExprLoc, + }, + For { + /// Loop target - either a single identifier or tuple unpacking pattern. + target: UnpackTarget, + iter: ExprLoc, + body: Vec, + or_else: Vec, + }, + /// While loop statement: `while test: body [else: orelse]` + /// + /// Executes body repeatedly while test is truthy. If the loop exits normally + /// (not via break), the else block runs. + While { + test: ExprLoc, + body: Vec, + or_else: Vec, + }, + /// Break statement - exits the innermost loop. + /// + /// When executed, control flow jumps past the loop's else block (if any). + /// Must be inside a loop, otherwise a `SyntaxError` is raised at compile time. + Break { + position: CodeRange, + }, + /// Continue statement - jumps to the next iteration of the innermost loop. + /// + /// When executed, control flow jumps back to the loop's iterator advancement. + /// Must be inside a loop, otherwise a `SyntaxError` is raised at compile time. + Continue { + position: CodeRange, + }, + If { + test: ExprLoc, + body: Vec, + or_else: Vec, + }, + /// Function definition (e.g. `def foo(): ...`). + /// + /// Decorators live on the statement rather than inside `F` because `F` is + /// also a class body and a method, neither of which can carry them — and + /// because a decorator is part of the `def` statement, not of the function + /// object it produces. Mirrors [`Node::ClassDef`]. + FunctionDef { + /// The function itself: signature and body, riding the `F` = + /// Raw→Prepared pipeline. + def: F, + /// In source order; evaluated in the enclosing scope and applied + /// bottom-up (`foo = deco(foo)`), like CPython. + decorators: Vec, + }, + /// Class definition (e.g. `class Foo: ...`). + /// + /// Modelled on CPython's class-body code object: the class body is a + /// synthetic zero-argument function ([`body`](Self::ClassDef::body), riding + /// the same `F` = Raw→Prepared pipeline as [`Node::FunctionDef`]) that + /// executes the class statements top-to-bottom into its own scope, then + /// assembles the namespace and returns a `Class`. Methods are ordinary + /// `FunctionDef`s in that body (with `self` as the first parameter); class + /// variables are `Assign`s. Class decorators are supported (see + /// [`decorators`](Self::ClassDef::decorators)); inheritance, metaclasses and + /// decorators on a `def` — including `classmethod`/`staticmethod`/`property` + /// — are rejected at parse time. See `limitations/classes.md`. + ClassDef { + /// The class name identifier (resolved to an enclosing-scope slot at prepare time). + name: Identifier, + /// The synthetic class-body function: its body is the class statements + /// in source order. Prepared and compiled exactly like a function; its + /// emitted code ends by building the namespace `Dict` and returning the + /// `Class` object. + body: F, + /// Top-level member names (methods + class vars) in source order. + /// Each is resolved to a class-body-local slot during prepare; the + /// compiler uses them to assemble the namespace dict. + members: Vec, + /// In source order; evaluated in the enclosing scope and applied + /// bottom-up (`cls = deco(cls)`), like CPython. + decorators: Vec, + /// Source position of the `class` statement (for error reporting). + position: CodeRange, + }, + /// Global variable declaration. Only present in parsed form, consumed during prepare. + /// + /// Declares that the listed names refer to module-level (global) variables, + /// allowing functions to read and write them instead of creating local variables. + Global { + position: CodeRange, + names: Vec, + }, + /// Nonlocal variable declaration. Only present in parsed form, consumed during prepare. + /// + /// Declares that the listed names refer to variables in enclosing function scopes, + /// allowing nested functions to read and write them instead of creating local variables. + Nonlocal { + position: CodeRange, + names: Vec, + }, + /// Try/except/else/finally block. + /// + /// Executes body, catches matching exceptions with handlers, runs else if no exception, + /// and always runs finally. + Try(Try), + /// `match SUBJECT:` with one or more `case` clauses (PEP 634). + /// + /// The subject is evaluated once; cases are tried top to bottom and the + /// first whose pattern matches (and whose guard, if any, is truthy) runs. + /// Nothing happens when no case matches. See `limitations/match.md`. + Match { + subject: ExprLoc, + cases: Vec>, + /// Source position of the `match` statement, for caret placement. + position: CodeRange, + }, + /// `with EXPR [as TARGET]: BODY` — runs BODY with a context manager. + /// + /// Semantics match CPython: `EXPR` is evaluated, `__enter__` is called on + /// the result and bound to `TARGET` (if present), then `BODY` runs. On a + /// normal exit `__exit__(None, None, None)` is called; on exception, + /// `__exit__(type, value, None)` is called (Monty has no traceback objects), + /// and a truthy return value suppresses the exception. + /// + /// `target` is `Option` to permit `with foo() as (a, b):` + /// shapes uniformly with [`Node::For`]; today the parser only emits the + /// `Name` variant since other unpack patterns are not yet exercised by + /// any user. + /// + /// Multi-item `with a() as x, b() as y:` is desugared into nested `With` + /// nodes by the parser, so this variant only ever carries a single + /// context. See `parse.rs` for the lowering and `limitations/with.md` + /// for the user-facing semantics. + With { + context: ExprLoc, + target: Option, + body: Vec, + position: CodeRange, + }, + /// Import statement (e.g., `import sys`, `import sys, os`, `import sys as s`). + /// + /// Loads one or more modules and binds them to names in the current namespace. + /// Multi-module imports like `import sys, os` are represented as a single node + /// with multiple entries in the vector. + Import { + /// The modules to import, each with a module name and binding target. + names: Vec, + }, + /// From-import statement (e.g., `from typing import TYPE_CHECKING`). + /// + /// Imports specific names from a module into the current namespace. + ImportFrom { + /// The top-level module to load (`a` for `from a.b import c`). + module_name: StringId, + /// The further components of a dotted module name, in order. + submodules: Vec, + /// Names to import: (import_name, binding) pairs. + /// The import_name is the name in the module, the binding is the local name + /// (alias if provided, otherwise the import name) with resolved namespace slot. + names: Vec<(StringId, Identifier)>, + /// Source position for error reporting. + position: CodeRange, + }, +} + +/// A prepared function definition with resolved names and scope information. +/// +/// This is created during the prepare phase and contains everything needed to +/// compile the function to bytecode. The function body has all names resolved +/// to namespace indices with proper scoping. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PreparedFunctionDef { + /// The function name identifier with resolved namespace index. + pub name: Identifier, + /// The function signature with parameter names and default counts. + pub signature: Signature, + /// The prepared function body with resolved names. + pub body: Vec>, + /// Number of local variable slots needed in the namespace. + pub namespace_size: usize, + /// Enclosing locations for variables captured from enclosing scopes. + /// + /// At definition time each source supplies a cell `HeapId` to bundle into + /// the `Closure`. Parallel (same index/order) to [`Self::free_var_slots`]. + pub free_var_enclosing_slots: Vec, + /// This function's own namespace slots that receive the captured free-var + /// cells, parallel to [`Self::free_var_enclosing_slots`]: cell `i` (gathered + /// from `free_var_enclosing_slots[i]` in the enclosing frame) is installed + /// at `free_var_slots[i]` when this frame is created. + /// + /// Slots are explicit rather than positional because a transitively + /// captured (pass-through) variable's slot is allocated late during + /// preparation and so does not fall in the contiguous param/cell/free + /// region the namespace layout otherwise follows. + pub free_var_slots: Vec, + /// Names parallel to `free_var_slots`, including captures never read by this body. + /// The compiler records them so `locals()` can report pass-through cells. + pub free_var_names: Vec, + /// This function's own namespace slots for cell variables (locals captured + /// by nested functions). A fresh cell is created for each at call time and + /// stored at `cell_var_slots[i]`. Parallel to [`Self::cell_param_indices`]. + pub cell_var_slots: Vec, + /// Maps each cell variable (parallel to [`Self::cell_var_slots`]) to its + /// parameter index, if the cell is for a captured parameter. + /// + /// When a parameter is also captured by nested functions, its bound value + /// must be copied into the cell after argument binding; `Some(param_index)` + /// names that parameter, `None` means the cell starts `Undefined`. + pub cell_param_indices: Vec>, + /// Prepared default value expressions, evaluated at function definition time. + /// + /// Layout: `[pos_defaults...][arg_defaults...][kwarg_defaults...]` + /// Each group contains only the parameters that have defaults, in declaration order. + /// The counts in `signature` indicate how many defaults exist for each group. + pub default_exprs: Vec, + /// Whether this is an async function (`async def`). + /// + /// When true, calling this function creates a `Coroutine` object instead of + /// immediately pushing a frame. + pub is_async: bool, +} + +/// Type alias for prepared AST nodes (output of prepare phase). +pub type PreparedNode = Node; + +/// Binary operators for arithmetic, bitwise, and boolean operations. +/// +/// The comment on each variant shows the source-level symbol. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub enum Operator { + // `+` + Add, + // `-` + Sub, + // `*` + Mult, + // `@` + MatMult, + // `/` + Div, + // `%` + Mod, + // `**` + Pow, + // `<<` + LShift, + // `>>` + RShift, + // `|` + BitOr, + // `^` + BitXor, + // `&` + BitAnd, + // `//` + FloorDiv, + // bool operators + // `and` + And, + // `or` + Or, +} + +/// Defined separately since these operators always return a bool. +/// +/// The strum `serialize` attribute on each variant is the source-level symbol, +/// and drives both `Display` and [`as_str`](Self::as_str). +#[repr(u8)] +#[derive( + Clone, + Copy, + Debug, + PartialEq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumIter, + strum::FromRepr, + strum::IntoStaticStr, +)] +pub enum CmpOperator { + #[strum(serialize = "==")] + Eq = 0, + #[strum(serialize = "!=")] + NotEq = 1, + #[strum(serialize = "<")] + Lt = 2, + #[strum(serialize = "<=")] + LtE = 3, + #[strum(serialize = ">")] + Gt = 4, + #[strum(serialize = ">=")] + GtE = 5, + #[strum(serialize = "is")] + Is = 6, + #[strum(serialize = "is not")] + IsNot = 7, + #[strum(serialize = "in")] + In = 8, + #[strum(serialize = "not in")] + NotIn = 9, +} + +impl CmpOperator { + /// The source-level symbol, e.g. `==` or `not in`. Same string `Display` + /// renders, but borrowed rather than formatted, so the error paths that + /// need it (incomparable ordering `TypeError`s, assert failure messages) + /// don't allocate. + pub fn as_str(self) -> &'static str { + self.into() + } + + /// Stable u8 encoding used in the low nibble of the `Assert` / + /// `AssertFailed` flags operand (see `bytecode::op::assert_flags`). + pub const fn as_operand(self) -> u8 { + self as u8 + } +} + +/// Computes an FNV-1a hash over comparison-operator identities and serialization. +#[cfg(test)] +pub(crate) fn comparison_operators_fingerprint() -> u64 { + const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + const PRIME: u64 = 0x0100_0000_01b3; + + fn update(hash: &mut u64, bytes: &[u8]) { + for byte in u32::try_from(bytes.len()) + .expect("fingerprint field length fits u32") + .to_le_bytes() + { + *hash ^= u64::from(byte); + *hash = hash.wrapping_mul(PRIME); + } + for byte in bytes { + *hash ^= u64::from(*byte); + *hash = hash.wrapping_mul(PRIME); + } + } + + let mut operators = CmpOperator::iter().collect::>(); + operators.sort_unstable_by_key(|operator| *operator as u8); + let mut hash = OFFSET_BASIS; + for operator in operators { + update(&mut hash, &[operator as u8]); + update(&mut hash, format!("{operator:?}").as_bytes()); + update(&mut hash, operator.as_str().as_bytes()); + update( + &mut hash, + &postcard::to_allocvec(&operator).expect("CmpOperator serialization cannot fail"), + ); + } + hash +} diff --git a/crates/bashkit-monty/src/frozen.rs b/crates/bashkit-monty/src/frozen.rs new file mode 100644 index 000000000..0dd48116d --- /dev/null +++ b/crates/bashkit-monty/src/frozen.rs @@ -0,0 +1,100 @@ +//! Shared compilation and dispatch for internal Python implementations. +//! +//! Internal functions use ordinary VM frames and suspension but are hidden from +//! tracebacks and namespace introspection. Private native helpers arrive as +//! explicit arguments, never through user globals or importable modules. + +use monty_types::CompileOptions; +use serde::{Deserialize, Serialize}; + +use crate::{ + args::ArgValues, + builtins::next, + bytecode::{CallResult, Compiler, VM}, + exception_private::RunResult, + intern::{CompileInterns, FunctionId, Interns}, + modules::functools, + name_map::NameMap, + parse::parse_with_interner, + prepare::prepare_with_existing_names, + types::{iter, lru_cache}, +}; + +/// Identifies an internal implementation with one authoritative source definition. +/// Qualified names persist in dumps; the registry uses compact enum keys at runtime. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub(crate) enum FrozenFunction { + /// Suspendable fold loop behind `functools.reduce`. + #[serde(rename = "functools.reduce")] + FunctoolsReduce, + /// Validate the result of a suspendable user `__iter__` method. + #[serde(rename = "builtins.iter")] + Iter, + /// Store a cached call's result only after it returns successfully. + #[serde(rename = "functools._lru_cache_miss")] + LruCacheMiss, + /// Return a default when a suspendable user `__next__` method is exhausted. + #[serde(rename = "builtins.next_default")] + NextDefault, +} + +impl FrozenFunction { + /// Prepares an unpublished implementation using this session's intern IDs. + /// The caller publishes the overlay before installing its frame. + pub(crate) fn compile(self, interns: &Interns) -> RunResult<(FunctionId, CompileInterns<'_>)> { + let source = self.source(); + let mut overlay = CompileInterns::new(interns); + let index = overlay.functions_len(); + let mut globals = NameMap::new(); + let nodes = + parse_with_interner(source, "", &mut overlay).map_err(|e| e.into_run_error(source))?; + let nodes = prepare_with_existing_names(nodes, &overlay, &mut globals).map_err(|e| e.into_run_error(source))?; + Compiler::compile_module(&nodes, &mut overlay, &globals, CompileOptions::default()) + .map_err(|e| e.into_run_error(source))?; + assert_eq!( + overlay.functions_len(), + index + 1, + "frozen source must define one function" + ); + assert_eq!( + globals.len(), + 1, + "frozen source must take its dependencies as arguments" + ); + // Successful compilation checked the bytecode's function-ID limit. + let id = FunctionId::from_index(u16::try_from(index).expect("compiled function ID fits u16")); + Ok((id, overlay)) + } + + /// Selects one self-contained function; dependencies arrive as arguments, not globals. + fn source(self) -> &'static str { + match self { + Self::FunctoolsReduce => functools::REDUCE_SOURCE, + Self::Iter => iter::ITER_SOURCE, + Self::LruCacheMiss => lru_cache::CACHE_MISS_SOURCE, + Self::NextDefault => next::NEXT_DEFAULT_SOURCE, + } + } +} + +/// Native primitives passed directly to internal Python functions. +/// These identities and their signatures are part of the captured bytecode's ABI. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, strum::Display)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum FrozenFunctions { + /// Call a user `__iter__` without validating its result yet. + GetIter, + /// Insert a successful result into a cache wrapper. + Store, + /// Check the result returned by a user `__iter__` method. + ValidateIterator, +} + +/// Dispatches private helpers using the same argument ownership rules as public natives. +pub(crate) fn call_helper(function: FrozenFunctions, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + match function { + FrozenFunctions::GetIter => iter::call_get_iter(args, vm), + FrozenFunctions::Store => lru_cache::call_store(args, vm).map(CallResult::Value), + FrozenFunctions::ValidateIterator => iter::call_validate_iterator(args, vm).map(CallResult::Value), + } +} diff --git a/crates/bashkit-monty/src/fstring.rs b/crates/bashkit-monty/src/fstring.rs new file mode 100644 index 000000000..dcffea803 --- /dev/null +++ b/crates/bashkit-monty/src/fstring.rs @@ -0,0 +1,2555 @@ +//! F-string type definitions and formatting functions. +//! +//! This module contains the AST types for f-strings (formatted string literals) +//! and the runtime formatting functions used by the bytecode VM. +//! +//! F-strings can contain literal text and interpolated expressions with optional +//! conversion flags (`!s`, `!r`, `!a`) and format specifications. + +use std::{fmt, fmt::Write, iter::Peekable, str, str::FromStr}; + +pub use monty_types::FormatFloat; +use monty_types::{LARGE_RESULT_THRESHOLD, ResourceTracker}; +use num_bigint::BigInt; +use num_traits::{Signed, ToPrimitive}; +use unicode_general_category::{GeneralCategory, get_general_category}; + +use crate::{ + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + expressions::ExprLoc, + heap::HeapData, + intern::StringId, + py_value::PyValue, + resource_checks::check_repeat_size, + string_builder::StringBuilder, + types::{ + Complex, PyTrait, Type, + long_int::{PyInt, check_bits_str_digits_limit}, + }, + value::Value, +}; + +// ============================================================================ +// F-string type definitions +// ============================================================================ + +/// Conversion flags for f-string interpolations. +/// +/// These control how the value is converted to string before formatting: +/// - `None`: Use default string conversion (equivalent to `str()`) +/// - `Str` (`!s`): Explicitly call `str()` +/// - `Repr` (`!r`): Call `repr()` for debugging representation +/// - `Ascii` (`!a`): Call `ascii()` for ASCII-safe representation +#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize, serde::Deserialize)] +pub enum ConversionFlag { + #[default] + None, + /// `!s` - convert using `str()` + Str, + /// `!r` - convert using `repr()` + Repr, + /// `!a` - convert using `ascii()` (escapes non-ASCII characters) + Ascii, +} + +/// A single part of an f-string. +/// +/// F-strings are composed of literal text segments and interpolated expressions. +/// For example, `f"Hello {name}!"` has three parts: +/// - `Literal(interned_hello)` (StringId for "Hello ") +/// - `Interpolation { expr: name, ... }` +/// - `Literal(interned_exclaim)` (StringId for "!") +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum FStringPart { + /// Literal text segment (e.g., "Hello " in `f"Hello {name}"`) + /// The StringId references the interned string in the Interns table. + Literal(StringId), + /// Interpolated expression with optional conversion and format spec + Interpolation { + /// The expression to evaluate + expr: Box, + /// Conversion flag: `None`, `!s` (str), `!r` (repr), `!a` (ascii) + conversion: ConversionFlag, + /// Optional format specification (can contain nested interpolations) + format_spec: Option, + /// Debug prefix for `=` specifier (e.g., "a=" for f'{a=}', " a = " for f'{ a = }'). + /// When present, this text is prepended to the output and repr conversion is used + /// by default (unless an explicit conversion is specified). + debug_prefix: Option, + }, +} + +/// Format specification for f-string interpolations. +/// +/// Can be either a pre-parsed static spec or contain nested interpolations. +/// For example: +/// - `f"{value:>10}"` has `FormatSpec::Static(encoded)` where `encoded` is the +/// bit-packed form produced by [`encode_format_spec`] +/// - `f"{value:{width}}"` has `FormatSpec::Dynamic` with the `width` variable +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum FormatSpec { + /// Pre-parsed and pre-encoded static format spec (e.g., ">10s", ".2f"). + /// + /// Parsing and encoding both happen at parse time so the compiler can + /// stamp this value straight into the bytecode constant pool as a + /// `Value::Int` — no further work, no fallible conversions. The VM + /// recognises it via the `FORMAT_VALUE_STATIC_SPEC` flag on the + /// emitted `FormatValue` opcode (not by inspecting the `Value` + /// variant) and decodes in-place. + /// + /// Specs whose width or precision exceed the encoding's capacity (see + /// [`MAX_ENCODED_WIDTH`]/[`MAX_ENCODED_PRECISION`]) are emitted as + /// `Dynamic` instead so the VM can re-parse them at runtime. + Static(i64), + /// Dynamic format spec with nested f-string parts + /// + /// These must be evaluated at runtime, then parsed into a `ParsedFormatSpec`. + Dynamic(Vec), +} + +/// Alignment specifier for the format mini-language. +/// +/// `Align::SignAware` (`=`) is only valid on numeric formats; the others +/// apply to any value. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum Align { + /// `<` — left-align the value, pad on the right. + Left, + /// `>` — right-align the value, pad on the left. + Right, + /// `^` — center the value, pad on both sides. + Center, + /// `=` — sign-aware: pad between sign and digits (numbers only). + SignAware, +} + +/// Sign handling specifier for numeric formats. +/// +/// `Sign::Minus` is Python's default (sign shown only for negative values), +/// and is also what an absent specifier means at runtime — so the parser +/// stores it as `Option::None` to keep "no spec given" distinct from +/// the explicit `-` form for round-tripping. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum Sign { + /// `+` — always emit a sign (`+` for positives, `-` for negatives). + Plus, + /// `-` — sign shown only for negatives (Python default). + Minus, + /// ` ` (space) — space for positives, `-` for negatives. + Space, +} + +/// Type character for the format mini-language. +/// +/// Selects between formatting families (integer base, float notation, +/// string). Values that don't appear here (e.g. `i`, `r`) are rejected at +/// parse time. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum TypeChar { + /// `b` — binary integer. + B, + /// `c` — integer codepoint as a single character. + C, + /// `d` — decimal integer. + D, + /// `e` — lowercase exponential float. + E, + /// `E` — uppercase exponential float. + EUpper, + /// `f` — fixed-point float. + F, + /// `F` — fixed-point float (uppercase NaN/inf). + FUpper, + /// `g` — general-format float (chooses between fixed and exponential). + G, + /// `G` — general-format float (uppercase exponent). + GUpper, + /// `n` — locale-aware integer (currently unimplemented; rejected at runtime). + N, + /// `o` — octal integer. + O, + /// `s` — string. + S, + /// `x` — lowercase hex integer. + X, + /// `X` — uppercase hex integer. + XUpper, + /// `%` — percentage float (multiplies by 100 and appends `%`). + Percent, +} + +/// Thousands-grouping specifier for numeric formats (`,` and `_`). +/// +/// Selects which separator is inserted between digit groups. The *group +/// size* is not stored here — it's 3 for decimal and float presentations +/// but 4 for the binary/octal/hex integer presentations (which only accept +/// `_`), so it's derived from the type char at format time. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum Grouping { + /// `,` — comma separator. Only valid for decimal/float presentations. + Comma, + /// `_` — underscore separator. Valid for decimal/float (groups of 3) and + /// for binary/octal/hex (groups of 4). + Underscore, +} + +impl Grouping { + /// The separator character inserted between digit groups. + fn separator(self) -> char { + match self { + Self::Comma => ',', + Self::Underscore => '_', + } + } +} + +impl Align { + /// Parses a format-spec alignment character into the corresponding variant. + pub fn from_char(c: char) -> Option { + match c { + '<' => Some(Self::Left), + '>' => Some(Self::Right), + '^' => Some(Self::Center), + '=' => Some(Self::SignAware), + _ => None, + } + } +} + +impl Sign { + /// Parses a format-spec sign character into the corresponding variant. + pub fn from_char(c: char) -> Option { + match c { + '+' => Some(Self::Plus), + '-' => Some(Self::Minus), + ' ' => Some(Self::Space), + _ => None, + } + } +} + +impl TypeChar { + /// Parses a format-spec type character into the corresponding variant. + /// + /// Returns `None` for characters that aren't part of the format + /// mini-language type set — used by [`ParsedFormatSpec::from_str`] to + /// decide whether the trailing character is a type spec or an error. + pub fn from_char(c: char) -> Option { + match c { + 'b' => Some(Self::B), + 'c' => Some(Self::C), + 'd' => Some(Self::D), + 'e' => Some(Self::E), + 'E' => Some(Self::EUpper), + 'f' => Some(Self::F), + 'F' => Some(Self::FUpper), + 'g' => Some(Self::G), + 'G' => Some(Self::GUpper), + 'n' => Some(Self::N), + 'o' => Some(Self::O), + 's' => Some(Self::S), + 'x' => Some(Self::X), + 'X' => Some(Self::XUpper), + '%' => Some(Self::Percent), + _ => None, + } + } + + /// Renders the type character back into its source form. Used for + /// error messages like "Unknown format code 'X' for object of type 'T'". + pub fn as_char(self) -> char { + match self { + Self::B => 'b', + Self::C => 'c', + Self::D => 'd', + Self::E => 'e', + Self::EUpper => 'E', + Self::F => 'f', + Self::FUpper => 'F', + Self::G => 'g', + Self::GUpper => 'G', + Self::N => 'n', + Self::O => 'o', + Self::S => 's', + Self::X => 'x', + Self::XUpper => 'X', + Self::Percent => '%', + } + } +} + +/// Parsed format specification following Python's format mini-language. +/// +/// Format: `[[fill]align][sign][z][#][0][width][grouping_option][.precision][type]` +/// +/// This struct is parsed at parse time for static format specs, avoiding runtime +/// string parsing. For dynamic format specs, parsing happens after evaluation. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub struct ParsedFormatSpec { + /// Fill character for padding (default: space). + pub fill: char, + /// Alignment, or `None` if not specified. + pub align: Option, + /// Sign handling, or `None` if not specified (treated as [`Sign::Minus`]). + pub sign: Option, + /// Alternate form (`#`): adds the `0b`/`0o`/`0x` base prefix to + /// binary/octal/hex integers and forces a decimal point on floats. + /// Validity against the presentation type is checked at format time. + pub alternate: bool, + /// Negative-zero coercion flag (`z`, Python 3.11+): a negative value that + /// rounds to zero at the chosen precision is emitted as positive zero + /// (`f"{-0.001:z.1f}"` → `0.0`). Valid only for floating-point + /// presentations (checked at format time). Like [`Self::frac_grouping`] it + /// has no spare encoding bit, so [`encode_format_spec`] forces specs that + /// use it onto the dynamic-spec path. + pub z: bool, + /// Whether to zero-pad numbers. + pub zero_pad: bool, + /// Minimum field width. + pub width: usize, + /// Thousands-grouping separator (`,` or `_`) for the *integer* digits, or + /// `None` if not specified. Validity against the presentation type is + /// checked at format time. + pub grouping: Option, + /// Grouping separator (`,` or `_`) for the *fractional* digits — the + /// Python 3.14 `[.precision][grouping]` extension (`f"{x:.6_f}"`). Groups + /// every 3 digits *from the left* of the fraction. `None` if absent. Specs + /// that set this can't use the compact bit encoding (no spare bits), so + /// [`encode_format_spec`] forces them onto the dynamic-spec path. + pub frac_grouping: Option, + /// Precision for floats or max width for strings. + pub precision: Option, + /// Type character, or `None` if not specified (defaults are type-dependent). + pub type_char: Option, +} + +/// Reason a [`ParsedFormatSpec`] couldn't be built from its source text. +/// +/// Lets callers distinguish CPython-style invalid specs ([`Self::Malformed`]) +/// from specs whose width or precision exceeds [`usize`] +/// ([`Self::NumberOverflow`]). The `Display` impl on [`ParseFormatSpecError`] +/// turns each variant into a human-readable message; runtime callers append +/// `" for object of type 'T'"` to mirror CPython's error style. +#[derive(Debug, Clone)] +pub enum ParseFormatSpecReason { + /// Spec doesn't match the format mini-language grammar — what CPython + /// itself raises `ValueError: Invalid format specifier` for. Reserved for + /// genuinely malformed specs (two or more trailing characters after the + /// type field, e.g. `kk`/`.2fz`); a *single* unrecognised trailing char is + /// [`Self::UnknownFormatCode`] instead, matching CPython's split. + Malformed, + /// A width or precision decimal integer overflows [`usize`] (e.g. + /// 22 nines in a row). Without this we'd silently truncate to 0 — see + /// [`consume_decimal_usize`]. + NumberOverflow, + /// A `.` with no following precision digits *and* no fractional grouping + /// option (`.f`, `.`, `.d`) — CPython's `ValueError: Format specifier + /// missing precision`. A `.` followed by a grouping char (`._f`, `.,`) is + /// valid and not this error. + MissingPrecision, + /// The single trailing char isn't a recognised presentation type + /// (`5k`, `k`). Carries the offending char; the runtime caller appends + /// `" for object of type 'T'"` to produce CPython's `Unknown format code + /// 'k' for object of type 'int'`. + UnknownFormatCode(char), + /// An integer grouping option (`,`/`_`) sits next to something it can't + /// coexist with — the other grouping char (`,_`) or an unrecognised + /// trailing char (`,k`). Holds CPython's exact, self-contained wording + /// (`Cannot specify ',' with 'k'.`), which carries no type suffix. + GroupingConflict(String), +} + +impl ParseFormatSpecReason { + /// Whether CPython appends the formatted value's type to this error. + pub(crate) fn needs_type_suffix(&self) -> bool { + matches!( + self, + Self::Malformed | Self::NumberOverflow | Self::UnknownFormatCode(_) + ) + } + + /// Builds the [`Self::GroupingConflict`] wording for an integer grouping + /// `g` immediately followed by the unrecognised trailing char `c`, + /// reproducing CPython's two distinct messages: `Cannot specify both ',' + /// and '_'.` when `c` is the *other* grouping char, otherwise `Cannot + /// specify '' with ''.`. + fn grouping_conflict(g: Grouping, c: char) -> Self { + let msg = if (c == ',' || c == '_') && c != g.separator() { + "Cannot specify both ',' and '_'.".to_owned() + } else { + format!("Cannot specify '{}' with '{c}'.", g.separator()) + }; + Self::GroupingConflict(msg) + } +} + +/// Error returned by [`ParsedFormatSpec::from_str`]. +/// +/// Holds the original spec text plus a [`ParseFormatSpecReason`] so the +/// runtime and compile-time error wrappers can choose between +/// CPython-matching messages and Monty-specific ones. +#[derive(Debug, Clone)] +pub struct ParseFormatSpecError { + /// The full spec text that failed to parse. + pub spec: String, + /// Why parsing failed. + pub reason: ParseFormatSpecReason, +} + +impl ParseFormatSpecError { + fn new(spec: &str, reason: ParseFormatSpecReason) -> Self { + Self { + spec: spec.to_owned(), + reason, + } + } + + /// Whether this error should be deferred to the runtime (dynamic-spec) path + /// rather than raised as a compile-time `SyntaxError`. + /// + /// CPython raises these as *runtime* `ValueError`s whose exact wording is + /// value-type-dependent (`Unknown format code`) or otherwise only resolvable + /// at format time, so the compiler emits the literal spec for the VM to + /// re-parse and raise the matching error. Genuinely-malformed specs and + /// `usize` overflow stay compile-time errors (the latter is a deliberate, + /// documented divergence). + pub fn defer_to_runtime(&self) -> bool { + matches!( + self.reason, + ParseFormatSpecReason::MissingPrecision + | ParseFormatSpecReason::UnknownFormatCode(_) + | ParseFormatSpecReason::GroupingConflict(_) + ) + } +} + +impl fmt::Display for ParseFormatSpecError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.reason { + ParseFormatSpecReason::Malformed => write!(f, "Invalid format specifier '{}'", self.spec), + ParseFormatSpecReason::NumberOverflow => { + write!( + f, + "Invalid format specifier '{}': width or precision overflows usize", + self.spec + ) + } + ParseFormatSpecReason::MissingPrecision => f.write_str("Format specifier missing precision"), + ParseFormatSpecReason::UnknownFormatCode(c) => write!(f, "Unknown format code '{c}'"), + ParseFormatSpecReason::GroupingConflict(msg) => f.write_str(msg), + } + } +} + +impl ParsedFormatSpec { + /// Parses a format specification string into its components. + /// + /// Runtime callers keep the reason separate from the borrowed source so a + /// failed parse does not duplicate a guest-sized format spec. + pub(crate) fn parse_runtime(spec: &str) -> Result { + if spec.is_empty() { + return Ok(Self { + fill: ' ', + ..Default::default() + }); + } + + let mut result = Self { + fill: ' ', + ..Default::default() + }; + let mut chars = spec.chars().peekable(); + + // Parse fill and align: [[fill]align] + // If the second char is an align marker, the first is the fill; otherwise + // the first char (if any) may itself be the align. + let mut fill_specified = false; + if let Some(align) = spec.chars().nth(1).and_then(Align::from_char) { + result.fill = chars.next().unwrap_or(' '); + fill_specified = true; + chars.next(); + result.align = Some(align); + } else { + result.align = chars.next_if_map(|c| Align::from_char(c).ok_or(c)); + } + + result.sign = chars.next_if_map(|c| Sign::from_char(c).ok_or(c)); + + // `z` (negative-zero coercion) sits between the sign and `#` in the + // grammar. A `z` in *fill* position (`z>8`) was already consumed by the + // fill/align step above, so reaching here means the flag. Whether it's + // legal for the presentation type is checked at format time. + result.z = chars.next_if_eq(&'z').is_some(); + + // `#` (alternate form). Whether it's legal for the chosen presentation + // type is decided at format time (the value type isn't known here for + // type-less specs), so it's validated in `format_with_spec`. + result.alternate = chars.next_if_eq(&'#').is_some(); + + // Parse the zero-padding flag (must come before width). Per CPython, a + // leading `0` sets the fill to `'0'` (unless a fill char was already + // given) and implies sign-aware (`=`) padding *only when no explicit + // alignment was specified*. With an explicit align (`<05`, `^05`, + // `*<05`) the `0` is merely a fill character, so `zero_pad`/`=` stay + // off and the chosen alignment is honoured. + if chars.next_if_eq(&'0').is_some() { + if !fill_specified { + result.fill = '0'; + } + if result.align.is_none() { + result.zero_pad = true; + } + } + + // Parse width + result.width = consume_decimal_usize(&mut chars) + .map_err(|()| ParseFormatSpecReason::NumberOverflow)? + .unwrap_or(0); + + // Grouping option (`,` or `_` thousands separator). Whether it's + // legal for the chosen presentation type can't be decided here (the + // value type isn't known until format time for type-less specs), so + // it's validated in `format_with_spec`. + result.grouping = chars.next_if(|c| matches!(c, ',' | '_')).map(|c| match c { + ',' => Grouping::Comma, + _ => Grouping::Underscore, + }); + + // Parse precision and an optional fractional grouping option: + // `.[precision][grouping]` (Python 3.14). The grouping char after the + // precision (`.6_`, or `._` with no precision) groups the fractional + // digits; its legality for the presentation type is checked at format + // time alongside the integer grouping. + if chars.next_if_eq(&'.').is_some() { + result.precision = consume_decimal_usize(&mut chars).map_err(|()| ParseFormatSpecReason::NumberOverflow)?; + result.frac_grouping = chars.next_if(|c| matches!(c, ',' | '_')).map(|c| match c { + ',' => Grouping::Comma, + _ => Grouping::Underscore, + }); + // A `.` must introduce either precision digits or a fractional + // grouping option; `.f`/`.`/`.d` are CPython's "missing precision". + if result.precision.is_none() && result.frac_grouping.is_none() { + return Err(ParseFormatSpecReason::MissingPrecision); + } + } + + // The presentation type is the spec's final character. Consume it + // unconditionally — CPython treats *any* single trailing char as the + // type field — so an unrecognised char becomes a specific "Unknown + // format code"/grouping-conflict error rather than the generic + // "Invalid format specifier". Two or more chars after the parsed fields + // are genuinely malformed. + let type_pos = chars.next(); + if chars.peek().is_some() { + return Err(ParseFormatSpecReason::Malformed); + } + if let Some(c) = type_pos { + if let Some(tc) = TypeChar::from_char(c) { + result.type_char = Some(tc); + } else { + // An unrecognised type char: an integer grouping option present + // alongside it makes CPython report the grouping conflict (which + // takes precedence), otherwise it's an unknown format code. + let reason = match result.grouping { + Some(g) => ParseFormatSpecReason::grouping_conflict(g, c), + None => ParseFormatSpecReason::UnknownFormatCode(c), + }; + return Err(reason); + } + } + + Ok(result) + } +} + +impl ParsedFormatSpec { + /// Renders the spec back into source form, for types such as `Decimal` that parse + /// their own spec grammar. + /// + /// The parse is lossy where `0` meets an explicit alignment (`<020` and `0<20` both + /// render as `0<20`) and in redundant spellings (`001`, ` <5`), so the compiler keeps + /// a static spec that does not round-trip as its source text instead. + pub(crate) fn to_spec_string(&self) -> String { + let mut out = String::new(); + if let Some(align) = self.align { + if self.fill != ' ' { + out.push(self.fill); + } + out.push(match align { + Align::Left => '<', + Align::Right => '>', + Align::Center => '^', + Align::SignAware => '=', + }); + } + if let Some(sign) = self.sign { + out.push(match sign { + Sign::Plus => '+', + Sign::Minus => '-', + Sign::Space => ' ', + }); + } + if self.z { + out.push('z'); + } + if self.alternate { + out.push('#'); + } + if self.zero_pad { + out.push('0'); + } + if self.width > 0 { + out.push_str(&self.width.to_string()); + } + if let Some(grouping) = self.grouping { + out.push(grouping.separator()); + } + if self.precision.is_some() || self.frac_grouping.is_some() { + out.push('.'); + if let Some(precision) = self.precision { + out.push_str(&precision.to_string()); + } + if let Some(grouping) = self.frac_grouping { + out.push(grouping.separator()); + } + } + if let Some(type_char) = self.type_char { + out.push(type_char.as_char()); + } + out + } +} + +impl FromStr for ParsedFormatSpec { + type Err = ParseFormatSpecError; + + fn from_str(spec: &str) -> Result { + Self::parse_runtime(spec).map_err(|reason| ParseFormatSpecError::new(spec, reason)) + } +} + +// ============================================================================ +// Format errors +// ============================================================================ + +/// Error type for format specification failures. +/// +/// These errors are returned from formatting functions and should be converted +/// to appropriate Python exceptions (usually ValueError) by the VM. +#[derive(Debug, Clone)] +pub enum FormatError { + /// Invalid alignment for the given type (e.g., '=' alignment on strings). + InvalidAlignment(String), + /// Value out of range (e.g., character code > 0x10FFFF). + Overflow(String), + /// Generic value error (e.g., invalid base, invalid Unicode). + ValueError(String), +} + +impl fmt::Display for FormatError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidAlignment(msg) | Self::Overflow(msg) | Self::ValueError(msg) => { + write!(f, "{msg}") + } + } + } +} + +/// Formats a value according to a format specification, applying type-appropriate formatting. +/// +/// Dispatches to the appropriate formatting function based on the value type and format spec: +/// - Integers: `format_int`, `format_int_base`, `format_char` +/// - Floats: `format_float_f`, `format_float_e`, `format_float_g`, `format_float_percent` +/// - Strings: `format_string` +/// +/// Returns a `ValueError` if the format type character is incompatible with the value type. +pub fn format_with_spec(value: &Value, spec: &ParsedFormatSpec, vm: &mut VM<'_>) -> Result { + let value_type = value.py_type(vm); + + // Bool is an `int` subclass: every integer/float presentation applies to it + // using the numeric value (`1`/`0`), so treat it as an int for dispatch + // while keeping `value_type` (= bool) for error wording. The exception is a + // *directive-free* spec — `str(bool)` wins there (`format(True, "")` is + // `"True"`, not `"1"`). The compiler already elides a literal empty spec + // `f"{b:}"`, but a *runtime* empty spec (`f"{b:{s}}"`, `s == ""`) still + // arrives here as an all-default `ParsedFormatSpec`, so this guard is what + // keeps `format(True, "")` → `"True"`. + let coerced_bool; + let value = if let Value::Bool(b) = value + && spec_has_directives(spec) + { + coerced_bool = Value::Int(i64::from(*b)); + &coerced_bool + } else { + value + }; + + // A `str` value is formatted entirely through the string mini-language: + // `validate_string_spec` rejects (in CPython's precedence order) every flag + // that is meaningless for text, then `format_string` applies precision, + // width, and fill. Handling strings here in one place keeps them off the + // numeric validation/dispatch below and makes the VM's `!s`/`!r`/`!a` + // conversion paths — which reuse the very same two functions — reject + // identical specs (`f"{x:#}"` and `f"{x!s:#}"` raise the same error). + if value_type == Type::Str { + validate_string_spec(spec)?; + // `value` is already a `str`, so borrow it directly — no `py_str` + // round-trip (which would allocate a fresh heap copy just to drop it). + return format_string(value.to_str(vm)?, spec, &vm.heap.tracker); + } + + // A grouping option (`,`/`_`) is only legal for certain presentation + // types; reject the illegal combinations with CPython's message before + // dispatching to a formatter that would otherwise ignore the flag. + if let Some(grouping) = spec.grouping { + validate_grouping(grouping, spec.type_char, value_type)?; + } + if let Some(grouping) = spec.frac_grouping + && spec.type_char == Some(TypeChar::N) + { + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("Cannot specify '{}' with 'n'.", grouping.separator()), + ) + .into()); + } + + // Precision is meaningless for integer presentations. CPython rejects it + // inside the integer formatter — *after* the parse-time grouping check + // above but *before* the `#`/sign checks below, so this ordering matters + // (`{0:#.0c}` reports the precision error, not the alternate-form one). + if spec.precision.is_some() && formats_as_integer(spec.type_char, value_type) { + return Err(SimpleException::new_msg( + ExcType::ValueError, + "Precision not allowed in integer format specifier".to_owned(), + ) + .into()); + } + + // If the presentation type is not valid for this value, CPython reports + // "Unknown format code" *before* the alternate-form check (the type chooses + // the formatter, so an invalid type errors first): `f"{3.14:#c}"` is + // "Unknown format code 'c' for object of type 'float'", not the `#`-with-`c` + // message. The dispatch `match` below also catches this as a safety net. + if let Some(c) = spec.type_char + && !type_valid_for_value(spec.type_char, value_type) + { + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!( + "Unknown format code '{}' for object of type '{}'", + c.as_char(), + value_type.name(vm.heap, vm.interns) + ), + ) + .into()); + } + + // `z` (negative-zero coercion) is only meaningful for floating-point + // presentations. CPython rejects it elsewhere with a presentation-specific + // message, *after* the "Unknown format code" check (so a bad type wins) and + // before the alternate-form check (`f"{5:z#}"` reports the `z` error). + // Strings are handled by `validate_string_spec`; here the value is numeric or + // a non-numeric type-less spec (string-formatted, like `validate_alternate`). + if spec.z && !formats_as_float(spec.type_char, value_type) { + let kind = if formats_as_integer(spec.type_char, value_type) { + "integer" + } else { + "string" + }; + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("Negative zero coercion (z) not allowed in {kind} format specifier"), + ) + .into()); + } + + // A sign flag (`+`/`-`/space) is meaningless for the `c` (character) + // presentation, which has no numeric value to sign. CPython rejects it in + // the integer formatter *after* the `z` check (`f"{0: zc}"` reports the `z` + // error, not this one) and before the alternate-form check. The + // `Int`/`Bool` guard keeps a `c` on any other type routing to the + // "Unknown format code" error above instead. + if spec.sign.is_some() && spec.type_char == Some(TypeChar::C) && matches!(value_type, Type::Int | Type::Bool) { + return Err(SimpleException::new_msg( + ExcType::ValueError, + "Sign not allowed with integer format specifier 'c'".to_owned(), + ) + .into()); + } + + // The alternate form (`#`) is likewise illegal for `c`/`s` presentations. + if spec.alternate { + validate_alternate(spec.type_char, value_type)?; + } + + // A complex has two checks of its own, still ahead of the precision preflight + // below so an invalid spec raises `ValueError` whatever its precision costs. + if let Value::Ref(id) = value + && let HeapData::Complex(_) = vm.heap.get(*id) + { + check_complex_spec(spec)?; + } + + // CPython bounds a float precision by `INT_MAX - 1024` before looking at + // the value, so `inf`/`nan` and ints under a float presentation hit it too. + if spec.precision.is_some_and(|precision| precision > MAX_FLOAT_PRECISION) + && formats_as_float(spec.type_char, value_type) + { + return Err(ExcType::value_error_precision_too_big()); + } + + // `spec.precision` on the float formats is rendered as that many decimal + // digits. Reject an attacker-chosen oversized result before formatting; + // tracker-backed builders guard the later copies at their actual size. + // + // This applies to `f`/`e`/`%` always, and to the `g`-family + // (`g`/`G`/`n`/type-less-with-precision) *only* under alternate form (`#`): + // plain `g` strips trailing zeros and caps internally, but `#g` keeps every + // zero so its digit count scales with precision just like `f`. + let precision_scales_output = matches!( + spec.type_char, + Some(TypeChar::F | TypeChar::FUpper | TypeChar::E | TypeChar::EUpper | TypeChar::Percent) + ) || (spec.alternate + && matches!( + spec.type_char, + None | Some(TypeChar::G | TypeChar::GUpper | TypeChar::N) + )); + if let Some(precision) = spec.precision + && precision_scales_output + { + // The number of finite components the precision expands, so the whole + // output is charged before any of it is built. + let finite_parts = match value.py_value(vm) { + PyValue::Int(_) => 1, + PyValue::Float(value) => usize::from(value.is_finite()), + PyValue::Complex(value) => { + let value = value.get(vm.heap); + usize::from(value.real.is_finite()) + usize::from(value.imag.is_finite()) + } + _ => 0, + }; + if finite_parts > 0 { + // Fractional grouping (`f"{v:.{p}_f}"`) weaves in one separator per + // three emitted digits, so the native string reaches ~4/3 × precision + // before `allocate_string` accounts for it; budget the separators too. + let separators = if spec.frac_grouping.is_some() { + precision.saturating_sub(1) / 3 + } else { + 0 + }; + check_repeat_size(precision.saturating_add(separators), finite_parts, &vm.heap.tracker)?; + } + } + + match (value.py_value(vm), spec.type_char) { + (PyValue::Int(integer), _) => integer.format_spec(spec, vm), + (PyValue::Complex(value), _) => format_complex(*value.get(vm.heap), spec, &vm.heap.tracker), + + // Float formatting. A type-less spec with no precision uses the repr + // (shortest) digits, *not* `g` — only an explicit `g`/`G` or a type-less + // spec that carries a precision selects the `g` algorithm. + (PyValue::Float(f), None) if spec.precision.is_none() => format_float_default(f, spec, &vm.heap.tracker), + // `n` on a float behaves like `g` (locale-aware in CPython; C-locale + // here, so plain `g`). + (PyValue::Float(f), None | Some(TypeChar::G | TypeChar::GUpper | TypeChar::N)) => { + format_float_g(f, spec, &vm.heap.tracker) + } + (PyValue::Float(f), Some(TypeChar::F | TypeChar::FUpper)) => format_float_f(f, spec, &vm.heap.tracker), + (PyValue::Float(f), Some(TypeChar::E)) => format_float_e(f, spec, false, &vm.heap.tracker), + (PyValue::Float(f), Some(TypeChar::EUpper)) => format_float_e(f, spec, true, &vm.heap.tracker), + (PyValue::Float(f), Some(TypeChar::Percent)) => format_float_percent(f, spec, &vm.heap.tracker), + + // No type specifier on a non-string value: convert to string and + // format. (`str` values are handled by the short-circuit above.) + (_, None) => { + let s = value.py_str(vm)?; + defer_drop!(s, vm); + format_string(s.to_str(vm)?, spec, &vm.heap.tracker) + } + + // Type mismatch errors + (_, Some(c)) => Err(SimpleException::new_msg( + ExcType::ValueError, + format!( + "Unknown format code '{}' for object of type '{}'", + c.as_char(), + value_type.name(vm.heap, vm.interns) + ), + ) + .into()), + } +} + +impl<'h> PyInt<'h> { + /// Formats an integer after the caller has validated its numeric presentation. + fn format_spec(&self, spec: &ParsedFormatSpec, vm: &VM<'h>) -> RunResult { + let tracker = &vm.heap.tracker; + self.with_value( + vm, + |value| match spec.type_char { + None | Some(TypeChar::D | TypeChar::N) => format_int(value, spec, tracker), + Some(TypeChar::B) => format_int_base(value, 2, false, spec, tracker), + Some(TypeChar::O) => format_int_base(value, 8, false, spec, tracker), + Some(TypeChar::X) => format_int_base(value, 16, false, spec, tracker), + Some(TypeChar::XUpper) => format_int_base(value, 16, true, spec, tracker), + Some(TypeChar::C) => format_char(value, spec, tracker), + Some(TypeChar::F | TypeChar::FUpper) => format_float_f(value as f64, spec, tracker), + Some(TypeChar::E) => format_float_e(value as f64, spec, false, tracker), + Some(TypeChar::EUpper) => format_float_e(value as f64, spec, true, tracker), + Some(TypeChar::G | TypeChar::GUpper) => format_float_g(value as f64, spec, tracker), + Some(TypeChar::Percent) => format_float_percent(value as f64, spec, tracker), + Some(TypeChar::S) => unreachable!("integer presentation was validated"), + }, + |value| format_long_int(value, "int", spec, tracker), + ) + } +} + +/// Validates a format spec for a `str` value, raising the same `ValueError`s +/// CPython does for flags that are meaningless when formatting text. +/// +/// This is the single source of truth for "is this spec legal for a `str`": the +/// string branch of [`format_with_spec`] and the VM's `!s`/`!r`/`!a` conversion +/// paths (which convert to a string and then format it) both route through it, +/// so a value and its converted forms reject identical specs. Checks run in +/// CPython's precedence order — the first violation wins: +/// 1. a grouping option (`,`/`_`) — there is nothing to group in text +/// 2. a presentation type other than `s` +/// 3. a sign flag (`+`/`-`/space) +/// 4. the alternate form (`#`) +/// 5. `=` (sign-aware) alignment +pub fn validate_string_spec(spec: &ParsedFormatSpec) -> Result<(), RunError> { + if let Some(grouping) = spec.grouping { + validate_grouping(grouping, spec.type_char, Type::Str)?; + } + if let Some(c) = spec.type_char + && c != TypeChar::S + { + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("Unknown format code '{}' for object of type 'str'", c.as_char()), + ) + .into()); + } + if let Some(sign) = spec.sign { + let msg = match sign { + Sign::Space => "Space not allowed in string format specifier", + Sign::Plus | Sign::Minus => "Sign not allowed in string format specifier", + }; + return Err(SimpleException::new_msg(ExcType::ValueError, msg.to_owned()).into()); + } + if spec.z { + return Err(SimpleException::new_msg( + ExcType::ValueError, + "Negative zero coercion (z) not allowed in string format specifier".to_owned(), + ) + .into()); + } + if spec.alternate { + validate_alternate(spec.type_char, Type::Str)?; + } + if spec.align == Some(Align::SignAware) { + return Err(SimpleException::new_msg( + ExcType::ValueError, + "'=' alignment not allowed in string format specifier".to_owned(), + ) + .into()); + } + Ok(()) +} + +/// Checks that a grouping option is valid for the chosen presentation type, +/// returning CPython's `Cannot specify ',' with 'x'.` error otherwise. +/// +/// `,` is only allowed for decimal/float presentations; `_` additionally +/// allows the binary/octal/hex integer presentations (grouped in fours). For +/// a type-less spec the presentation is taken from the value: numeric values +/// permit grouping, everything else is string-formatted and reported as `s`. +fn validate_grouping(grouping: Grouping, type_char: Option, value_type: Type) -> Result<(), RunError> { + let allowed = match type_char { + None => matches!(value_type, Type::Int | Type::Bool | Type::Float | Type::Complex), + Some(TypeChar::B | TypeChar::O | TypeChar::X | TypeChar::XUpper) => grouping == Grouping::Underscore, + // `c`/`s` have nothing to group; `n` does its own locale grouping and so + // forbids an explicit one (`Cannot specify ',' with 'n'.`). + Some(TypeChar::C | TypeChar::S | TypeChar::N) => false, + // D, E/EUpper, F/FUpper, G/GUpper, Percent all accept both `,` and `_`. + Some(_) => true, + }; + if allowed { + Ok(()) + } else { + // For a type-less spec the value is being string-formatted, so the + // presentation char CPython reports is `s`. + let presentation = type_char.map_or('s', TypeChar::as_char); + Err(SimpleException::new_msg( + ExcType::ValueError, + format!("Cannot specify '{}' with '{presentation}'.", grouping.separator()), + ) + .into()) + } +} + +/// Whether the presentation `type_char` is valid for a value of `value_type`, +/// i.e. a formatter exists for the pair. A `false` result is CPython's "Unknown +/// format code" case. +/// +/// Integer codes (`b`/`c`/`d`/`o`/`x`/`X`) need an `int`/`bool`; float codes +/// (`e`/`E`/`f`/`F`/`g`/`G`/`%`) and `n` accept any real number (an `int` is +/// widened to a float), and all but `%` a `complex` too; `s` needs a `str`; a +/// type-less spec (`None`) is valid for every value (it falls back to `str()`). +fn type_valid_for_value(type_char: Option, value_type: Type) -> bool { + let is_int = matches!(value_type, Type::Int | Type::Bool); + let is_real = is_int || value_type == Type::Float; + let is_num = is_real || value_type == Type::Complex; + match type_char { + None => true, + Some(TypeChar::D | TypeChar::B | TypeChar::O | TypeChar::X | TypeChar::XUpper | TypeChar::C) => is_int, + Some( + TypeChar::E + | TypeChar::EUpper + | TypeChar::F + | TypeChar::FUpper + | TypeChar::G + | TypeChar::GUpper + | TypeChar::N, + ) => is_num, + Some(TypeChar::Percent) => is_real, + Some(TypeChar::S) => value_type == Type::Str, + } +} + +/// Whether `(type_char, value_type)` selects an *integer* presentation, i.e. +/// the value will be rendered via the integer formatter. +/// +/// True for the explicit integer codes (`d`/`b`/`o`/`x`/`X`/`c`) and for a +/// type-less spec on an `int`/`bool` value. Crucially it keys off `value_type` +/// (not the `Value` variant) so big integers (interned or stored as a heap ref +/// but typed `int`) are included. A float or string with one of those codes is +/// *not* an integer presentation — it's a type error handled at dispatch — so +/// this returns false there, letting the "Unknown format code" message win. +fn formats_as_integer(type_char: Option, value_type: Type) -> bool { + let int_value = matches!(value_type, Type::Int | Type::Bool); + match type_char { + // `n` selects the integer formatter for an int value (so precision is + // rejected there) but the float formatter for a float (precision ok). + Some(TypeChar::D | TypeChar::B | TypeChar::O | TypeChar::X | TypeChar::XUpper | TypeChar::C | TypeChar::N) => { + int_value + } + None => int_value, + _ => false, + } +} + +/// Whether `(type_char, value_type)` selects a *float* presentation, i.e. the +/// value will be rendered via one of the `format_float_*` functions. +/// +/// The float codes (`e`/`E`/`f`/`F`/`g`/`G`/`%`) always format as a float +/// (an `int` is widened); `n` and a type-less spec do so only for an actual +/// float or complex value. Used to gate the `z` (negative-zero coercion) flag, +/// which is legal only for float presentations, and the `MAX_FLOAT_PRECISION` cap. +fn formats_as_float(type_char: Option, value_type: Type) -> bool { + match type_char { + Some( + TypeChar::E + | TypeChar::EUpper + | TypeChar::F + | TypeChar::FUpper + | TypeChar::G + | TypeChar::GUpper + | TypeChar::Percent, + ) => true, + Some(TypeChar::N) | None => matches!(value_type, Type::Float | Type::Complex), + _ => false, + } +} + +/// Whether a spec carries any directive — i.e. it is more than the bare, +/// directive-free spec that is equivalent to `str(value)`. +/// +/// Used to decide how a `bool` formats: a directive-free spec yields +/// `str(bool)` (`"True"`), while any directive switches to numeric `int` +/// formatting (`format(True, " ")` → `" 1"`). Equivalent to "the original spec +/// string was empty", since every spec character sets at least one field. +fn spec_has_directives(spec: &ParsedFormatSpec) -> bool { + spec.align.is_some() + || spec.sign.is_some() + || spec.alternate + || spec.z + || spec.zero_pad + || spec.width != 0 + || spec.grouping.is_some() + || spec.frac_grouping.is_some() + || spec.precision.is_some() + || spec.type_char.is_some() +} + +/// Checks that the alternate form (`#`) is valid for the chosen presentation +/// type, returning CPython's wording otherwise. +/// +/// `#` is a no-op for decimal integers and meaningful for binary/octal/hex +/// integers and all float presentations, but is rejected for the character +/// (`c`) and string (`s`) presentations — the latter also covers a type-less +/// spec applied to a non-numeric value (which is string-formatted). +fn validate_alternate(type_char: Option, value_type: Type) -> Result<(), RunError> { + let message = match type_char { + Some(TypeChar::C) => Some("Alternate form (#) not allowed with integer format specifier 'c'"), + Some(TypeChar::S) => Some("Alternate form (#) not allowed in string format specifier"), + None if !matches!(value_type, Type::Int | Type::Bool | Type::Float | Type::Complex) => { + Some("Alternate form (#) not allowed in string format specifier") + } + _ => None, + }; + match message { + Some(msg) => Err(SimpleException::new_msg(ExcType::ValueError, msg.to_owned()).into()), + None => Ok(()), + } +} + +/// Maximum fill codepoint that fits in the 8-bit fill field of the encoded +/// format spec. Latin-1 covers the common cases (`*`, `_`, `-`, `.`, plus +/// any single-byte char); higher codepoints (CJK, emoji, etc.) fall back to +/// a dynamic spec so the VM re-parses at runtime. +pub const MAX_ENCODED_FILL: u32 = 0xFF; + +/// Maximum width that fits in the 20-bit width field of the encoded format spec. +pub const MAX_ENCODED_WIDTH: usize = (1 << 20) - 1; + +/// The largest precision CPython's float-to-string conversion accepts +/// (`DOUBLE_TO_STRING_PRECISION_MAX`, `INT_MAX - 1024`). Above it every float +/// presentation raises `ValueError: precision too big`, finite value or not. +pub const MAX_FLOAT_PRECISION: usize = i32::MAX as usize - 1024; + +/// Maximum precision that fits in the 21-bit precision field of the encoded format +/// spec. One slot (the zero value) is reserved to mean "no precision", so the +/// usable range for an explicit precision is `0..=MAX_ENCODED_PRECISION`. +pub const MAX_ENCODED_PRECISION: usize = (1 << 21) - 2; + +/// Encodes a [`ParsedFormatSpec`] into an `i64` for storage in bytecode constants. +/// +/// Returns `None` if any field exceeds the encoding's capacity — the caller +/// should fall back to a dynamic (string-based) format spec in that case. +/// +/// Encoding layout (occupies bits 0-59; the sign bit is always 0, so the +/// result is a non-negative `i64`): +/// - bits 0-7: fill codepoint (Latin-1; max [`MAX_ENCODED_FILL`], default space=32) +/// - bits 8-10: [`Align`] (0=none, 1=Left, 2=Right, 3=Center, 4=SignAware) +/// - bits 11-12: [`Sign`] (0=none, 1=Plus, 2=Minus, 3=Space) +/// - bit 13: zero_pad +/// - bits 14-33: width (20 bits, max [`MAX_ENCODED_WIDTH`]) +/// - bits 34-54: precision+1 (21 bits; 0 = no precision) +/// - bits 55-59: [`TypeChar`] (0=none, 1-15=B/C/D/E/EUpper/F/FUpper/G/GUpper/N/O/S/X/XUpper/Percent) +/// - bits 60-61: [`Grouping`] (0=none, 1=Comma, 2=Underscore) +/// - bit 62: alternate form (`#`) +/// +/// Bit 62 is the last free bit (bit 63 is the sign bit, which must stay 0); a +/// future flag would need the packing reworked rather than another bit added. +pub fn encode_format_spec(spec: &ParsedFormatSpec) -> Option { + // Fractional grouping and the `z` flag have no spare encoding bit (bit 62, + // alternate, is the last free one), so any spec that uses either falls back + // to the dynamic path where the literal is re-parsed at runtime. + if spec.frac_grouping.is_some() || spec.z { + return None; + } + let fill_code = u32::from(spec.fill); + if fill_code > MAX_ENCODED_FILL { + return None; + } + if spec.width > MAX_ENCODED_WIDTH { + return None; + } + if let Some(p) = spec.precision + && p > MAX_ENCODED_PRECISION + { + return None; + } + + let fill = i64::from(fill_code); + let align: i64 = spec.align.map_or(0, |a| match a { + Align::Left => 1, + Align::Right => 2, + Align::Center => 3, + Align::SignAware => 4, + }); + let sign: i64 = spec.sign.map_or(0, |s| match s { + Sign::Plus => 1, + Sign::Minus => 2, + Sign::Space => 3, + }); + let zero_pad = i64::from(spec.zero_pad); + // `try_from` is infallible after the bounds checks above; the expects + // document the invariant that keeps clippy's wrap-on-64-bit lint at bay. + let width = i64::try_from(spec.width).expect("width bounds-checked by MAX_ENCODED_WIDTH"); + // Store precision as `p + 1`, reserving 0 for the "no precision" marker. + let precision: i64 = spec.precision.map_or(0, |p| { + i64::try_from(p).expect("precision bounds-checked by MAX_ENCODED_PRECISION") + 1 + }); + let type_char: i64 = spec.type_char.map_or(0, |c| match c { + TypeChar::B => 1, + TypeChar::C => 2, + TypeChar::D => 3, + TypeChar::E => 4, + TypeChar::EUpper => 5, + TypeChar::F => 6, + TypeChar::FUpper => 7, + TypeChar::G => 8, + TypeChar::GUpper => 9, + TypeChar::N => 10, + TypeChar::O => 11, + TypeChar::S => 12, + TypeChar::X => 13, + TypeChar::XUpper => 14, + TypeChar::Percent => 15, + }); + let grouping: i64 = spec.grouping.map_or(0, |g| match g { + Grouping::Comma => 1, + Grouping::Underscore => 2, + }); + let alternate = i64::from(spec.alternate); + + // Every field occupies bits 0..63, so the sign bit is never set and the + // shifts/ORs stay within well-defined i64 territory. + Some( + fill | (align << 8) + | (sign << 11) + | (zero_pad << 13) + | (width << 14) + | (precision << 34) + | (type_char << 55) + | (grouping << 60) + | (alternate << 62), + ) +} + +/// Decodes an [`i64`] back into a [`ParsedFormatSpec`]. +/// +/// Reverses the bit-packing done by [`encode_format_spec`]. Used by the VM +/// when executing `FormatValue` with the `FORMAT_VALUE_STATIC_SPEC` flag to +/// recover the pre-parsed spec from the constant pool entry. +pub fn decode_format_spec(encoded: i64) -> ParsedFormatSpec { + // The valid encoding sits in bits 0..63 so `cast_unsigned` is a no-op + // reinterpret — the sign bit (bit 63) is always 0 here. + let encoded = encoded.cast_unsigned(); + let fill = (encoded & 0xFF) as u8 as char; + let align_bits = (encoded >> 8) & 0x07; + let sign_bits = (encoded >> 11) & 0x03; + let zero_pad = ((encoded >> 13) & 0x01) != 0; + let width = ((encoded >> 14) & 0xF_FFFF) as usize; + let precision_raw = ((encoded >> 34) & 0x1F_FFFF) as usize; + let type_bits = ((encoded >> 55) & 0x1F) as u8; + let grouping_bits = (encoded >> 60) & 0x03; + let alternate = ((encoded >> 62) & 0x01) != 0; + + let align = match align_bits { + 1 => Some(Align::Left), + 2 => Some(Align::Right), + 3 => Some(Align::Center), + 4 => Some(Align::SignAware), + _ => None, + }; + + let sign = match sign_bits { + 1 => Some(Sign::Plus), + 2 => Some(Sign::Minus), + 3 => Some(Sign::Space), + _ => None, + }; + + // Encoding stores `precision + 1`, so 0 means "no precision". + let precision = if precision_raw == 0 { + None + } else { + Some(precision_raw - 1) + }; + + let type_char = match type_bits { + 1 => Some(TypeChar::B), + 2 => Some(TypeChar::C), + 3 => Some(TypeChar::D), + 4 => Some(TypeChar::E), + 5 => Some(TypeChar::EUpper), + 6 => Some(TypeChar::F), + 7 => Some(TypeChar::FUpper), + 8 => Some(TypeChar::G), + 9 => Some(TypeChar::GUpper), + 10 => Some(TypeChar::N), + 11 => Some(TypeChar::O), + 12 => Some(TypeChar::S), + 13 => Some(TypeChar::X), + 14 => Some(TypeChar::XUpper), + 15 => Some(TypeChar::Percent), + _ => None, + }; + + let grouping = match grouping_bits { + 1 => Some(Grouping::Comma), + 2 => Some(Grouping::Underscore), + _ => None, + }; + + ParsedFormatSpec { + fill, + align, + sign, + alternate, + // Specs using the `z` flag are never encoded (see `encode_format_spec`), + // so a decoded spec never carries one. + z: false, + zero_pad, + width, + grouping, + // Specs with fractional grouping are never encoded (see + // `encode_format_spec`), so a decoded spec never carries one. + frac_grouping: None, + precision, + type_char, + } +} + +// ============================================================================ +// Formatting functions +// ============================================================================ + +/// Formats a string value according to a format specification. +/// +/// Applies the following transformations in order: +/// 1. Truncation: If `precision` is set, limits the string to that many characters +/// 2. Alignment: Pads to `width` using `fill` character (default left-aligned for strings) +/// +/// Returns an error if `=` alignment is used (sign-aware padding only valid for numbers). +pub fn format_string(value: &str, spec: &ParsedFormatSpec, tracker: &ResourceTracker) -> RunResult { + if spec.align == Some(Align::SignAware) { + return Err( + FormatError::InvalidAlignment("'=' alignment not allowed in string format specifier".to_owned()).into(), + ); + } + + let precision = spec.precision.unwrap_or(usize::MAX); + let mut end = value.len(); + let mut value_len = 0; + for (index, (byte_offset, _)) in value.char_indices().enumerate() { + tracker.check_time_every(index)?; + if value_len == precision { + end = byte_offset; + break; + } + value_len += 1; + } + let value = &value[..end]; + + let padding = spec.width.saturating_sub(value_len); + let align = spec.align.unwrap_or(Align::Left); + let left_padding = match align { + Align::Right => padding, + Align::Center => padding / 2, + Align::Left | Align::SignAware => 0, + }; + let right_padding = padding - left_padding; + let capacity = value.len().saturating_add(padding.saturating_mul(spec.fill.len_utf8())); + let mut output = format_builder(capacity, tracker)?; + for index in 0..left_padding { + tracker.check_time_every(index)?; + output.push(spec.fill)?; + } + push_format_str(&mut output, value, tracker)?; + for index in 0..right_padding { + tracker.check_time_every(left_padding + index)?; + output.push(spec.fill)?; + } + output.finish_raw() +} + +/// Formats an integer in decimal with a format specification. +/// +/// Applies the following: +/// - Sign prefix based on `sign` spec: `+` (always show), `-` (negatives only), ` ` (space for positive) +/// - Zero-padding: When `zero_pad` is true or `=` alignment, inserts zeros between sign and digits +/// - Alignment: Right-aligned by default for numbers, pads to `width` with `fill` character +pub fn format_int(n: i64, spec: &ParsedFormatSpec, tracker: &ResourceTracker) -> RunResult { + let is_negative = n < 0; + // Use unsigned_abs() to avoid overflow panic on i64::MIN + let abs_str = n.unsigned_abs().to_string(); + let sign = numeric_sign(is_negative, &abs_str, spec); + pad_signed_numeric(sign, "", &abs_str, spec, tracker) +} + +/// Formats an integer in binary (base 2), octal (base 8), or hexadecimal (base 16). +/// +/// Used for format types `b`, `o`, `x`, and `X`. The sign is prepended for +/// negative numbers. The alternate form (`#`) adds the `0b`/`0o`/`0x` base +/// prefix, which sits after the sign and counts toward the field width. +/// +/// `uppercase` (the `X` type) uppercases the digits **and** the `0x` prefix +/// (`0X`) — but *not* the fill/padding, so it must be applied to the digits +/// here rather than via `to_uppercase()` on the padded result (which would also +/// uppercase an alphabetic fill, e.g. `f"{180:a>8X}"` → `aaaaaaB4`). +/// Returns an error for invalid base values. +pub fn format_int_base( + n: i64, + base: u32, + uppercase: bool, + spec: &ParsedFormatSpec, + tracker: &ResourceTracker, +) -> RunResult { + let is_negative = n < 0; + let abs_val = n.unsigned_abs(); + + let (abs_str, base_prefix) = match (base, uppercase) { + (2, _) => (format!("{abs_val:b}"), "0b"), + (8, _) => (format!("{abs_val:o}"), "0o"), + (16, false) => (format!("{abs_val:x}"), "0x"), + (16, true) => (format!("{abs_val:X}"), "0X"), + _ => return Err(FormatError::ValueError("Invalid base".to_owned()).into()), + }; + let prefix = if spec.alternate { base_prefix } else { "" }; + + let sign = numeric_sign(is_negative, &abs_str, spec); + pad_signed_numeric(sign, prefix, &abs_str, spec, tracker) +} + +/// Formats a big integer through the numeric mini-language, +/// mirroring the `i64` paths ([`format_int`] / [`format_int_base`] / +/// `format_float_*`) but sourcing digits from the arbitrary-precision `BigInt`. +/// +/// Integer presentations (`d`/`b`/`o`/`x`/`X` and the default) convert the +/// magnitude to the requested radix and reuse [`pad_signed_numeric`] for sign, +/// grouping, prefix, and padding. Float presentations (`f`/`e`/`g`/`%`) convert +/// to `f64` first, raising `OverflowError` when the value is too large to +/// represent — exactly as CPython does. `c` overflows the code-point range +/// (a `LongInt` is always `> i64::MAX`) and `s` is an unknown code, matching +/// CPython's two distinct errors. `value_type` only feeds the `s` message and +/// is always `Type::Int` here. +/// +/// `tracker` guards the radix conversion: `BigInt::to_str_radix` materializes +/// the full digit string on the (untracked) Rust heap before `allocate_string` +/// runs, so a huge `LongInt` formatted as `:b`/`:o`/`:x` could allocate gigabytes +/// outside the resource limit (`f"{1 << n:b}"`). Each radix render is size-checked +/// up front against `tracker`. +fn format_long_int( + li: &BigInt, + value_type: &str, + spec: &ParsedFormatSpec, + tracker: &ResourceTracker, +) -> Result { + let sign = if li.is_negative() { + "-" + } else { + positive_sign_prefix(spec.sign) + }; + let magnitude = li.magnitude(); + // `uppercase` (the `X` type) uppercases the hex digits and the `0x` prefix + // (`0X`) but never the fill, so it's applied to the digits *before* padding. + let radix = |base: u32, base_prefix: &'static str, uppercase: bool| -> Result { + // Pre-check the digit-string size: a base-`b` render of an `n`-bit + // magnitude is at most `n / log2(b)` ASCII digits — `log2(b)` is + // `base.trailing_zeros()` for the power-of-two bases here; base 10 uses + // `1` (conservative) but is already bounded by `check_bits_str_digits_limit`. + let max_digits = li.bits() / u64::from(base.trailing_zeros().max(1)); + check_repeat_size( + 1, + usize::try_from(max_digits).unwrap_or(usize::MAX).saturating_add(2), + tracker, + )?; + let mut digits = magnitude.to_str_radix(base); + let prefix = if !spec.alternate { + "" + } else if uppercase { + // Only hex is ever uppercased, so `0x` → `0X`. + "0X" + } else { + base_prefix + }; + if uppercase { + digits.make_ascii_uppercase(); + } + pad_signed_numeric(sign, prefix, &digits, spec, tracker) + }; + let as_float = || match li.to_f64() { + Some(f) if f.is_finite() => Ok(f), + _ => Err(RunError::from(SimpleException::new_msg( + ExcType::OverflowError, + "int too large to convert to float".to_owned(), + ))), + }; + + match spec.type_char { + // `n` formats a big int as decimal (C locale, no grouping), like `d`. + None | Some(TypeChar::D | TypeChar::N) => { + // Only base-10 conversion is bounded by CPython's int_max_str_digits. + check_bits_str_digits_limit(li.bits())?; + radix(10, "", false) + } + Some(TypeChar::B) => radix(2, "0b", false), + Some(TypeChar::O) => radix(8, "0o", false), + Some(TypeChar::X) => radix(16, "0x", false), + Some(TypeChar::XUpper) => radix(16, "0x", true), + Some(TypeChar::F | TypeChar::FUpper) => format_float_f(as_float()?, spec, tracker), + Some(TypeChar::E) => format_float_e(as_float()?, spec, false, tracker), + Some(TypeChar::EUpper) => format_float_e(as_float()?, spec, true, tracker), + Some(TypeChar::G | TypeChar::GUpper) => format_float_g(as_float()?, spec, tracker), + Some(TypeChar::Percent) => format_float_percent(as_float()?, spec, tracker), + // A `LongInt` is always out of the C-long range `c` converts through. + Some(TypeChar::C) => Err(SimpleException::new_msg( + ExcType::OverflowError, + "Python int too large to convert to C long".to_owned(), + ) + .into()), + // `s` is not an integer presentation; surface CPython's "Unknown format + // code" wording (the `i64` path reaches the same message via its + // dispatch fall-through). + Some(TypeChar::S) => Err(SimpleException::new_msg( + ExcType::ValueError, + format!("Unknown format code 's' for object of type '{value_type}'"), + ) + .into()), + } +} + +/// Formats an integer as a Unicode character (format type `c`). +/// +/// Converts the integer to its corresponding Unicode code point. Valid range is 0 to 0x10FFFF. +/// Returns `Overflow` error if out of range, `ValueError` if not a valid Unicode scalar value +/// (e.g., surrogate code points). Right-aligned by default: `c` is an integer +/// presentation, so it follows the numeric default (`format(65, '5c')` → `' A'`). +pub fn format_char(n: i64, spec: &ParsedFormatSpec, tracker: &ResourceTracker) -> RunResult { + if !(0..=0x0010_FFFF).contains(&n) { + return Err(FormatError::Overflow("%c arg not in range(0x110000)".to_owned()).into()); + } + let n_u32 = u32::try_from(n).expect("format_char n validated in 0..=0x10FFFF range"); + let c = char::from_u32(n_u32).ok_or_else(|| FormatError::ValueError("Invalid Unicode code point".to_owned()))?; + let value = c.to_string(); + // `=` (SignAware) on `:c` is accepted by CPython but degenerates to right-align + // because there's no sign component to pad between. Map it now so `pad_string` + // (which treats SignAware as a no-op) does the right thing. + let align = match spec.align.unwrap_or(Align::Right) { + Align::SignAware => Align::Right, + other => other, + }; + pad_string(&value, spec.width, align, spec.fill, tracker) +} + +/// Formats a complex as CPython's `complex.__format__` does: each part goes +/// through the float formatters with width, fill and alignment stripped, the +/// imaginary part always carries a sign, and the assembled `re±imj` — wrapped in +/// parentheses for a type-less spec, like `str()` — is padded as one string. +/// +/// Every spec check, including [`check_complex_spec`], ran in `format_with_spec`. +fn format_complex(c: Complex, spec: &ParsedFormatSpec, tracker: &ResourceTracker) -> RunResult { + // A type-less spec renders like `str()`: repr digits, parentheses, and no + // real part at all when it is exactly `+0.0`. + let str_style = spec.type_char.is_none(); + let skip_real = str_style && c.real == 0.0 && c.real.is_sign_positive(); + let part_spec = |sign| ParsedFormatSpec { + fill: ' ', + align: None, + sign, + alternate: spec.alternate, + z: spec.z, + zero_pad: false, + width: 0, + grouping: spec.grouping, + frac_grouping: spec.frac_grouping, + precision: spec.precision, + type_char: spec.type_char, + }; + let real = if skip_real { + String::new() + } else { + format_complex_part(c.real, &part_spec(spec.sign), tracker)? + }; + // The imaginary part carries an explicit sign unless it stands alone, in + // which case the spec's own sign convention applies. + let imag_sign = if skip_real { spec.sign } else { Some(Sign::Plus) }; + let imag = format_complex_part(c.imag, &part_spec(imag_sign), tracker)?; + let body = if str_style && !skip_real { + format!("({real}{imag}j)") + } else { + format!("{real}{imag}j") + }; + pad_string( + &body, + spec.width, + spec.align.unwrap_or(Align::Right), + spec.fill, + tracker, + ) +} + +/// Zero padding and `=` alignment have no meaning for two numbers; CPython +/// rejects them before formatting either part. +fn check_complex_spec(spec: &ParsedFormatSpec) -> RunResult<()> { + if spec.zero_pad || spec.fill == '0' { + Err(ExcType::value_error( + "Zero padding is not allowed in complex format specifier", + )) + } else if spec.align == Some(Align::SignAware) { + Err(ExcType::value_error( + "'=' alignment flag is not allowed in complex format specifier", + )) + } else { + Ok(()) + } +} + +/// Formats one part of a complex. A type-less spec without precision uses the +/// repr digits with an integral value's `.0` dropped (`(1+2j)`, not +/// `(1.0+2.0j)`); with a precision it is `g`, never the `.0`-preserving +/// float default; the explicit float codes format as for a float. +fn format_complex_part(f: f64, spec: &ParsedFormatSpec, tracker: &ResourceTracker) -> RunResult { + match spec.type_char { + None if spec.precision.is_none() => { + let is_negative = f.is_sign_negative() && !f.is_nan(); + let abs_val = f.abs(); + let repr = FormatFloat(abs_val).to_string(); + let digits = repr.strip_suffix(".0").map_or_else(|| repr.clone(), str::to_owned); + let abs_str = maybe_alternate_point(digits, abs_val, spec); + let sign = numeric_sign(is_negative, &abs_str, spec); + pad_signed_numeric(sign, "", &abs_str, spec, tracker) + } + None => format_float_g( + f, + &ParsedFormatSpec { + type_char: Some(TypeChar::G), + ..*spec + }, + tracker, + ), + Some(TypeChar::G | TypeChar::GUpper | TypeChar::N) => format_float_g(f, spec, tracker), + Some(TypeChar::F | TypeChar::FUpper) => format_float_f(f, spec, tracker), + Some(TypeChar::E) => format_float_e(f, spec, false, tracker), + Some(TypeChar::EUpper) => format_float_e(f, spec, true, tracker), + // `format_with_spec` has already rejected every other code for a complex. + Some(other) => Err(ExcType::value_error(format!( + "Unknown format code '{}' for object of type 'complex'", + other.as_char() + ))), + } +} + +/// Formats a float in fixed-point notation (format types `f` and `F`). +/// +/// Always includes a decimal point with `precision` digits after it (default 6). +/// Handles sign prefix, zero-padding between sign and digits when `zero_pad` or `=` alignment. +/// Right-aligned by default. NaN and infinity are formatted as `nan`/`inf` (or `NAN`/`INF` for `F`). +pub fn format_float_f(f: f64, spec: &ParsedFormatSpec, tracker: &ResourceTracker) -> RunResult { + let is_negative = f.is_sign_negative() && !f.is_nan(); + let precision = spec.precision.unwrap_or(6); + let abs_val = f.abs(); + if let Some(digits) = short_float_digits(abs_val, precision, spec, |out| write!(out, "{abs_val:.precision$}")) { + let sign = numeric_sign(is_negative, digits.as_str(), spec); + return pad_signed_numeric(sign, "", digits.as_str(), spec, tracker); + } + let uppercase = spec.type_char == Some(TypeChar::FUpper); + let abs_str = if let Some(word) = non_finite_repr(f, uppercase) { + word.to_owned() + } else { + let abs_str = fmt_float_fixed(abs_val, precision, tracker)?; + maybe_alternate_point(abs_str, abs_val, spec) + }; + let sign = numeric_sign(is_negative, &abs_str, spec); + pad_signed_numeric(sign, "", &abs_str, spec, tracker) +} + +/// Formats a float in exponential/scientific notation (format types `e` and `E`). +/// +/// Produces output like `1.234568e+03` with `precision` digits after decimal (default 6). +/// The `uppercase` parameter controls whether to use `E` or `e` for the exponent marker. +/// Exponent is always formatted with a sign and at least 2 digits (Python convention). +pub fn format_float_e( + f: f64, + spec: &ParsedFormatSpec, + uppercase: bool, + tracker: &ResourceTracker, +) -> RunResult { + let is_negative = f.is_sign_negative() && !f.is_nan(); + let abs_str = if let Some(word) = non_finite_repr(f, uppercase) { + word.to_owned() + } else { + let abs_val = f.abs(); + let abs_str = fmt_float_exp(abs_val, spec.precision.unwrap_or(6), uppercase, tracker)?; + // Fix exponent format to match Python (e+03 not e3) + let abs_str = fix_exp_format(&abs_str, tracker)?; + maybe_alternate_point(abs_str, abs_val, spec) + }; + let sign = numeric_sign(is_negative, &abs_str, spec); + pad_signed_numeric(sign, "", &abs_str, spec, tracker) +} + +/// Formats a float in "general" format (format types `g` and `G`). +/// +/// Chooses between fixed-point and exponential notation based on the magnitude: +/// - Uses exponential if exponent < -4 or >= precision +/// - Otherwise uses fixed-point notation +/// +/// Unlike `f` and `e` formats, trailing zeros are stripped from the result. +/// Default precision is 6, but minimum is 1 significant digit. +pub fn format_float_g(f: f64, spec: &ParsedFormatSpec, tracker: &ResourceTracker) -> RunResult { + let is_negative = f.is_sign_negative() && !f.is_nan(); + // `G` (and only `G`) uppercases the exponent marker and `inf`/`nan`. + let uppercase = spec.type_char == Some(TypeChar::GUpper); + // Non-finite values short-circuit before the `log10`/exponent maths below, + // which would be meaningless for `inf`/`nan`. + if let Some(word) = non_finite_repr(f, uppercase) { + // `z` never coerces a non-finite value (`word` has no digits), so the + // sign is `"-"` for `-inf` as usual. + let sign = numeric_sign(is_negative, word, spec); + return pad_signed_numeric(sign, "", word, spec, tracker); + } + + let precision = spec.precision.unwrap_or(6).max(1); + let abs_val = f.abs(); + + // Python's g format uses exponential when the decimal exponent is `< -4` or + // `>= precision`. The exponent must be taken *after* rounding to `precision` + // significant figures: a value that rounds up across a power-of-ten + // boundary (`9.99` at 1 sig fig → `10`) gains an exponent and must switch to + // scientific (`f"{9.99:.1g}"` → `'1e+01'`, not `'10'`). Rust's `{:e}` rounds + // for us, so read the exponent back from the rounded scientific form rather + // than from `log10` of the unrounded value. + let exp = if abs_val == 0.0 { + 0 + } else { + let mantissa_digits = precision.saturating_sub(1).min(MAX_FMT_PRECISION_EXP); + let sci = format!("{abs_val:.mantissa_digits$e}"); + sci[sci.find('e').map_or(sci.len(), |i| i + 1)..] + .parse::() + .unwrap_or(0) + }; + + let exp_magnitude = usize::try_from(exp.unsigned_abs()).unwrap_or(usize::MAX); + // A type-less spec that reaches here carries a precision (the no-precision + // case goes through `format_float_default`). CPython's type-less-with- + // precision form is `g`-like but diverges in two ways: it switches to + // scientific one exponent *earlier* (`exp >= precision - 1`, vs `g`'s + // `>= precision`) and it appends `.0` when the result has no point/exponent + // (the `Py_DTSF_ADD_DOT_0` flag) — e.g. `f"{100.0:.3}"` is `'1e+02'` (not + // `g`'s `'100'`) and `f"{1.0:.2}"` is `'1.0'` (not `'1'`). + let is_default = spec.type_char.is_none(); + let sci_threshold = if is_default { + precision.saturating_sub(1) + } else { + precision + }; + // The alternate form (`#`) keeps the trailing zeros that `g` normally strips + // and forces a decimal point. This applies whenever the `g` algorithm runs + // — an explicit `g`/`G` *or* a type-less spec that carries a precision. + let alternate_g = spec.alternate; + let abs_str = if exp < -4 || (exp >= 0 && exp_magnitude >= sci_threshold) { + // Use exponential notation + let exp_prec = precision.saturating_sub(1); + if alternate_g { + // `#` preserves every mantissa zero, so the output scales with + // precision: let `fmt_float_exp` synthesise the digits beyond Rust's + // formatter cap, then normalise the exponent (`e+06`). Bounded by the + // precision pre-check in `format_with_spec`. + fix_exp_format(&fmt_float_exp(abs_val, exp_prec, uppercase, tracker)?, tracker)? + } else { + // Plain `g` strips trailing zeros, so mantissa digits beyond the cap + // would be dropped anyway — cap to avoid generating them. + strip_trailing_zeros_exp( + &fmt_float_exp(abs_val, exp_prec.min(MAX_FMT_PRECISION_EXP), uppercase, tracker)?, + tracker, + )? + } + } else { + let sig_digits = if exp < 0 { + precision.saturating_add(exp_magnitude).saturating_sub(1) + } else { + precision.saturating_sub(exp_magnitude.saturating_add(1)) + }; + if alternate_g { + // `#` keeps the trailing zeros, so the digit count scales with + // precision; `fmt_float_fixed` synthesises any beyond the formatter + // cap (bounded by the precision pre-check in `format_with_spec`). + fmt_float_fixed(abs_val, sig_digits, tracker)? + } else { + // Plain `g` strips trailing zeros, so digits beyond the cap would be + // dropped anyway — cap before formatting. + let cap = sig_digits.min(MAX_FMT_PRECISION); + strip_trailing_zeros(&format!("{abs_val:.cap$}")) + } + }; + let abs_str = if alternate_g { + maybe_alternate_point(abs_str, abs_val, spec) + } else { + abs_str + }; + // `Py_DTSF_ADD_DOT_0`: the type-less form always shows a decimal point, so + // a result with no `.`/`e` gets a trailing `.0` (`'1234'` → `'1234.0'`). + let abs_str = if is_default && !abs_str.contains(['.', 'e', 'E']) { + format!("{abs_str}.0") + } else { + abs_str + }; + + let sign = numeric_sign(is_negative, &abs_str, spec); + pad_signed_numeric(sign, "", &abs_str, spec, tracker) +} + +/// Formats a float with the *default* presentation — no type char and no +/// precision — applying sign, grouping, and field padding around the shortest +/// round-tripping digits ([`FormatFloat`]). +/// +/// CPython's type-less float format uses repr mode here, **not** `g` with the +/// default precision 6: `f"{1234567.0:>12}"` is `" 1234567.0"`, not +/// `" 1.23457e+06"`. A *precision* on a type-less float (`f"{x:.3}"`) does +/// select the `g` algorithm and so stays in [`format_float_g`]. +/// +/// Unlike the repr/str path this needs an owned `String` (the result is +/// post-processed by `maybe_alternate_point` and then padded), so it +/// materializes [`FormatFloat`] via `to_string` rather than streaming. +fn format_float_default(f: f64, spec: &ParsedFormatSpec, tracker: &ResourceTracker) -> RunResult { + let is_negative = f.is_sign_negative() && !f.is_nan(); + let abs_val = f.abs(); + // The alternate form (`#`) still forces a decimal point on the repr digits, + // even in scientific notation (`format(1e20, '#')` → `'1.e+20'`). + let abs_str = maybe_alternate_point(FormatFloat(abs_val).to_string(), abs_val, spec); + let sign = numeric_sign(is_negative, &abs_str, spec); + pad_signed_numeric(sign, "", &abs_str, spec, tracker) +} + +/// Applies ASCII conversion to a string (escapes non-ASCII characters). +/// +/// Used for the `!a` conversion flag in f-strings. Takes a string (typically a repr) +/// and escapes all non-ASCII characters using `\xNN`, `\uNNNN`, or `\UNNNNNNNN`. +pub fn ascii_escape(s: &str) -> String { + let mut result = String::new(); + for c in s.chars() { + if c.is_ascii() { + result.push(c); + } else { + let code = c as u32; + if code <= 0xFF { + write!(result, "\\x{code:02x}") + } else if code <= 0xFFFF { + write!(result, "\\u{code:04x}") + } else { + write!(result, "\\U{code:08x}") + } + .expect("string write should be infallible"); + } + } + result +} + +/// Formats a float as a percentage (format type `%`). +/// +/// Multiplies the value by 100 and appends a `%` sign. Uses fixed-point notation +/// with `precision` decimal places (default 6). For example, `0.1234` becomes `12.340000%`. +pub fn format_float_percent(f: f64, spec: &ParsedFormatSpec, tracker: &ResourceTracker) -> RunResult { + let percent_val = f * 100.0; + let is_negative = percent_val.is_sign_negative() && !percent_val.is_nan(); + let precision = spec.precision.unwrap_or(6); + let abs_val = percent_val.abs(); + if let Some(digits) = short_float_digits(abs_val, precision, spec, |out| write!(out, "{abs_val:.precision$}%")) { + let sign = numeric_sign(is_negative, digits.as_str(), spec); + return pad_signed_numeric(sign, "", digits.as_str(), spec, tracker); + } + // The `%` presentation has no uppercase variant, so `inf`/`nan` stay lower. + let abs_str = if let Some(word) = non_finite_repr(percent_val, false) { + format!("{word}%") + } else { + let digits = fmt_float_fixed(abs_val, precision, tracker)?; + // A builder rather than `push`: digits past `u16::MAX` precision fill their buffer exactly, + // so growing it in place would skip the soft memory check. + let mut output = format_builder(digits.len().saturating_add(1), tracker)?; + push_format_str(&mut output, &digits, tracker)?; + output.push('%')?; + let abs_str = output.finish_raw()?; + // `#` forces the point before the `%` (`#.0%` → `50.%`). + maybe_alternate_point(abs_str, abs_val, spec) + }; + let sign = numeric_sign(is_negative, &abs_str, spec); + pad_signed_numeric(sign, "", &abs_str, spec, tracker) +} + +// ============================================================================ +// Helper functions +// ============================================================================ + +/// CPython's spelling of a non-finite float for a given presentation *case*. +/// +/// Rust renders NaN as `"NaN"` (mixed case) and always lowercases infinity; +/// CPython instead uses `"nan"`/`"inf"` for the lowercase presentations +/// (`f`, `e`, `g`, `%`, and the default) and `"NAN"`/`"INF"` for the uppercase +/// ones (`F`, `E`, `G`). Returns `None` for a finite value so the caller falls +/// through to its normal digit formatting. The sign (for `-inf`) is applied by +/// the caller, so this returns the unsigned word only. +fn non_finite_repr(value: f64, uppercase: bool) -> Option<&'static str> { + if value.is_nan() { + Some(if uppercase { "NAN" } else { "nan" }) + } else if value.is_infinite() { + Some(if uppercase { "INF" } else { "inf" }) + } else { + None + } +} + +/// Renders the sign prefix that precedes a non-negative number's digits. +/// +/// Centralizes the `+`/space/empty decision that every numeric formatter +/// (`format_int`, `format_float_*`, etc.) needs when the value isn't +/// negative. Returns `""` for `None` and for `Some(Sign::Minus)` since both +/// mean "no leading mark on positives". +fn positive_sign_prefix(sign: Option) -> &'static str { + match sign { + Some(Sign::Plus) => "+", + Some(Sign::Space) => " ", + None | Some(Sign::Minus) => "", + } +} + +/// Computes the sign prefix for a formatted numeric magnitude, applying the `z` +/// flag's negative-zero coercion. +/// +/// The standard sign helper for every numeric formatter (`format_int`, +/// `format_int_base`, `format_float_*`). It is `"-"` for a negative value and +/// otherwise [`positive_sign_prefix`], *except* that the `z` flag +/// (`f"{-0.001:z.1f}"` → `0.0`) coerces a negative value that *rounds to zero at +/// the chosen precision* to positive zero. The rounding is already baked into +/// `abs_str`, so "rounds to zero" is detected structurally via +/// [`is_rounded_zero`]. `z` is only ever set for float presentations (it is +/// rejected for integer/string ones in `format_with_spec`), so the integer +/// callers get the plain sign behaviour. +fn numeric_sign(is_negative: bool, abs_str: &str, spec: &ParsedFormatSpec) -> &'static str { + if is_negative && !(spec.z && is_rounded_zero(abs_str)) { + "-" + } else { + positive_sign_prefix(spec.sign) + } +} + +/// Whether a formatted magnitude string represents zero — it has at least one +/// digit and every digit is `0` (e.g. `"0.00"`, `"0.000000e+00"`, `"0%"`). +/// +/// Requiring a digit excludes `inf`/`nan` (which carry none), so the `z` flag +/// never coerces the sign of a non-finite value. +fn is_rounded_zero(abs_str: &str) -> bool { + let mut saw_digit = false; + for b in abs_str.bytes() { + if b.is_ascii_digit() { + saw_digit = true; + if b != b'0' { + return false; + } + } + } + saw_digit +} + +/// Applies the alternate form's (`#`) "always show a decimal point" rule to a +/// finite float string, returning it unchanged when `#` is absent. +/// +/// The point is inserted before the exponent (`e`/`E`) or percent (`%`) marker, +/// or at the end for plain fixed-point — so `#.0f` of 1.0 → `1.`, `#.0e` → +/// `1.e+00`, `#.0%` of 0.5 → `50.%`. A no-op when a `.` is already present (any +/// non-zero precision) and skipped for non-finite values (`inf`/`nan` have no +/// point). +fn maybe_alternate_point(abs_str: String, abs_val: f64, spec: &ParsedFormatSpec) -> String { + if !spec.alternate || !abs_val.is_finite() { + return abs_str; + } + let marker = abs_str.find(['e', 'E', '%']).unwrap_or(abs_str.len()); + if abs_str[..marker].contains('.') { + abs_str + } else { + format!("{}.{}", &abs_str[..marker], &abs_str[marker..]) + } +} + +/// Pads `sign + prefix + abs_str` to `spec.width` with the right alignment +/// semantics for a signed numeric value. +/// +/// `prefix` is the alternate-form base marker (`0x`/`0o`/`0b`) or `""`. It +/// sits immediately after the sign and before any internal padding, and counts +/// toward the field width — `format(255, '#06x')` → `0x00ff`. +/// +/// Numeric formatters all share three padding modes: +/// - `zero_pad` (`0` flag): insert `'0'` between the prefix and the digits. +/// - `Align::SignAware` (`=`): insert `spec.fill` between the prefix and the +/// digits. +/// - Anything else: glue `sign` + `prefix` + `abs_str` together and let +/// [`pad_string`] place fill outside the value. +/// +/// Without this helper each formatter that wants sign-aware behaviour had +/// to inline the same conditional, and the ones that *didn't* (the +/// non-decimal integer bases, all the float formats except `:f`) silently +/// dropped width for `=` — see `parse_errors.rs::format_spec_…` tests. +/// Default alignment is right because all callers are numeric formats; +/// `format_char` (default left, no sign) needs separate handling. +/// +/// When `spec.grouping` is set the thousands separator is woven through the +/// integer digits before padding — see [`pad_signed_grouped`]. When +/// `spec.frac_grouping` is set, the fractional digits are grouped first (a +/// no-op for values with no fractional part, e.g. integers). +fn pad_signed_numeric( + sign: &str, + prefix: &str, + abs_str: &str, + spec: &ParsedFormatSpec, + tracker: &ResourceTracker, +) -> RunResult { + // Fractional grouping is applied up front so the integer-grouping/padding + // below treats the grouped fraction as an opaque suffix. + let frac_grouped; + let abs_str = if let Some(g) = spec.frac_grouping { + frac_grouped = insert_frac_grouping(abs_str, g.separator(), tracker)?; + frac_grouped.as_str() + } else { + abs_str + }; + let align = spec.align.unwrap_or(Align::Right); + match spec.grouping { + None => pad_signed_ungrouped(sign, prefix, abs_str, align, spec, tracker), + Some(grouping) => pad_signed_grouped(sign, prefix, abs_str, align, grouping, spec, tracker), + } +} + +/// Inserts `sep` into the fractional digit run every three digits *from the +/// left*, implementing Python 3.14's `[.precision][grouping]` fractional +/// grouping (`f"{x:.6_f}"` → `…123_457`). +/// +/// The fractional run is the maximal `[0-9]*` immediately after the first `.`; +/// the integer part and any exponent/`%` suffix are left untouched. A no-op +/// when the string has no fractional part (e.g. an integer), so it is safe to +/// call unconditionally from [`pad_signed_numeric`]. Output size is bounded by +/// the (already tracked) input length plus one separator per three digits. +fn insert_frac_grouping(s: &str, sep: char, tracker: &ResourceTracker) -> RunResult { + let (after, frac_len) = if let Some(dot) = s.find('.') { + let after = dot + 1; + let frac_len = s[after..] + .find(|c: char| !c.is_ascii_digit()) + .unwrap_or(s.len() - after); + (after, frac_len) + } else { + (s.len(), 0) + }; + let separators = frac_len.saturating_sub(1) / 3; + let mut out = format_builder(s.len().saturating_add(separators), tracker)?; + push_format_str(&mut out, &s[..after], tracker)?; + for (i, c) in s[after..after + frac_len].chars().enumerate() { + tracker.check_time_every(i)?; + if i > 0 && i.is_multiple_of(3) { + out.push(sep)?; + } + out.push(c)?; + } + push_format_str(&mut out, &s[after + frac_len..], tracker)?; + out.finish_raw() +} + +/// Padding for a signed numeric with no thousands grouping (the common case). +/// +/// Handles the three modes documented on [`pad_signed_numeric`]: `0`-flag +/// zero-padding, `=` sign-aware fill, and ordinary outside padding. `prefix` +/// (the `#` base marker or `""`) is emitted right after the sign in every mode. +fn pad_signed_ungrouped( + sign: &str, + prefix: &str, + abs_str: &str, + align: Align, + spec: &ParsedFormatSpec, + tracker: &ResourceTracker, +) -> RunResult { + pad_signed_parts(sign, prefix, abs_str, "", align, spec, tracker) +} + +/// Padding for a signed numeric with a thousands separator (`,` or `_`). +/// +/// The separator only ever lands between *integer* digits, so `abs_str` is +/// first split into its leading digit run and any trailing part (fraction, +/// exponent, `%`). Binary/octal/hex presentations group in fours and never +/// carry a suffix; decimal/float presentations group in threes. `prefix` (the +/// `#` base marker or `""`) sits after the sign and is never grouped. Zero fill +/// (the `0` flag or an explicit `0=`) is special: its leading zeros become part +/// of the number and are themselves grouped to fill the field width +/// (`format(1234, '08,')` → `'0,001,234'`), whereas any other `=` fill and +/// outside padding wrap an already-grouped value. +fn pad_signed_grouped( + sign: &str, + prefix: &str, + abs_str: &str, + align: Align, + grouping: Grouping, + spec: &ParsedFormatSpec, + tracker: &ResourceTracker, +) -> RunResult { + let sep = grouping.separator(); + let is_base = matches!( + spec.type_char, + Some(TypeChar::B | TypeChar::O | TypeChar::X | TypeChar::XUpper) + ); + let group_size = if is_base { 4 } else { 3 }; + let (int_digits, suffix) = if is_base { + (abs_str, "") + } else { + // Decimal digits are 0-9 only, so the first non-digit marks the start + // of the fraction/exponent/`%` suffix. + let end = abs_str.find(|c: char| !c.is_ascii_digit()).unwrap_or(abs_str.len()); + abs_str.split_at(end) + }; + + // Non-finite values (`inf`/`nan`/`INF`/`NAN`) have no integer digits, so + // there is nothing to group: CPython drops the separator entirely and + // zero-pads the bare word ungrouped (`format(inf, '020,') == '…00inf'`, + // no commas). Delegating here also avoids `insert_grouping` underflowing + // on an empty digit string. + if int_digits.is_empty() { + return pad_signed_ungrouped(sign, prefix, abs_str, align, spec, tracker); + } + + // CPython grows the digits, not the fill, for the `0` flag and an explicit `0=` alike. + let grouped_zero_fill = spec.zero_pad || (spec.fill == '0' && spec.align == Some(Align::SignAware)); + let min_int_width = if grouped_zero_fill { + // Grow the integer part with grouped leading zeros until the whole + // field (sign + prefix + grouped digits + suffix) reaches the width. + let reserved = sign.len() + prefix.len() + suffix.len(); + spec.width.saturating_sub(reserved) + } else { + 0 + }; + let grouped = insert_grouping(int_digits, group_size, sep, min_int_width, tracker)?; + pad_signed_parts(sign, prefix, &grouped, suffix, align, spec, tracker) +} + +/// Builds a signed value and its padding into one tracked buffer. +fn pad_signed_parts( + sign: &str, + prefix: &str, + body: &str, + suffix: &str, + align: Align, + spec: &ParsedFormatSpec, + tracker: &ResourceTracker, +) -> RunResult { + tracker.check_time()?; + let value_len = sign.len() + prefix.len() + body.len() + suffix.len(); + let padding = spec.width.saturating_sub(value_len); + let fill = if spec.zero_pad { '0' } else { spec.fill }; + let capacity = sign + .len() + .saturating_add(prefix.len()) + .saturating_add(body.len()) + .saturating_add(suffix.len()) + .saturating_add(padding.saturating_mul(fill.len_utf8())); + let mut output = format_builder(capacity, tracker)?; + + if spec.zero_pad || align == Align::SignAware { + output.push_str(sign)?; + output.push_str(prefix)?; + push_padding(&mut output, fill, padding, tracker)?; + push_format_str(&mut output, body, tracker)?; + push_format_str(&mut output, suffix, tracker)?; + } else { + let left = match align { + Align::Left => 0, + Align::Right => padding, + Align::Center => padding / 2, + Align::SignAware => unreachable!(), + }; + push_padding(&mut output, fill, left, tracker)?; + output.push_str(sign)?; + output.push_str(prefix)?; + push_format_str(&mut output, body, tracker)?; + push_format_str(&mut output, suffix, tracker)?; + push_padding(&mut output, fill, padding - left, tracker)?; + } + output.finish_raw() +} + +/// Appends repeated fill while polling long writes for time limits. +fn push_padding(output: &mut StringBuilder<'_>, fill: char, count: usize, tracker: &ResourceTracker) -> RunResult<()> { + for i in 0..count { + tracker.check_time_every(i)?; + output.push(fill)?; + } + Ok(()) +} + +/// Defers large timed allocations so emission can poll before reserving the full result. +fn format_builder(capacity: usize, tracker: &ResourceTracker) -> RunResult> { + if capacity > LARGE_RESULT_THRESHOLD && tracker.has_time_limit() { + Ok(StringBuilder::new(tracker)) + } else { + Ok(StringBuilder::with_capacity(capacity, tracker)?) + } +} + +/// Copies large timed fragments incrementally so the deadline is polled during the copy. +fn push_format_str(output: &mut StringBuilder<'_>, value: &str, tracker: &ResourceTracker) -> RunResult<()> { + if value.len() <= LARGE_RESULT_THRESHOLD || !tracker.has_time_limit() { + output.push_str(value)?; + } else { + for (i, c) in value.chars().enumerate() { + tracker.check_time_every(i)?; + output.push(c)?; + } + } + Ok(()) +} + +/// Inserts `sep` between every `group_size` digits of `digits`, counting from +/// the right, optionally left-padding with `'0'` first so the grouped result +/// is at least `min_width` characters wide. +/// +/// `min_width` drives the zero-fill interaction: CPython grows the zero-padded +/// integer one digit at a time until digits-plus-separators reach the field +/// width, so the result can overshoot `min_width` by one when the final digit +/// also introduces a separator (`format(1234, '08,')` → `'0,001,234'`, 9 +/// wide for a width of 8). Callers must pass a non-empty `digits` (numeric +/// formatters always emit at least one digit, and [`pad_signed_grouped`] +/// routes non-finite values away before reaching here); the arithmetic is +/// nonetheless hardened against an empty string so it can never panic. +fn insert_grouping( + digits: &str, + group_size: usize, + sep: char, + min_width: usize, + tracker: &ResourceTracker, +) -> RunResult { + tracker.check_time()?; + // `digits` are ASCII (decimal or hex), so byte length == char count. + let ndigits = digits.len(); + let total = grouped_digit_count(ndigits, group_size, min_width); + let zeros = total - ndigits; + + let capacity = total.saturating_add(total.saturating_sub(1) / group_size); + let mut out = format_builder(capacity, tracker)?; + let mut digit_chars = digits.chars(); + for i in 0..total { + tracker.check_time_every(i)?; + if i > 0 && (total - i).is_multiple_of(group_size) { + out.push(sep)?; + } + // The first `zeros` positions are synthesised leading zeros; the rest + // consume the original digit string left-to-right. + out.push(if i < zeros { + '0' + } else { + digit_chars.next().expect("digit_chars yields exactly ndigits items") + })?; + } + out.finish_raw() +} + +/// Returns the smallest count at least `ndigits` whose grouped width reaches `min_width`. +fn grouped_digit_count(ndigits: usize, group_size: usize, min_width: usize) -> usize { + let required = min_width.saturating_sub(min_width.saturating_sub(1) / (group_size + 1)); + ndigits.max(required) +} + +/// Consumes a run of Unicode decimal digits and folds them into a [`usize`]. +/// +/// Returns `Ok(None)` when no digit is present, `Ok(Some(n))` for a parsed +/// number, and `Err(())` if accumulating would overflow [`usize`]. Used for +/// the width and precision fields of the format mini-language — both are +/// decimal integers terminated by the next non-digit. +/// +/// Folding digits inline avoids the intermediate `String` that +/// `.parse::()` would need, and surfaces overflow so the caller +/// can bail with a parse error rather than silently clamping to 0. +fn consume_decimal_usize(chars: &mut Peekable>) -> Result, ()> { + let mut value: Option = None; + while let Some((_, digit)) = chars.next_if_map(|c| decimal_digit_value(c).map_or_else(|| Err(c), |d| Ok((c, d)))) { + let next = value + .unwrap_or(0) + .checked_mul(10) + .and_then(|n| n.checked_add(digit as usize)) + .ok_or(())?; + value = Some(next); + } + Ok(value) +} + +/// Returns the numeric value of a Unicode decimal digit. +pub(crate) fn decimal_digit_value(character: char) -> Option { + if get_general_category(character) != GeneralCategory::DecimalNumber { + return None; + } + + let code_point = character as u32; + let mut run_start = code_point; + while let Some(previous) = run_start.checked_sub(1).and_then(char::from_u32) { + if get_general_category(previous) != GeneralCategory::DecimalNumber { + break; + } + run_start -= 1; + } + Some((code_point - run_start) % 10) +} + +/// Maximum precision Rust's `format!` accepts for fixed-point float formatting +/// before it panics with "Formatting argument out of range" (i.e. `u16::MAX`). +/// +/// Python allows arbitrary precision in f-strings (e.g. `.{10**6}f`), so +/// we cap at this limit and pad manually with zeros beyond it. +const MAX_FMT_PRECISION: usize = u16::MAX as usize; + +/// Maximum precision Rust's `format!` accepts for exponential (`e`/`E`) float +/// formatting. One less than `MAX_FMT_PRECISION` because Rust's internal +/// `to_exact_exp_str` uses `ndigits = precision + 1`, which would overflow +/// `u16::MAX` and hit an `ndigits > 0` assertion at exactly `u16::MAX`. +const MAX_FMT_PRECISION_EXP: usize = (u16::MAX as usize) - 1; + +/// Formats a float in fixed-point notation at an arbitrary precision. +/// +/// Rust's `format!` panics if precision exceeds `u16::MAX`. For non-finite +/// values (NaN/inf) precision is ignored entirely, matching Rust's behavior. +/// For finite values beyond the native limit we format at `MAX_FMT_PRECISION` +/// and append trailing zeros — f64 precision bottoms out long before this, so +/// every additional digit Python would emit is a zero anyway. +fn fmt_float_fixed(abs_val: f64, precision: usize, tracker: &ResourceTracker) -> RunResult { + if precision <= MAX_FMT_PRECISION || !abs_val.is_finite() { + let int_digits = if abs_val >= 1.0 && abs_val.is_finite() { + #[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "`log10` of a finite value >= 1 is in 0..309" + )] + let digits = abs_val.log10() as usize; + digits + 1 + } else { + 1 + }; + return Ok(write_float( + abs_val, + int_digits, + precision, + format_args!("{abs_val:.precision$}"), + )); + } + let base = format!("{abs_val:.MAX_FMT_PRECISION$}"); + let extra = precision - MAX_FMT_PRECISION; + let mut output = format_builder(base.len().saturating_add(extra), tracker)?; + output.push_str(&base)?; + for i in 0..extra { + tracker.check_time_every(i)?; + output.push('0')?; + } + output.finish_raw() +} + +/// Formats a float in exponential notation at an arbitrary precision. +/// +/// Same precision-capping strategy as `fmt_float_fixed`, but trailing zeros +/// are injected into the mantissa (before the exponent marker) rather than +/// appended to the end. +fn fmt_float_exp(abs_val: f64, precision: usize, uppercase: bool, tracker: &ResourceTracker) -> RunResult { + if precision <= MAX_FMT_PRECISION_EXP || !abs_val.is_finite() { + return Ok(if uppercase { + write_float(abs_val, 1, precision, format_args!("{abs_val:.precision$E}")) + } else { + write_float(abs_val, 1, precision, format_args!("{abs_val:.precision$e}")) + }); + } + let base = if uppercase { + format!("{abs_val:.MAX_FMT_PRECISION_EXP$E}") + } else { + format!("{abs_val:.MAX_FMT_PRECISION_EXP$e}") + }; + let extra = precision - MAX_FMT_PRECISION_EXP; + // Inject padding zeros immediately before the exponent marker. + if let Some(e_pos) = base.find(['e', 'E']) { + let (mantissa, exp_part) = base.split_at(e_pos); + let mut output = format_builder(base.len().saturating_add(extra), tracker)?; + output.push_str(mantissa)?; + for i in 0..extra { + tracker.check_time_every(i)?; + output.push('0')?; + } + output.push_str(exp_part)?; + output.finish_raw() + } else { + Ok(base) + } +} + +/// Formats a finite float's digits on the stack when they are short and need no `#` point. +/// +/// This skips a heap allocation per float in the common case; `None` sends the caller to +/// its general path, which handles non-finite values, `#` and long results. `write` runs only +/// once `precision` is known to be small, since `fmt` panics on one above `u16::MAX`. +fn short_float_digits( + abs_val: f64, + precision: usize, + spec: &ParsedFormatSpec, + write: impl FnOnce(&mut StackDigits) -> fmt::Result, +) -> Option { + if abs_val.is_finite() && !spec.alternate && precision < StackDigits::CAPACITY { + let mut digits = StackDigits::new(); + write(&mut digits).ok().map(|()| digits) + } else { + None + } +} + +/// A fixed-size stack buffer for a short formatted number; writes past its capacity fail. +struct StackDigits { + buf: [u8; Self::CAPACITY], + len: usize, +} + +impl StackDigits { + /// Bytes held; a longer result makes the write fail and the caller fall back to a `String`. + const CAPACITY: usize = 64; + + fn new() -> Self { + Self { + buf: [0; Self::CAPACITY], + len: 0, + } + } + + fn as_str(&self) -> &str { + str::from_utf8(&self.buf[..self.len]).expect("only whole `str` fragments are written") + } +} + +impl Write for StackDigits { + fn write_str(&mut self, s: &str) -> fmt::Result { + let end = self.len + s.len(); + self.buf + .get_mut(self.len..end) + .ok_or(fmt::Error)? + .copy_from_slice(s.as_bytes()); + self.len = end; + Ok(()) + } +} + +/// Room [`write_float`] reserves beyond the digits: the point, an exponent like `e+308`, +/// a rounding carry and an estimate of the integer digits that is off by one. +const FLOAT_DIGITS_SLACK: usize = 9; + +/// Writes formatted float `args` into a buffer sized for `int_digits` before the point and +/// `precision` after it. +/// +/// `format!` sizes its buffer from the literal text, which is empty for a bare float, so its +/// buffer would grow through several reallocations. The sizes only apply to finite values: +/// non-finite ones ignore precision, which may be huge. +fn write_float(abs_val: f64, int_digits: usize, precision: usize, args: fmt::Arguments<'_>) -> String { + let capacity = if abs_val.is_finite() { + int_digits.saturating_add(precision).saturating_add(FLOAT_DIGITS_SLACK) + } else { + 3 + }; + let mut output = String::with_capacity(capacity); + output.write_fmt(args).expect("writing to a String cannot fail"); + output +} + +/// Pads a string to a given width with alignment. +/// +/// `Align::SignAware` must not reach this function — numeric formatters +/// handle `=` via [`pad_signed_numeric`] (which inserts fill between sign +/// and digits before any call to `pad_string`), and [`format_char`] maps +/// `=` to right-align since chars have no sign. Routing a SignAware value +/// here would silently drop width, which `debug_assert!` catches in test +/// builds; release builds degrade to no-op padding as a safety net. +fn pad_string(value: &str, width: usize, align: Align, fill: char, tracker: &ResourceTracker) -> RunResult { + debug_assert!( + align != Align::SignAware, + "pad_string received Align::SignAware; callers must handle `=` themselves \ + (numeric formatters via pad_signed_numeric, format_char by mapping to Right)" + ); + let value_len = value.chars().count(); + let padding = width.saturating_sub(value_len); + let (left, right) = match align { + Align::Left => (0, padding), + Align::Right => (padding, 0), + Align::Center => (padding / 2, padding - padding / 2), + Align::SignAware => (0, 0), + }; + tracker.check_time()?; + let capacity = value.len().saturating_add(padding.saturating_mul(fill.len_utf8())); + let mut output = format_builder(capacity, tracker)?; + push_padding(&mut output, fill, left, tracker)?; + output.push_str(value)?; + push_padding(&mut output, fill, right, tracker)?; + output.finish_raw() +} + +/// Strips trailing zeros from a decimal float string. +/// +/// Used by the `:g` format to remove insignificant trailing zeros. +/// Also removes the decimal point if all fractional digits are stripped. +/// Has no effect if the string doesn't contain a decimal point. +fn strip_trailing_zeros(s: &str) -> String { + if !s.contains('.') { + return s.to_owned(); + } + let trimmed = s.trim_end_matches('0'); + if let Some(stripped) = trimmed.strip_suffix('.') { + stripped.to_owned() + } else { + trimmed.to_owned() + } +} + +/// Strips trailing zeros from a float in exponential notation. +/// +/// Splits the string at `e` or `E`, strips zeros from the mantissa part, +/// then recombines with the exponent. Also normalizes the exponent format +/// to Python's convention (sign and at least 2 digits). +fn strip_trailing_zeros_exp(s: &str, tracker: &ResourceTracker) -> RunResult { + if let Some(e_pos) = s.find(['e', 'E']) { + let (mantissa, exp_part) = s.split_at(e_pos); + let trimmed_mantissa = strip_trailing_zeros(mantissa); + let fixed_exp = fix_exp_format(exp_part, tracker)?; + let mut output = format_builder(trimmed_mantissa.len().saturating_add(fixed_exp.len()), tracker)?; + output.push_str(&trimmed_mantissa)?; + output.push_str(&fixed_exp)?; + output.finish_raw() + } else { + Ok(strip_trailing_zeros(s)) + } +} + +/// Converts Rust's exponential format to Python's format. +/// +/// Rust produces "e3" or "e-3" but Python expects "e+03" or "e-03". +/// This function ensures the exponent has: +/// 1. A sign character ('+' or '-') +/// 2. At least 2 digits +fn fix_exp_format(s: &str, tracker: &ResourceTracker) -> RunResult { + // Find the 'e' or 'E' marker + let Some(e_pos) = s.find(['e', 'E']) else { + let mut output = format_builder(s.len(), tracker)?; + push_format_str(&mut output, s, tracker)?; + return output.finish_raw(); + }; + + let (before_e, e_and_rest) = s.split_at(e_pos); + let e_char = e_and_rest.chars().next().unwrap(); + let exp_part = &e_and_rest[1..]; + + // Parse the exponent sign and value + let (sign, digits) = if let Some(stripped) = exp_part.strip_prefix('-') { + ('-', stripped) + } else if let Some(stripped) = exp_part.strip_prefix('+') { + ('+', stripped) + } else { + ('+', exp_part) + }; + + // Ensure at least 2 digits + let padding = 2usize.saturating_sub(digits.len()); + let capacity = before_e + .len() + .saturating_add(e_char.len_utf8()) + .saturating_add(sign.len_utf8()) + .saturating_add(padding) + .saturating_add(digits.len()); + let mut output = format_builder(capacity, tracker)?; + push_format_str(&mut output, before_e, tracker)?; + output.push(e_char)?; + output.push(sign)?; + for _ in 0..padding { + output.push('0')?; + } + output.push_str(digits)?; + output.finish_raw() +} diff --git a/crates/bashkit-monty/src/function.rs b/crates/bashkit-monty/src/function.rs new file mode 100644 index 000000000..13dcec560 --- /dev/null +++ b/crates/bashkit-monty/src/function.rs @@ -0,0 +1,173 @@ +use std::{ + cell::OnceCell, + fmt::{self, Write}, +}; + +use crate::{args::Signature, bytecode::Code, expressions::Identifier, intern::Interns, namespace::NamespaceId}; + +/// How an exact positional call can bypass argument binding. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ExactPositionalCall { + /// Arguments can remain on the VM stack as synchronous frame locals. + Sync(usize), + /// Arguments can move directly from the VM stack into a coroutine namespace. + Async(usize), +} + +/// A defined function once compiled and ready for execution. +/// +/// Contains compiled code, parameter metadata and closure layout. +/// Committed functions have stable addresses in `Interns` and are referenced by `FunctionId`. +/// +/// # Namespace Layout +/// +/// Parameters occupy slots `0..signature.param_count()` (see `Signature`). +/// Cell variables, captured free variables, and ordinary locals follow, but +/// their slots are **explicit** (carried in `cell_var_slots` / `free_var_slots`) +/// rather than positional: a transitively captured (pass-through) free variable +/// is discovered late during preparation and is assigned a slot in the locals +/// region, so the old contiguous `[params][cells][free][locals]` invariant no +/// longer holds. Each cell/free slot is therefore placed individually at frame +/// setup (see `install_closure_cells`). +/// +/// # Closure Support +/// +/// - `free_var_enclosing_slots[i]`: legacy compiler record of the enclosing +/// slot for captured cell `i`; runtime closure creation uses bytecode. +/// - `free_var_slots[i]`: slot in *this* frame where that captured cell is +/// installed at call time (parallel to `free_var_enclosing_slots`). +/// - `cell_var_slots[i]`: slot in this frame for an owned cell (a local captured +/// by a nested function); a fresh cell is created there at call time. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) struct Function { + /// The function name (used for error messages and repr). + #[serde(rename = "N")] + pub name: Identifier, + /// The function signature. + #[serde(rename = "S")] + pub signature: Signature, + /// Size of the initial namespace (number of local variable slots). + #[serde(rename = "Z")] + pub namespace_size: usize, + /// Legacy compiler record of enclosing slots; closure creation uses bytecode. + #[serde(rename = "E")] + pub free_var_enclosing_slots: Vec, + /// This frame's slots that receive the captured free-var cells, parallel to + /// [`Self::free_var_enclosing_slots`]. Explicit (not positional) so + /// late-allocated pass-through slots land correctly. + #[serde(rename = "F")] + pub free_var_slots: Vec, + /// This frame's slots for owned cell variables (locals captured by nested + /// functions); a fresh cell is created for each at call time. Parallel to + /// [`Self::cell_param_indices`]. + #[serde(rename = "C")] + pub cell_var_slots: Vec, + /// Maps each cell variable (parallel to [`Self::cell_var_slots`]) to its + /// parameter index when the cell is for a captured parameter, so the bound + /// value can be copied in; `None` means the cell starts `Undefined`. + #[serde(rename = "P")] + pub cell_param_indices: Vec>, + /// Number of default parameter values. + /// + /// At function definition time, this many default values are evaluated and stored + /// in a separate defaults array. The signature indicates how these map to parameters. + #[serde(rename = "D")] + pub defaults_count: usize, + /// Whether this is an async function (`async def`). + /// + /// When true, calling this function creates a `Coroutine` object instead of + /// immediately pushing a frame. The coroutine captures the bound arguments + /// and starts execution only when awaited. + #[serde(rename = "A")] + pub is_async: bool, + /// Cached binder-free call plan, derived from the fields above and cached + /// via [`Self::exact_positional_call`]. + /// + /// Never serialized: a function loaded from a REPL dump starts with this + /// empty and derives it fresh on first call, so staleness with respect to + /// an older binary's derivation logic is structurally impossible rather + /// than merely checked. + #[serde(skip)] + exact_positional_call: OnceCell>, + /// Compiled body borrowed by active frames, which track body-relative instruction offsets. + #[serde(rename = "B")] + pub code: Code, +} + +impl Function { + /// Create a new compiled function. + /// + /// This is typically called by the bytecode compiler after compiling a `PreparedFunctionDef`. + /// + /// # Arguments + /// * `name` - The function name identifier + /// * `signature` - The function signature with parameter names and defaults + /// * `namespace_size` - Number of local variable slots needed + /// * `free_var_enclosing_slots` - Enclosing-frame slots for captured cells + /// * `free_var_slots` - This frame's slots receiving the captured cells + /// * `cell_var_slots` - This frame's slots for owned cells + /// * `cell_param_indices` - Maps each owned cell to a parameter index, if any + /// * `defaults_count` - Number of default parameter values + /// * `is_async` - Whether this is an async function + /// * `code` - The compiled bytecode for the function body + #[expect(clippy::too_many_arguments)] + pub fn new( + name: Identifier, + signature: Signature, + namespace_size: usize, + free_var_enclosing_slots: Vec, + free_var_slots: Vec, + cell_var_slots: Vec, + cell_param_indices: Vec>, + defaults_count: usize, + is_async: bool, + code: Code, + ) -> Self { + Self { + name, + signature, + namespace_size, + free_var_enclosing_slots, + free_var_slots, + cell_var_slots, + cell_param_indices, + defaults_count, + is_async, + exact_positional_call: OnceCell::new(), + code, + } + } + + /// Returns the binder-free call plan for this function, deriving and + /// caching it on first use. + pub(crate) fn exact_positional_call(&self) -> Option { + *self + .exact_positional_call + .get_or_init(|| self.derive_exact_positional_call()) + } + + /// Derives the binder-free call plan from authoritative function metadata. + fn derive_exact_positional_call(&self) -> Option { + if self.cell_var_slots.is_empty() && self.free_var_slots.is_empty() { + self.signature.exact_positional_count().map(|count| { + if self.is_async { + ExactPositionalCall::Async(count) + } else { + ExactPositionalCall::Sync(count) + } + }) + } else { + None + } + } + + /// Writes the Python repr() string for this function to a formatter. + pub fn py_repr_fmt(&self, f: &mut W, interns: &Interns, py_id: impl fmt::LowerHex) -> fmt::Result { + write!( + f, + "", + interns.get_str(self.name.name_id), + py_id + ) + } +} diff --git a/crates/bashkit-monty/src/hash.rs b/crates/bashkit-monty/src/hash.rs new file mode 100644 index 000000000..6d2936eef --- /dev/null +++ b/crates/bashkit-monty/src/hash.rs @@ -0,0 +1,388 @@ +//! Single source of truth for hashing Python values. +//! +//! Defines: +//! +//! * [`HashValue`] — a verified Python hash. Construction goes through +//! [`HashValue::from_raw`]; storing or comparing hashes anywhere in the +//! runtime should use this type rather than a bare `u64` so the invariant +//! is enforced by the type system. +//! +//! Internally backed by a [`NonZero`] holding the **bit-inverse** of +//! the raw hash. The inversion is invisible to callers (`from_raw` / +//! `get` translate at the boundary) but means `Option` is +//! niche-packed into 8 bytes — `None` is the bit pattern `0`, the inverse +//! of the reserved `u64::MAX` sentinel. +//! * [`hash_python_str`] / [`hash_python_bytes`] / [`hash_python_long_int`] +//! — the canonical hash functions for `str`, `bytes` and arbitrary-precision +//! `int`. Routing every `str`/`bytes`/`int` hash through these helpers +//! keeps the invariant "interned and heap values with equal content hash +//! identically" local rather than scattered, since otherwise dict lookups +//! would silently miss. +//! * [`RESERVED_STRING_HASHES`] — lazily computed hashes for the reserved ASCII +//! single-character strings and the empty string. + +use std::{ + collections::hash_map::DefaultHasher, + fmt, + hash::{Hash, Hasher}, + num::NonZero, + sync::atomic::{AtomicU64, Ordering}, +}; + +use num_bigint::BigInt; +use num_traits::{FromPrimitive, ToPrimitive}; + +use crate::heap::HeapId; + +/// A verified Python hash value. +/// +/// Internally a [`NonZero`] holding the bit-inverse of the raw hash, so +/// `Option` niche-packs into 8 bytes. Construct via +/// [`HashValue::from_raw`]; extract via [`HashValue::get`] (both translate +/// the inversion at the boundary). +/// +/// The bit-inversion is purely an implementation detail of the niche +/// packing — none of the public traits leak it. [`Hash`], [`fmt::Debug`], +/// [`serde::Serialize`] and [`serde::Deserialize`] all hand-translate to/from +/// the raw `u64` form, so: +/// +/// * Composite hashes that fold a `HashValue` see the same bytes `get()` +/// returns (independent of storage layout — a future change to e.g. +/// `NonMaxU64` would leave tuple/dict hashes invariant). +/// * Debug output shows the raw hash (`HashValue(5)`, not the inverted bits). +/// * Snapshots store the raw hash, so the wire format is decoupled from the +/// niche-packing representation. +/// +/// Stored in interner hash tables, returned by `Value::py_hash`, and used +/// wherever a known-good hash needs to be passed around. +#[derive(Clone, Copy, PartialEq, Eq)] +#[repr(transparent)] +pub(crate) struct HashValue(NonZero); + +impl HashValue { + /// Wraps a freshly-computed raw hash. + /// + /// Bit-inverts and stores as `NonZero`. The single edge case where + /// `!hash == 0` (i.e. raw `hash == u64::MAX`) maps to + /// [`NonZero::::MIN`] — equivalent to bumping the raw hash by 1. + /// Mirrors CPython's reservation of `Py_hash_t = -1`. Bias: 1 in 2^64, + /// no impact on common hashes like `hash(0) == 0`. + #[inline] + #[must_use] + pub const fn new(hash: u64) -> Self { + Self(match NonZero::new(!hash) { + Some(nz) => nz, + None => NonZero::::MIN, + }) + } + + /// Returns the underlying `u64` for use in modulo arithmetic, hashbrown + /// indexing, and other places that need a bare hash. + #[inline] + #[must_use] + pub const fn raw(self) -> u64 { + !self.0.get() + } +} + +impl Hash for HashValue { + /// Folds the raw hash (not the stored, inverted form) so that + /// composite hashes are independent of the niche-packing representation. + /// Without this, a future change to the internal layout would silently + /// alter every tuple / namedtuple / dataclass hash. + #[inline] + fn hash(&self, state: &mut H) { + self.raw().hash(state); + } +} + +impl fmt::Debug for HashValue { + /// Prints the raw hash, not the stored bit-inverted form, so debugging + /// output matches `get()`. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("HashValue").field(&self.raw()).finish() + } +} + +impl serde::Serialize for HashValue { + /// Emits the raw hash so the wire format is decoupled from the + /// niche-packing representation. + fn serialize(&self, serializer: S) -> Result { + self.raw().serialize(serializer) + } +} + +impl<'de> serde::Deserialize<'de> for HashValue { + /// Reads a raw `u64` and reconstructs via [`HashValue::from_raw`], so + /// even a pathological wire value of `u64::MAX` is handled by the same + /// sentinel-collision path as fresh hashes. + fn deserialize>(deserializer: D) -> Result { + Ok(Self::new(u64::deserialize(deserializer)?)) + } +} + +/// Hashes a float so that an integral value hashes like the equal `int` +/// (`hash(1.0) == hash(1)`, `2.0**100` like `2**100`), which dict lookup +/// across the numeric tower relies on; anything else hashes its bits. +pub(crate) fn hash_f64(f: f64) -> HashValue { + // 2^63, the first power of two past i64::MAX (exactly representable). + const TWO_POW_63: f64 = 9_223_372_036_854_775_808.0; + if f.fract() != 0.0 || !f.is_finite() { + HashValue::new(f.to_bits()) + } else if (-TWO_POW_63..TWO_POW_63).contains(&f) { + #[expect(clippy::cast_possible_truncation)] + HashValue::new((f as i64).cast_unsigned()) + } else { + hash_python_long_int(&BigInt::from_f64(f).expect("finite f64 converts to BigInt")) + } +} + +/// Hashes any `Hash` value with a fresh [`DefaultHasher`]. +/// +/// Keeps the hasher boilerplate in one place for the cold `Value::py_hash` arms +/// (functions, named builtins, heap identities), so the hot arms (int/str/ref) +/// never pay for constructing a hasher they don't use. +#[inline] +pub(crate) fn hash_one(value: impl Hash) -> HashValue { + let mut hasher = DefaultHasher::new(); + value.hash(&mut hasher); + HashValue::new(hasher.finish()) +} + +/// Hashes a heap value by its identity (`HeapId`). +/// +/// The canonical hash for objects that compare by identity — user classes, +/// instances, bound methods, and cells (CPython's default for objects without +/// a user `__hash__`). Keeps the `DefaultHasher` boilerplate in one place. +#[inline] +pub(crate) fn identity_hash(id: HeapId) -> HashValue { + hash_one(id) +} + +/// Hashes a value with no heap identity (a builtin, type, marker or singleton) +/// by its stable name. Dict and set entries persist their hash in dumps, so a +/// hash tied to an enum's declaration order would break lookups in older dumps +/// once a variant is inserted. `kind` keeps `int` apart from the string `'int'`. +pub(crate) fn hash_named(kind: &'static str, name: &str) -> HashValue { + hash_one((kind, name)) +} + +/// Hashes a string using the canonical Python-string hash function. +/// +/// Both heap-allocated `Str` values and interned strings must use this so +/// that an interned `"foo"` and a heap `"foo"` hash identically — required +/// for dict-key consistency. +#[inline] +pub(crate) fn hash_python_str(s: &str) -> HashValue { + let mut hasher = DefaultHasher::new(); + s.hash(&mut hasher); + HashValue::new(hasher.finish()) +} + +/// Hashes a bytes value using the canonical Python-bytes hash function. +/// +/// Counterpart to [`hash_python_str`] for `bytes`. Used by both heap `Bytes` +/// and the interned bytes table. +#[inline] +pub(crate) fn hash_python_bytes(b: &[u8]) -> HashValue { + let mut hasher = DefaultHasher::new(); + b.hash(&mut hasher); + HashValue::new(hasher.finish()) +} + +/// Hashes a `BigInt` consistently with Python's `int` hash. +/// +/// For values that fit in `i64`, returns `i.cast_unsigned()` so that +/// `hash(LongInt(5)) == hash(Value::Int(5))`. For larger values, falls back +/// to hashing `(sign, little-endian bytes)` via [`DefaultHasher`]. +/// +/// Used by heap `LongInt::py_hash` and by `Interns::long_int_hash` so that +/// interned and heap-allocated long ints with equal value hash identically. +#[inline] +pub(crate) fn hash_python_long_int(bi: &BigInt) -> HashValue { + if let Some(i) = bi.to_i64() { + HashValue::new(i.cast_unsigned()) + } else { + let mut hasher = DefaultHasher::new(); + let (sign, bytes) = bi.to_bytes_le(); + sign.hash(&mut hasher); + bytes.hash(&mut hasher); + HashValue::new(hasher.finish()) + } +} + +/// A value paired with its precomputed Python [`HashValue`]. +/// +/// Used in the interner storage so each entry carries its own hash next to +/// the value — push-the-pair instead of parallel arrays. This makes it +/// impossible to forget to keep the value and hash in sync, and makes +/// serde recompute-on-deserialise local to this type. +/// +/// Constructors, `SerializeHashed` and `Deserialize` impls are provided for +/// each concrete value type used by the interners. Adding another requires a +/// constructor and both serde halves. +/// +/// # Wire format +/// +/// `Serialize` writes only the value (the hash is recomputable): text and +/// big integers as `T`'s own serialised form, `Vec` as a byte string via +/// `serde_bytes`, chosen by the private `SerializeHashed` trait. `Deserialize` +/// reads the same form and rebuilds the hash via the appropriate +/// `hash_python_*` helper, so round-tripping through serde is lossless and any +/// deserialiser-supplied bytes always produce a hash consistent with the +/// canonical helpers. +#[derive(Debug, Clone)] +pub(crate) struct WithHash { + value: T, + hash: HashValue, +} + +impl WithHash { + /// Borrow the wrapped value. + #[inline] + pub fn value(&self) -> &T { + &self.value + } + + /// The precomputed [`HashValue`]. + #[inline] + pub fn hash(&self) -> HashValue { + self.hash + } +} + +impl> WithHash { + /// Caches the Python hash for owned or borrowed string storage. + #[inline] + pub fn for_str(value: T) -> Self { + let hash = hash_python_str(value.as_ref()); + Self { value, hash } + } +} + +impl WithHash> { + /// Construct from an owned `Vec`, hashing via [`hash_python_bytes`]. + #[inline] + pub fn for_bytes(value: Vec) -> Self { + let hash = hash_python_bytes(&value); + Self { value, hash } + } +} + +impl WithHash { + /// Construct from an owned `BigInt`, hashing via [`hash_python_long_int`]. + #[inline] + pub fn for_long_int(value: BigInt) -> Self { + let hash = hash_python_long_int(&value); + Self { value, hash } + } +} + +// `Serialize` emits just the inner value. The hash is recomputable from the +// value during deserialisation, so we don't waste bytes encoding it (and we +// don't risk locking the snapshot format to the current hash function). +impl serde::Serialize for WithHash { + fn serialize(&self, serializer: S) -> Result { + self.value.serialize_hashed(serializer) + } +} + +/// How a hashed value is written: byte payloads go out as a byte string rather +/// than one integer per byte, everything else as itself. +trait SerializeHashed { + fn serialize_hashed(&self, serializer: S) -> Result; +} + +impl SerializeHashed for Vec { + fn serialize_hashed(&self, serializer: S) -> Result { + serde_bytes::serialize(self, serializer) + } +} + +/// Text and big integers already have the right serde form. +macro_rules! serialize_hashed_as_self { + ($($ty:ty),*) => {$( + impl SerializeHashed for $ty { + fn serialize_hashed(&self, serializer: S) -> Result { + serde::Serialize::serialize(self, serializer) + } + } + )*}; +} + +serialize_hashed_as_self!(String, Box, BigInt); + +// `Deserialize` is hand-written per concrete `T` so the right +// `hash_python_*` helper is invoked. +impl<'de> serde::Deserialize<'de> for WithHash { + fn deserialize>(deserializer: D) -> Result { + Ok(Self::for_str(String::deserialize(deserializer)?)) + } +} + +impl<'de> serde::Deserialize<'de> for WithHash> { + fn deserialize>(deserializer: D) -> Result { + Ok(Self::for_str(Box::::deserialize(deserializer)?)) + } +} + +impl<'de> serde::Deserialize<'de> for WithHash> { + fn deserialize>(deserializer: D) -> Result { + Ok(Self::for_bytes(serde_bytes::deserialize(deserializer)?)) + } +} + +impl<'de> serde::Deserialize<'de> for WithHash { + fn deserialize>(deserializer: D) -> Result { + Ok(Self::for_long_int(BigInt::deserialize(deserializer)?)) + } +} + +/// Per-slot lazy `static` hash table. +/// +/// `[AtomicU64; N]` storing the inner bits of [`HashValue`] (i.e. the +/// bit-inverted raw hash). `0` is the "uncomputed" sentinel — naturally +/// equivalent to [`Option`]'s `None` since `HashValue`'s niche +/// is exactly `0`. +/// +/// On the first access of slot `i` the closure is invoked, the result is +/// stored, and subsequent accesses return it directly. Two threads racing +/// to fill the same slot is benign: they compute the same value and one +/// wins the store; the other's store overwrites with the same bits. +/// +/// Used for the reserved ASCII and empty-string hash table. +/// `Cell>` would be the equivalent for non-`static` / +/// per-instance use (Phase 2's per-type heap caches). +pub(crate) struct LazyHashTable { + cells: [AtomicU64; N], +} + +impl LazyHashTable { + /// Construct an empty table — every slot starts uncomputed (`0`). + pub const fn new() -> Self { + Self { + cells: [const { AtomicU64::new(0) }; N], + } + } + + /// Returns the cached [`HashValue`] for `index`, or computes and stores it. + /// + /// `Ordering::Relaxed` suffices: the only invariant is "any non-zero + /// value observed is a valid `HashValue`'s inner bits" — true by + /// construction since we only store `HashValue::0.get()` (which is + /// guaranteed non-zero by `NonZero`). + #[inline] + pub fn get_or_compute(&self, index: usize, compute: impl FnOnce() -> HashValue) -> HashValue { + if let Some(stored) = NonZero::new(self.cells[index].load(Ordering::Relaxed)) { + HashValue(stored) + } else { + let h = compute(); + self.cells[index].store(h.0.get(), Ordering::Relaxed); + h + } + } +} + +/// Per-slot lazy hashes for ASCII IDs 0–127 and the empty-string ID 128. +/// Each slot hashes the matching entry of [`crate::intern::RESERVED_STRS`]. +pub(crate) static RESERVED_STRING_HASHES: LazyHashTable<129> = LazyHashTable::new(); diff --git a/crates/bashkit-monty/src/heap/free_list.rs b/crates/bashkit-monty/src/heap/free_list.rs new file mode 100644 index 000000000..0cd6bf8ec --- /dev/null +++ b/crates/bashkit-monty/src/heap/free_list.rs @@ -0,0 +1,44 @@ +use std::cell::UnsafeCell; + +use crate::heap::HeapId; + +/// Not-thread-safe free list for `HeapId`s. +pub struct FreeList { + /// Content of the free list. See `.pop()` and `.push()` for more details. + ids: UnsafeCell>, +} + +impl FreeList { + pub fn new() -> Self { + Self { + ids: UnsafeCell::new(Vec::new()), + } + } + + /// Pops a `HeapId` from the free list. Returns `None` if the free list is empty. + pub fn pop(&self) -> Option { + // SAFETY: (DH) + // - `.pop()` does not shrink the vector so no reentrancy concerns from an allocator + // - `.pop()` does not re-enter into itself, so with `FreeList` being `!Sync`, we can + // be sure that there are no concurrent calls to `.pop()` that could cause data races. + // - No `FreeList` methods hand out references to the inner vector, `HeapId` is `Copy`, + // so the value is trivially copied out without causing other code to run. + unsafe { (*self.ids.get()).pop() } + } + + /// Pushes a `HeapId` back to the free list. Borrows the freelist mutably. + pub fn push(&mut self, id: HeapId) { + // Requiring `&mut self` avoids unsafe here as well as possible weird edge cases + // like what if a re-entrant allocator was able to try to push to a static + // free list while it was already being pushed to. + self.ids.get_mut().push(id); + } +} + +impl From> for FreeList { + fn from(ids: Vec) -> Self { + Self { + ids: UnsafeCell::new(ids), + } + } +} diff --git a/crates/bashkit-monty/src/heap/mod.rs b/crates/bashkit-monty/src/heap/mod.rs new file mode 100644 index 000000000..307d273eb --- /dev/null +++ b/crates/bashkit-monty/src/heap/mod.rs @@ -0,0 +1,2765 @@ +#![expect( + unsafe_code, + reason = "Paged arena hands out typed, aliasable views into UnsafeCell entries" +)] + +#[cfg(feature = "ref-count-return")] +use std::collections::HashSet; +use std::{ + cell::{Cell, UnsafeCell}, + collections::BTreeMap, + fmt, + iter::once, + marker::PhantomData, + ops::{Deref, DerefMut}, + ptr::{self, NonNull}, + sync::Arc, +}; + +use monty_types::{DEFAULT_GC_INTERVAL, MontyUuid, ResourceTracker}; +use serde::{de::Error as _, ser::SerializeStruct}; + +#[cfg(feature = "ref-count-return")] +use crate::types::Type; +use crate::{ + asyncio::{Awaiter, ExternalFutureState, GatherState}, + types::{ExtFunction, HostClassType, TimeZone, Tuple, decimal::py_context::DecimalSlot}, + value::Value, +}; +// Re-export items moved to `heap_traits` so that `crate::heap::DropGuard` etc. continue +// to resolve (used by the `defer_drop!` macros and throughout the codebase). +pub(crate) use crate::{ + heap_data::HeapData, + heap_traits::{ContainsHeap, DropGuard, DropWithContext, HeapItem}, +}; + +mod free_list; +mod stable_heap; +pub(crate) use stable_heap::StableHeap; + +/// Unique identifier for values stored inside the heap arena. +/// +/// The ID does not encode ownership. Local IDs should normally be borrowed or +/// wrapped immediately in `Value::Ref`; owned fields must document and release +/// their reference through `HeapItem` or `DropWithContext` cleanup. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct HeapId(usize); + +impl HeapId { + /// Creates a `HeapId` from a raw index. + #[inline] + pub(crate) fn from_index(index: usize) -> Self { + Self(index) + } + + /// Returns the raw index value. + #[inline] + pub fn index(self) -> usize { + self.0 + } +} + +/// The empty tuple is a singleton which is allocated at startup. +const EMPTY_TUPLE_ID: HeapId = HeapId(0); + +/// Color tag used by the trial-deletion cycle collector (Bacon–Rajan, ECOOP 2001). +/// +/// Each [`HeapEntry`] carries a color that represents what the collector currently +/// believes about the entry. Outside of a running collection, every reachable +/// entry is either [`Black`](Self::Black) (live, not part of any suspected cycle) +/// or [`Purple`](Self::Purple) (a candidate cycle root discovered by `dec_ref`, +/// awaiting investigation). [`Gray`](Self::Gray) and [`White`](Self::White) are +/// transient states used only during a [`Heap::collect_cycles`] call. +/// +/// The encoding fits in a single byte and is serialized as part of every +/// [`HeapEntry`]: a snapshot taken with cycles pending must round-trip through +/// serde so the entries stay enrolled as candidates after restore (otherwise a +/// graph that becomes garbage just before snapshot would leak permanently). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +pub(crate) enum CcColor { + /// Live and not currently a cycle candidate. Default state for every newly + /// allocated entry. + #[default] + #[serde(rename = "B")] + Black, + /// Visited by `MarkGray` during a collection cycle. Children's refcounts + /// have been provisionally decremented; a later `Scan` pass decides whether + /// to resurrect (back to [`Black`](Self::Black)) or condemn + /// ([`White`](Self::White)) the entry. + #[serde(rename = "G")] + Gray, + /// Confirmed unreachable by the current collection: every reference into + /// the entry comes from another condemned entry. `CollectWhite` will free + /// it. Only seen mid-collection. + #[serde(rename = "W")] + White, + /// Candidate cycle root. Set by `dec_ref` whenever a GC-tracked entry's + /// refcount drops to a non-zero value — the only situation in which a new + /// reference cycle can become unreachable. The collector seeds its work + /// from every entry currently flagged Purple. + #[serde(rename = "P")] + Purple, +} + +/// This structure allows for reading into the heap more efficiently than repeated calls to `Heap::get` and +/// `Heap::get_mut` by performing the indexing and type lookup once, and then using the borrow checker to +/// safely deference the resulting pointers for short-lived borrows. +/// +/// The safety boundary is primarily that `HeapRead` pointers generated by the `HeapReader::read` API must remain valid +/// for their lifetime, see the safety notes in `HeapRead::get` for how that is guaranteed. +pub(crate) struct HeapReader<'a> { + pub(crate) heap: &'a mut Heap, + /// Makes the lifetime `'a` invariant. + phantom: PhantomData &'a ()>, +} + +impl HeapReader<'_> { + /// The ONLY way to get a `HeapReader`. By only providing an API which takes a closure which + /// must be satisfied for all `'a`, it's impossible to create other `HeapReader` with the + /// exact same lifetime `'a`. + /// + /// To allow other data to be borrowed alongside the `HeapReader`, the closure is given a + /// `&'a mut D` with the same lifetime as the `HeapReader`, which is forwarded from the + /// `&mut D` passed to this function. This rebranding lets callers (most notably the + /// `VM`) hold borrows whose lifetime matches the `HeapReader`'s invariant brand `'a`, + /// which is what allows the `VM` to be parameterized by a single lifetime. + pub fn with( + heap: &mut Heap, + data: &mut D, + f: impl for<'a> FnOnce(&'a mut HeapReader<'a>, &'a mut D) -> R, + ) -> R { + f( + &mut HeapReader { + heap: &mut *heap, + phantom: PhantomData, + }, + data, + ) + } +} + +impl<'a> HeapReader<'a> { + /// Resolves a `HeapId` to a stable, branded [`HeapPtr<'a>`] for its entry. + /// + /// The returned `HeapPtr` can be used for efficient repeated access to the same entry + /// without needing to re-index into the paged storage on every access. + /// + /// # Panics + /// + /// Panics if `id` is out of bounds. + pub(crate) fn read_ptr(&self, id: HeapId) -> HeapPtr<'a> { + // SAFETY: [DH] - `HeapPtr` prevents holding reference to freed slots across calls to allocate; it + // always hands out either live `&HeapData` or `None`, never `&Option`. + let slot = unsafe { self.heap.entries.slot_at(id) }.expect("HeapReader::read_ptr - id out of bounds"); + HeapPtr { + inner: NonNull::from(slot), + brand: PhantomData, + } + } + + /// Indexes into the heap. + /// + /// Thin wrapper around [`HeapPtr::read`]: resolves `id` to a `HeapPtr` and + /// delegates the typed match/reader-count logic there. Panics if `id` is out + /// of bounds or the slot is currently freed. + pub fn read(&self, id: HeapId) -> HeapReadOutput<'a> { + self.read_ptr(id).read(id, self) + } + + /// Reads `id` as the requested concrete payload type. + /// + /// Returns `None` when the live entry stores a different payload type. + pub fn read_as(&self, id: HeapId) -> Option> { + T::try_from_read(self.read(id)).ok() + } + + /// Allocates a concrete payload and returns an owning, typed handle to it. + /// + /// The allocation's initial reference must eventually be transferred with + /// `into_value`/`into_id`, or released by guarding the handle with `DropGuard`. + pub fn allocate_as(&self, value: T) -> HeapAllocation<'a, T> { + let entry = self.heap.new_entry(value.into_heap_data()); + let (id, slot) = self.heap.entries.allocate_with_slot(entry); + HeapAllocation { + id, + ptr: HeapPtr { + inner: NonNull::from(slot), + brand: PhantomData, + }, + read: None, + } + } + + /// Brands a shared external borrow without granting mutable access to its source. + #[expect(clippy::unused_self, reason = "'a lifetime is used to create the safety guarantees")] + pub fn protect<'t, U: ?Sized>(&mut self, value: &'t U) -> BorrowedHeapRead<'t, 'a, U> { + BorrowedHeapRead { + inner: HeapRead { + value: NonNull::from(value), + borrow: PhantomData, + }, + original: PhantomData, + } + } + + /// Brands an exclusive external borrow; payload access is serialized by this reader. + #[expect(clippy::unused_self, reason = "'a lifetime is used to create the safety guarantees")] + pub fn protect_mut<'t, U: ?Sized>(&mut self, value: &'t mut U) -> BorrowedHeapReadMut<'t, 'a, U> { + BorrowedHeapReadMut { + inner: HeapReadMut { + read: HeapRead { + value: NonNull::from(value), + borrow: PhantomData, + }, + }, + original: PhantomData, + } + } +} + +impl ContainsHeap for HeapReader<'_> { + fn heap(&self) -> &Heap { + self.heap.heap() + } + fn heap_mut(&mut self) -> &mut Heap { + self.heap.heap_mut() + } +} + +impl Deref for HeapReader<'_> { + type Target = Heap; + + fn deref(&self) -> &Self::Target { + self.heap + } +} + +impl DerefMut for HeapReader<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.heap + } +} + +macro_rules! heap_storage_value { + (inline $value:expr) => { + $value + }; + (boxed $value:expr) => { + Box::new($value) + }; +} + +/// Maps a concrete Rust payload to its heap representation and typed read variant. +/// +/// Implementations are generated from `heap_data::heap_payloads`, keeping each +/// payload's storage conversion and typed read extraction in the central registry. +pub(crate) trait HeapPayload: Sized { + /// Wraps this payload in its corresponding `HeapData` variant. + fn into_heap_data(self) -> HeapData; + + /// Extracts this payload's typed handle from a dynamic heap read. + fn try_from_read(read: HeapReadOutput<'_>) -> Result, HeapReadOutput<'_>>; +} + +macro_rules! define_heap_read_support { + ($( + $(#[$meta:meta])* + $variant:ident($storage:ident $payload:ty) + ),* $(,)?) => { + /// A type-safe read handle for any payload stored in the heap. + /// Variants mirror `HeapData`, which carries their docs; its serde attributes + /// would not compile here, so the registry's attributes are not repeated. + pub enum HeapReadOutput<'a> { + $( + $variant(HeapObjectRead<'a, $payload>), + )* + } + + impl HeapReadOutput<'_> { + /// Returns the heap entry containing the complete dynamically read object. + pub fn id(&self) -> HeapId { + match self { + $(Self::$variant(value) => value.id(),)* + } + } + } + + $( + impl HeapPayload for $payload { + #[inline] + fn into_heap_data(self) -> HeapData { + HeapData::$variant(heap_storage_value!($storage self)) + } + + #[inline] + fn try_from_read( + read: HeapReadOutput<'_>, + ) -> Result, HeapReadOutput<'_>> { + if let HeapReadOutput::$variant(value) = read { + Ok(value) + } else { + Err(read) + } + } + } + )* + + }; +} + +crate::heap_data::heap_payloads!(define_heap_read_support); + +/// A newly allocated heap object with its initial owned reference. +/// +/// Typed access is created lazily by [`Self::read`], so transferring an allocation +/// directly into a `Value` or raw ID does not touch the entry's reader count. +#[must_use = "the allocation's initial reference must be transferred"] +pub struct HeapAllocation<'a, T> { + id: HeapId, + ptr: HeapPtr<'a>, + read: Option>, +} + +impl<'a, T: HeapPayload> HeapAllocation<'a, T> { + /// Returns the allocated object's identity without transferring ownership. + pub fn id(&self) -> HeapId { + self.id + } + + /// Creates the typed read handle on first access and reuses it thereafter. + pub fn read(&mut self, heap: &HeapReader<'a>) -> &mut HeapObjectRead<'a, T> { + let id = self.id; + let ptr = self.ptr; + self.read.get_or_insert_with(|| { + T::try_from_read(ptr.read(id, heap)) + .unwrap_or_else(|_| unreachable!("allocated payload has its registered type")) + }) + } + + /// Transfers the allocation's initial reference into a `Value`. + pub fn into_value(self) -> Value { + Value::Ref(self.into_id()) + } + + /// Transfers the allocation's initial reference as an owned raw ID. + pub fn into_id(mut self) -> HeapId { + let id = self.id(); + drop(self.read.take()); + id + } +} + +impl DropWithContext for HeapAllocation<'_, T> { + fn drop_with(mut self, ctx: &mut C) { + drop(self.read.take()); + Value::Ref(self.id).drop_with(ctx); + } +} + +/// A typed read handle for a Python object stored in a specific heap entry. +/// +/// Unlike [`HeapRead`], this always represents the complete object rather than +/// protected external data or a projected field, so its [`HeapId`] is available +/// to operations that need Python identity or an owned reference to `self`. +pub struct HeapObjectRead<'a, T: ?Sized> { + /// Identity of the complete Python object exposed by `read`. + id: HeapId, + /// Mutable capability; never exposed by value or mutable reference. + read: HeapReadMut<'a, T>, + /// Owned reader count, keeping this entry alive until the guard is dropped. + readers: NonNull>, +} + +impl<'a, T: ?Sized> HeapObjectRead<'a, T> { + /// Returns the heap entry containing this object. + pub fn id(&self) -> HeapId { + self.id + } + + /// Returns a new owned reference to this object. + pub fn clone_value(&self, heap: &HeapReader<'a>) -> Value { + heap.inc_ref(self.id); + Value::Ref(self.id) + } +} + +impl<'a, T: ?Sized> Deref for HeapObjectRead<'a, T> { + type Target = HeapReadMut<'a, T>; + + fn deref(&self) -> &Self::Target { + &self.read + } +} + +impl Drop for HeapObjectRead<'_, T> { + fn drop(&mut self) { + // SAFETY: the paged storage keeps the counter's address stable, and this + // owned reader count prevents the entry from being freed before the guard. + let cell = unsafe { self.readers.as_ref() }; + cell.set(cell.get() - 1); + } +} + +/// A typed, identity-free view protected by a [`HeapReader`]. +/// +/// Complete heap objects are exposed as [`HeapObjectRead`]; this lower-level +/// handle also supports projected fields and data protected by `protect`. +pub struct HeapRead<'a, T: ?Sized> { + value: NonNull, + /// Makes the lifetime `'a` invariant. In combination with the invariant lifetime + /// on `HeapReader` and the `HeapReader::with` API, this guarantees that this + /// `HeapRead` originated from that matching `HeapReader` (there is no way to + /// construct another `HeapReader` with the same lifetime). + borrow: PhantomData &'a T>, +} + +/// Aliasable mutable-access capability, used only through shared references. +/// +/// The matching reader serializes payload access. Owners expose no `DerefMut`, +/// extraction or cloning API: replacing this capability could detach its pointer +/// from the source lifetime or reader count held by its owner. +pub struct HeapReadMut<'a, T: ?Sized> { + read: HeapRead<'a, T>, +} + +impl<'a, T: ?Sized> Deref for HeapReadMut<'a, T> { + type Target = HeapRead<'a, T>; + + fn deref(&self) -> &Self::Target { + &self.read + } +} + +impl<'a, T: ?Sized> HeapRead<'a, T> { + /// Borrows the value while both this handle and the reader remain borrowed. + /// + /// Borrowing the handle also keeps protected external data and projection sources alive. + pub fn get<'r>(&'r self, _: &'r HeapReader<'a>) -> &'r T { + // SAFETY: (DH) + // - The HeapReader has an invariant lifetime 'a which guarantees that this HeapRead + // came from the heap borrowed by this HeapReader. + // - The address of the `HeapValue` never changes because entries are stored in + // paged storage (`HeapEntries`) where each page is never reallocated or moved. + // - The owning HeapObjectRead holds a reader count which guarantees the entry + // will never be freed by `dec_ref` or `collect_cycles` while the owner is + // borrowed through this HeapRead. The cycle collector's + // `Scan` phase treats `readers > 0` as an external reference and resurrects + // the entry to Black instead of condemning it as White. + // - The type of the `HeapValue` can never change once allocated. This is + // guaranteed by never exposing `&mut HeapData` outside of this module. + // - For protected external data and projections, borrowing this handle keeps the source + // borrow alive instead; their wrappers do not own a reader count. + // - The borrow on `HeapReader` guarantees that there are no mutable borrows on any heap + // data while the return value of this function is alive. + unsafe { self.value.as_ref() } + } + + /// Casts this reader to a field of type `U` at some `offset` within the struct. + /// + /// Borrows `self` to keep the source alive; the projection owns no reader count. + /// + /// # Safety + /// - The field of type `U` must ALWAYS exist at `offset` within `T` (i.e. `T` cannot be an enum, union etc) + unsafe fn cast_as_member_ref(&self, offset: usize) -> BorrowedHeapRead<'_, 'a, U> { + BorrowedHeapRead { + inner: HeapRead { + // SAFETY: caller guarantees offset points to a valid field of type U within T + value: unsafe { self.value.byte_add(offset) }.cast(), + borrow: PhantomData, + }, + original: PhantomData, + } + } +} + +impl<'a, T: ?Sized> HeapReadMut<'a, T> { + /// Exclusively borrows the payload, not the capability; aliases share the reader lock. + pub fn get_mut<'r>(&'r self, _: &'r mut HeapReader<'a>) -> &'r mut T { + let mut value = self.read.value; + // SAFETY: the owner guarantees a writable, live pointee. The mutable reader + // borrow excludes all other payload access until this reference expires. + unsafe { value.as_mut() } + } + + /// Casts this reader to a field of type `U` at some `offset` within the struct. + /// + /// Borrows the capability's owner; payload exclusivity still comes from the reader. + /// + /// # Safety + /// - The field of type `U` must ALWAYS exist at `offset` within `T` (i.e. `T` cannot be an enum, union etc) + unsafe fn cast_as_member_ref_mut(&self, offset: usize) -> BorrowedHeapReadMut<'_, 'a, U> { + BorrowedHeapReadMut { + inner: HeapReadMut { + read: HeapRead { + // SAFETY: caller guarantees offset points to a valid field of type U within T + value: unsafe { self.read.value.byte_add(offset) }.cast(), + borrow: PhantomData, + }, + }, + original: PhantomData, + } + } +} + +/// Read-only payload access, including projections that must re-resolve their storage. +/// +/// A vector or box may be replaced between accesses through another capability; +/// its projection must borrow the current allocation rather than cache a pointer. +pub(crate) trait HeapView<'a, T: ?Sized> { + /// Borrows the current payload for the joint lifetime of the view and reader. + fn get<'r>(&'r self, reader: &'r HeapReader<'a>) -> &'r T; +} + +impl<'a, T: ?Sized> HeapView<'a, T> for HeapRead<'a, T> { + fn get<'r>(&'r self, reader: &'r HeapReader<'a>) -> &'r T { + self.get(reader) + } +} + +impl<'a, T> HeapRead<'a, Vec> { + /// Projects the current vector buffer without retaining its allocation address. + pub fn as_slice(&self) -> HeapSliceRead<'_, 'a, T> { + HeapSliceRead { source: self } + } +} + +/// A vector projection that observes buffer replacement between reader borrows. +pub struct HeapSliceRead<'source, 'a, T> { + source: &'source HeapRead<'a, Vec>, +} + +impl<'a, T> HeapView<'a, [T]> for HeapSliceRead<'_, 'a, T> { + fn get<'r>(&'r self, reader: &'r HeapReader<'a>) -> &'r [T] { + self.source.get(reader).as_slice() + } +} + +impl<'a, T: ?Sized> HeapRead<'a, Box> { + /// Projects the current box allocation without retaining its address. + pub fn as_box_value(&self) -> HeapBoxRead<'_, 'a, T> { + HeapBoxRead { source: self } + } +} + +/// A box projection that observes replacement between reader borrows. +pub struct HeapBoxRead<'source, 'a, T: ?Sized> { + source: &'source HeapRead<'a, Box>, +} + +impl<'a, T: ?Sized> HeapView<'a, T> for HeapBoxRead<'_, 'a, T> { + fn get<'r>(&'r self, reader: &'r HeapReader<'a>) -> &'r T { + self.source.get(reader).as_ref() + } +} + +/// Shared capability whose source borrow stays alive through every payload access. +pub struct BorrowedHeapRead<'original, 'a, U: ?Sized> { + inner: HeapRead<'a, U>, + original: PhantomData<&'original U>, +} + +impl<'a, U: ?Sized> Deref for BorrowedHeapRead<'_, 'a, U> { + type Target = HeapRead<'a, U>; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +/// Helper for `heap_read_ref_as_field`; callers must uphold `HeapRead::cast_as_member_ref`'s contract. +pub(crate) unsafe fn cast_as_member_ref_type_hinted<'r, 'a, T, U>( + heap_read: &'r HeapRead<'a, T>, + offset: usize, + _type_hint: impl for<'s> Fn(&'s HeapRead<'a, T>) -> *const U, +) -> BorrowedHeapRead<'r, 'a, U> { + // SAFETY: (DH) - caller upholds `cast_as_member` contract + unsafe { heap_read.cast_as_member_ref(offset) } +} + +macro_rules! heap_read_ref_as_field { + ($heap_read:ident, $ty:ty, $field:tt) => {{ + let offset = std::mem::offset_of!($ty, $field); + #[expect(unreachable_code)] + let type_hint = |read: &$crate::heap::HeapRead<'_, $ty>| &raw const read.get(unreachable!()).$field; + // SAFETY: (DH) + // - `std::mem::offset_of!` guarantees there is a field at fixed offset + // - `type_hint` guarantees that the field is of type `U` for the safety contract + #[expect(unsafe_code)] + unsafe { + $crate::heap::cast_as_member_ref_type_hinted($heap_read, offset, type_hint) + } + }}; +} + +pub(crate) use heap_read_ref_as_field; + +/// Mutable capability backed by a source borrow, never exposing its inner handle mutably. +pub struct BorrowedHeapReadMut<'original, 'a, U: ?Sized> { + inner: HeapReadMut<'a, U>, + original: PhantomData<&'original mut U>, +} + +impl<'a, U: ?Sized> Deref for BorrowedHeapReadMut<'_, 'a, U> { + type Target = HeapReadMut<'a, U>; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +/// Helper for `heap_read_ref_as_field_mut`; callers must uphold `HeapReadMut::cast_as_member_ref_mut`'s contract. +pub(crate) unsafe fn cast_as_member_ref_mut_type_hinted<'r, 'a, T, U>( + heap_read: &'r HeapReadMut<'a, T>, + offset: usize, + _type_hint: impl for<'s> Fn(&'s HeapRead<'a, T>) -> *const U, +) -> BorrowedHeapReadMut<'r, 'a, U> { + // SAFETY: (DH) - caller upholds `cast_as_member` contract + unsafe { heap_read.cast_as_member_ref_mut(offset) } +} + +macro_rules! heap_read_ref_as_field_mut { + ($heap_read:ident, $ty:ty, $field:tt) => {{ + let offset = std::mem::offset_of!($ty, $field); + #[expect(unreachable_code)] + let type_hint = |read: &$crate::heap::HeapRead<'_, $ty>| &raw const read.get(unreachable!()).$field; + // SAFETY: (DH) + // - `std::mem::offset_of!` guarantees there is a field at fixed offset + // - `type_hint` guarantees that the field is of type `U` for the safety contract + #[expect(unsafe_code)] + unsafe { + $crate::heap::cast_as_member_ref_mut_type_hinted($heap_read, offset, type_hint) + } + }}; +} + +pub(crate) use heap_read_ref_as_field_mut; + +/// Stable, branded pointer to a heap slot's `Option`. +/// +/// `HeapPtr<'a>` carries the same invariant lifetime `'a` as the [`HeapReader<'a>`] +/// that produced it (via [`HeapReader::entry_ptr`]). The brand mechanism is identical +/// to the one on [`HeapRead`]: pointers minted by one reader cannot be dereferenced +/// via a reader from a different `HeapReader::with` scope (or, looking ahead, a +/// different [`Heap`]), so same-heap origin is checked at compile time rather than +/// trusted by convention. +/// +/// The pointer addresses the *slot's `Option`*, not the inner `HeapEntry` +/// directly. This makes it well-defined across the full lifetime of the slot — even +/// across `dec_ref`-driven frees and subsequent reuse by `allocate` — because the +/// slot's memory location never moves; only its `Some`/`None` state changes. +/// +/// This mirrors the semantics of [`Heap::get`]/[`StableHeap::entry`] where the outer +/// `Option` is the live/freed signal. +/// +/// Used as a fast handle inside paths that would otherwise re-index into paged storage +/// per access — currently the cycle collector, which converts `HeapId → HeapPtr` once +/// at push-time and uses the pointer directly on every subsequent pop, avoiding the +/// `pages[page_idx][slot_idx]` lookup chain. +#[derive(Copy, Clone)] +#[repr(transparent)] +pub(crate) struct HeapPtr<'a> { + inner: NonNull>, + /// Makes `'a` invariant. Matches the brand on [`HeapReader<'a>`] / [`HeapRead<'a, T>`] + /// so a `HeapPtr` cannot be reborrowed under a different reader scope. + brand: PhantomData &'a ()>, +} + +impl<'a> HeapPtr<'a> { + /// Returns the live [`HeapEntry`] this pointer refers to, panicking if the slot + /// has been freed. + /// + /// All `HeapEntry` fields are interior-mutable — `refcount`/`readers`/`color` + /// via `Cell` and `data` via `UnsafeCell` — so callers can mutate them through + /// the returned `&HeapEntry` without ever needing `&mut HeapEntry`. That's + /// what makes a `&self`-derived `HeapPtr` (with Shared provenance) sound to + /// dereference: we never derive `&mut` from it, so the SB/TB rules permit + /// interior mutation via the embedded `Cell`/`UnsafeCell`. + /// + /// Use [`Self::try_entry`] for code paths that may legitimately encounter + /// freed slots (e.g. linear scans over `0..heap.entries.len()`). + pub fn entry<'r>(self, reader: &'r HeapReader<'a>) -> &'r HeapEntry { + self.try_entry(reader).expect("HeapPtr::entry: slot has been freed") + } + + /// Returns the [`HeapEntry`] this pointer refers to, or `None` if the slot is + /// currently freed. + /// + /// Use where a freed slot is part of the expected state (linear scans, root + /// reseeds, etc.). Mutation paths (cycle collector mark/scan inner loops) should + /// prefer [`Self::entry`] so that an unexpectedly-freed entry surfaces as a + /// loud panic rather than a silent skip. + pub(crate) fn try_entry<'r>(self, _reader: &'r HeapReader<'a>) -> Option<&'r HeapEntry> { + // SAFETY: + // - The invariant `'a` on `_reader` matches this pointer's brand, which is + // only settable inside `HeapReader::with`. That guarantees same-heap + // origin: a `HeapPtr<'a>` from a different reader scope cannot satisfy + // this signature. + // - `StableHeap::entry_ptr` only returns pointers to initialized slots, so + // the `Option` behind the pointer is always a valid place. + // - The `&HeapReader` borrow excludes any `&mut HeapReader` op that could + // free the slot during the returned reference's lifetime. + unsafe { self.inner.as_ref() }.as_ref() + } + + /// Returns the entry's [`HeapData`] payload via the `UnsafeHeapData` interior- + /// mutability boundary. + /// + /// `UnsafeCell::get` produces a `*mut HeapData` with `SharedReadWrite` permission, + /// so the returned `&HeapData` is sound even though the underlying `HeapPtr` was + /// minted via `&self`-derived `entry_ptr`. Mutation of the payload still requires + /// `&mut HeapReader` via the [`HeapReadMut`] machinery. + pub fn data<'r>(self, reader: &'r HeapReader<'a>) -> &'r HeapData { + let entry = self.entry(reader); + // SAFETY: `UnsafeCell::get` yields a `SharedReadWrite` pointer; the `&HeapReader` + // borrow on `reader` excludes any concurrent `&mut HeapReader` operation that + // could mutate the payload during the returned reference's lifetime. + unsafe { &*entry.data.0.get() } + } + + /// Returns the typed [`HeapReadOutput`] for this entry, incrementing the + /// reader count owned by the wrapped [`HeapObjectRead`] until its `Drop`. + /// + /// The guard's capability pointers are derived through the `UnsafeHeapData` + /// `UnsafeCell`, retaining `SharedReadWrite` permission for both read access + /// and mutation via [`HeapReadMut::get_mut`], which requires `&mut HeapReader`. + fn read(self, id: HeapId, reader: &HeapReader<'a>) -> HeapReadOutput<'a> { + /// Computes a `HeapObjectRead` from the raw `UnsafeCell` pointer and a shared reference + /// to the variant field. The `&T` is only used to compute the field's byte offset + /// within the `HeapData` enum; the returned `NonNull` is derived from the original + /// `*mut HeapData` pointer so it inherits the `SharedReadWrite` permission from + /// the `UnsafeCell`, allowing both reads and writes. + #[inline] + fn heap_read<'a, T>( + id: HeapId, + base: *mut HeapData, + field: &T, + readers: NonNull>, + ) -> HeapObjectRead<'a, T> { + let base_addr = base as usize; + let field_addr = ptr::from_ref(field) as usize; + let offset = field_addr - base_addr; + HeapObjectRead { + id, + readers, + read: HeapReadMut { + read: HeapRead { + // SAFETY: The pointer is derived from the UnsafeCell's `*mut` via byte + // offset, preserving the `SharedReadWrite` permission. No reference retag + // occurs — we only use the `&T` for its address, not to derive the pointer. + value: unsafe { NonNull::new_unchecked(base.byte_add(offset).cast::()) }, + borrow: PhantomData, + }, + }, + } + } + + /// Like `heap_read` but for `Box` fields inside `HeapData` variants. + /// + /// The `&Box` is only used to locate the box field inside the enum; the + /// inner pointer is *loaded out of* that field rather than derived by + /// dereferencing the box. Dereferencing (`boxed.as_ref()`) would create a + /// shared `&T` whose `SharedReadOnly` provenance makes later + /// `HeapReadMut::get_mut` writes UB; the loaded pointer instead carries the + /// box's own stored (writeable) provenance. + #[expect( + clippy::borrowed_box, + reason = "We intentionally take &Box to signal this is for boxed HeapData variants; &T would lose that context" + )] + fn heap_read_boxed<'a, T>( + id: HeapId, + base: *mut HeapData, + boxed: &Box, + readers: NonNull>, + ) -> HeapObjectRead<'a, T> { + let base_addr = base as usize; + let field_addr = ptr::from_ref(boxed) as usize; + let offset = field_addr - base_addr; + // SAFETY: `offset` locates the live `Box` field within the enum, and the + // pointer to it is derived from the `UnsafeCell`'s `*mut` (not from `&Box`), + // preserving `SharedReadWrite` permission for the load below. `Box` with + // `T: Sized` is guaranteed to be represented as a single non-null pointer, so + // loading the field as `*mut T` yields the box's data pointer together with + // the read/write provenance it was stored with. + let value = unsafe { NonNull::new_unchecked(base.byte_add(offset).cast::<*mut T>().read()) }; + HeapObjectRead { + id, + readers, + read: HeapReadMut { + read: HeapRead { + value, + borrow: PhantomData, + }, + }, + } + } + + macro_rules! heap_read_value { + (inline $id:expr, $base:expr, $value:expr, $readers:expr) => { + heap_read($id, $base, $value, $readers) + }; + (boxed $id:expr, $base:expr, $value:expr, $readers:expr) => { + heap_read_boxed($id, $base, $value, $readers) + }; + } + + let entry = self.entry(reader); + // Increment the reader count for this entry. The corresponding decrement + // happens in `HeapObjectRead::drop`. + entry.readers.set(entry.readers.get() + 1); + let readers = NonNull::from(&entry.readers); + // Get the raw pointer from the UnsafeCell — this has SharedReadWrite permission. + let base: *mut HeapData = entry.data.0.get(); + + macro_rules! read_heap_payload { + ($( + $(#[$meta:meta])* + $variant:ident($storage:ident $payload:ty) + ),* $(,)?) => { + // SAFETY: `base` points to this live entry's `UnsafeHeapData`. + match unsafe { &*base } { + $( + HeapData::$variant(value) => HeapReadOutput::$variant( + heap_read_value!($storage id, base, value, readers) + ), + )* + } + }; + } + + // SAFETY: Match on a shared reference (`&*base`) to read the discriminant without + // creating a Unique retag. The shared retag is compatible with existing + // SharedReadWrite permissions from prior `read()` calls into the same UnsafeCell. + // The `heap_read` helper then derives the NonNull from `base` (not from `&T`), + // so the returned pointer retains full SharedReadWrite permission. + crate::heap_data::heap_payloads!(read_heap_payload) + } +} + +/// A single entry inside the heap arena, storing refcount and payload. +/// +/// Hashing state lives on the per-type structs that benefit from it +/// ([`Str`], [`Bytes`], [`Tuple`], [`NamedTuple`], [`FrozenSet`] (via +/// `SetStorage`), [`Path`]). Cheap-to-hash types ([`Range`], [`Slice`], +/// dates etc.) recompute on demand. Unhashable types ([`List`], [`Dict`], +/// [`Set`]) return `None` from `py_hash` directly. None of these need +/// per-entry metadata. +/// +/// The `color` field encodes the entry's state for the trial-deletion cycle +/// collector (see [`CcColor`]). Outside of a running collection, every live +/// entry is either Black (uninteresting) or Purple (a cycle-root candidate +/// queued for investigation); Gray and White are transient states only seen +/// during [`Heap::collect_cycles`]. Cell-typed for symmetry with `refcount` +/// — every write goes through an `&mut Heap` path (`dec_ref` and the +/// collector's `mark_gray`/`scan`/`scan_black`). +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct HeapEntry { + #[serde(rename = "R")] + refcount: Cell, + /// Number of active `HeapRead` pointers into this entry's data. + /// + /// Incremented when `HeapReader::read` creates a `HeapRead`, decremented when + /// the `HeapRead` is dropped. `dec_ref` panics if it would free an entry that + /// still has active readers — this guarantees that `HeapRead` pointers remain + /// valid for as long as they exist. + #[serde(skip)] // should always be 0 during serde ops + readers: Cell, + /// The payload data + #[serde(rename = "D")] + data: UnsafeHeapData, + /// Cycle-collector color. See [`CcColor`]. + /// + /// Round-trips through serde because a snapshot taken between bytecode + /// instructions can capture entries in the [`Purple`](CcColor::Purple) + /// pending-collection state; dropping the color on restore would leak + /// any cycle that became unreachable just before the snapshot. + #[serde(rename = "C")] + color: Cell, +} + +/// What one heap entry costs, payload and bookkeeping together. +/// +/// For preflighting a burst of allocations whose count is caller-controlled: +/// charging only the payloads would under-count by the refcount, reader count +/// and collector colour every entry also carries. +pub(crate) const HEAP_ENTRY_SIZE: usize = size_of::(); + +/// This wrapper containing `UnsafeCell` exists to allow for data inside of `HeapValue` +/// to be safely pointed to via the `HeapReader` API. +/// +/// The safety invariants are protected by the `Heap` / `HeapReader` API: +/// - It is never possible to alias mutable and immutable borrows into heap values, +/// whether they are the same or different value. +/// - When a mutable borrow of a heap value exists, no other heap value may be +/// borrowed. (See `Heap::get_mut` and `HeapRead::get`, which both require a `&mut` +/// borrow on the heap.) +struct UnsafeHeapData(UnsafeCell); + +impl fmt::Debug for UnsafeHeapData { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // SAFETY: (DH) Debug formatting is read-only and never called concurrently + // with mutation. This matches the safety invariants of the HeapReader API. + let data = unsafe { &*self.0.get() }; + f.debug_tuple("UnsafeHeapData").field(data).finish() + } +} + +impl serde::Serialize for UnsafeHeapData { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + // SAFETY: when heap data is being serialized, there is no mutable borrow + // possible on any data contents + HeapData::serialize(unsafe { &*self.0.get() }, serializer) + } +} + +impl<'de> serde::Deserialize<'de> for UnsafeHeapData { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + Ok(Self(UnsafeCell::new(HeapData::deserialize(deserializer)?))) + } +} + +/// Reference-counted arena that backs all heap-only runtime values. +/// +/// Uses a free list to reuse slots from freed values, keeping memory usage +/// constant for long-running loops that repeatedly allocate and free values. +/// When an value is freed via `dec_ref`, its slot ID is added to the free list. +/// New allocations pop from the free list when available, otherwise append. +/// +/// Cycle collection uses Bacon–Rajan trial deletion: candidates come from +/// `dec_ref` (every container whose refcount drops to a non-zero value is +/// flagged [`Purple`](CcColor::Purple)), so the VM does not enumerate live +/// roots — refcount math itself proves reachability and values held only on +/// the Rust stack are correctly preserved by their non-zero refcount. +/// +/// Owns the [`ResourceTracker`] that enforces memory/time limits and schedules +/// GC; unconfigured limits reduce every check to a single predictable branch. +#[derive(Debug)] +pub(crate) struct Heap { + /// Paged storage for heap entries with integrated free list. + entries: StableHeap, + /// Resource tracker for enforcing limits and scheduling GC. + pub tracker: ResourceTracker, + /// Number of entries currently flagged [`Purple`](CcColor::Purple) — i.e., + /// suspected cycle roots awaiting collection. + /// + /// Used as an early-out: when zero, `collect_cycles` has no candidates + /// and skips its heap walk entirely. The actual GC *frequency* is still + /// driven by `allocations_since_gc` against the configured interval, so + /// programs that produce no cycle candidates pay no collector cost + /// regardless of how many allocations they perform. + /// + /// All `dec_ref` paths that mutate this counter take `&mut self`, so a + /// plain `usize` is sufficient (no interior mutability needed). + purple_count: usize, + /// Number of GC-applicable allocations since the last cycle collection. + /// + /// Incremented for every GC-tracked allocation (see [`HeapData::is_gc_tracked`]) + /// and reset to zero at the end of every successful [`collect_cycles`] + /// call. Combined with [`purple_count`](Self::purple_count) to gate + /// automatic collections in [`should_gc`](Self::should_gc). + /// + /// Uses `Cell` for interior mutability so that `allocate(&self)` can + /// increment. + allocations_since_gc: Cell, + /// When true, [`should_gc`](Self::should_gc) returns false regardless of + /// the candidate count, suppressing automatic cycle-collection passes. + /// Toggled by the `gc.disable()` / `gc.enable()` Python helpers (only + /// registered under the `test-hooks` feature). Explicit `gc.collect()` + /// calls still run. + #[cfg(feature = "test-hooks")] + gc_disabled: bool, + /// Cached HeapId for the `datetime.timezone.utc` singleton. + /// + /// Lazily allocated on first access to `timezone.utc`. Once created, the refcount + /// is incremented on each access so the caller can drop their reference normally. + timezone_utc: Option, + /// Owned references to the session's `decimal` contexts, indexed by [`DecimalSlot`]. + /// + /// Created lazily by `types::decimal::py_context`. Kept here rather than on the VM so the + /// current context outlives each VM, as the heap does across REPL feeds and dumps. + decimal_contexts: [Option; DecimalSlot::COUNT], + /// Live external functions indexed by name without owning heap references. + /// + /// Uses `BTreeMap` to avoid large residual capacity from spikes of `ExtFunction` allocations. + ext_function_cache: BTreeMap, HeapId>, + /// Live sandbox classes and instances by boundary uuid, so a value the host + /// hands back resolves to the original object. Weak like + /// `ext_function_cache`: cleared when the object is freed, rebuilt on restore. + boundary_index: BTreeMap, + /// Live host class type objects by class uuid — one `HostClassType` entry + /// per host class, shared by its instances and `type(x)`. Separate from + /// `boundary_index` because host and sandbox uuids are distinct namespaces. + /// Weak like the others: cleared on free, rebuilt on restore. + host_type_index: BTreeMap, +} + +impl serde::Serialize for Heap { + fn serialize(&self, serializer: S) -> Result { + let mut state = serializer.serialize_struct("Heap", 6)?; + state.serialize_field("entries", &self.entries)?; + state.serialize_field("tracker", &self.tracker)?; + state.serialize_field("purple_count", &self.purple_count)?; + state.serialize_field("allocations_since_gc", &self.allocations_since_gc.get())?; + state.serialize_field("timezone_utc", &self.timezone_utc)?; + state.serialize_field("decimal_contexts", &self.decimal_contexts)?; + state.end() + } +} + +impl<'de> serde::Deserialize<'de> for Heap { + fn deserialize>(deserializer: D) -> Result { + #[derive(serde::Deserialize)] + struct HeapFields { + entries: StableHeap, + tracker: ResourceTracker, + purple_count: usize, + allocations_since_gc: u32, + timezone_utc: Option, + #[serde(default)] + decimal_contexts: [Option; DecimalSlot::COUNT], + } + let fields = HeapFields::deserialize(deserializer)?; + let mut entries = fields.entries; + let WeakIndexes { + ext_function_cache, + boundary_index, + host_type_index, + } = restore_entries(&mut entries).map_err(D::Error::custom)?; + Ok(Self { + entries, + tracker: fields.tracker, + purple_count: fields.purple_count, + allocations_since_gc: Cell::new(fields.allocations_since_gc), + #[cfg(feature = "test-hooks")] + gc_disabled: false, + timezone_utc: fields.timezone_utc, + decimal_contexts: fields.decimal_contexts, + ext_function_cache, + boundary_index, + host_type_index, + }) + } +} + +/// Rebuilds weak indexes and rejects transient GC states before the heap can be used. +/// +/// Snapshots are trusted for correctness, but must remain memory-safe even when invalid. +/// Gray/White entries would bypass parts of marking/scanning, on which the collector's +/// protection of live `HeapRead` pointers depends. Collection cannot suspend in these states. +fn restore_entries(entries: &mut StableHeap) -> Result { + let mut indexes = WeakIndexes::default(); + for index in 0..entries.len() { + let id = HeapId::from_index(index); + let Some(mut entry) = entries.entry(id) else { + continue; + }; + if matches!(entry.color.get(), CcColor::Gray | CcColor::White) { + return Err("snapshot contains a transient GC color"); + } + match entry.get_mut().data.0.get_mut() { + HeapData::ExtFunction(function) => { + indexes.ext_function_cache.insert(function.cache_key(), id); + } + HeapData::Instance(instance) => { + indexes.index_boundary_uuid(instance.uuid(), id); + } + HeapData::Class(class) => { + indexes.index_boundary_uuid(class.uuid(), id); + } + HeapData::HostClassType(ty) => { + indexes.host_type_index.insert(ty.type_id(), id); + } + _ => {} + } + } + Ok(indexes) +} + +/// A freed object's key in one of the heap's weak indexes. +enum WeakIndexKey { + ExtFunction(Arc), + Boundary(MontyUuid), + HostType(MontyUuid), +} + +/// The heap's weak (non-owning) indexes, rebuilt from the entries on restore. +#[derive(Default)] +struct WeakIndexes { + ext_function_cache: BTreeMap, HeapId>, + boundary_index: BTreeMap, + host_type_index: BTreeMap, +} + +impl WeakIndexes { + /// Indexes `id` under `uuid` when the object has one (it has crossed to the host). + fn index_boundary_uuid(&mut self, uuid: Option, id: HeapId) { + if let Some(uuid) = uuid { + self.boundary_index.insert(uuid, id); + } + } +} + +/// GC interval when the resource tracker sets none: [`DEFAULT_GC_INTERVAL`]. +/// +/// The trial-deletion collector additionally short-circuits the trace when +/// `purple_count == 0`, so programs that produce no cycle candidates pay no +/// collector cost regardless of their allocation rate. +/// +/// When the `memory-model-checks` feature is enabled, this is reduced to 1 to +/// stress-test GC behavior on every allocation. +const GC_INTERVAL: usize = if cfg!(feature = "memory-model-checks") { + 1 +} else { + DEFAULT_GC_INTERVAL +}; + +impl Heap { + /// Creates a new heap with the given resource tracker. + /// + /// Use this to create heaps with custom resource limits or GC scheduling. + pub fn new(capacity: usize, tracker: ResourceTracker) -> Self { + let this = Self { + entries: StableHeap::with_capacity(capacity), + tracker, + purple_count: 0, + allocations_since_gc: Cell::new(0), + #[cfg(feature = "test-hooks")] + gc_disabled: false, + timezone_utc: None, + decimal_contexts: [None; DecimalSlot::COUNT], + ext_function_cache: BTreeMap::new(), + boundary_index: BTreeMap::new(), + host_type_index: BTreeMap::new(), + }; + + // The empty-tuple singleton starts with refcount = 1 — that single ref *is* the + // permanent heap-owned reference. `get_empty_tuple` bumps the refcount on each + // hand-out so callers can `dec_ref` normally; the heap-owned ref keeps the + // singleton's rc ≥ 1 forever, which is why trial deletion needs no special-case + // rooting for it (a debug_assert in `dec_ref` enforces the invariant). + let empty_tuple = HeapData::Tuple(Tuple::default()); + let new_entry = HeapEntry { + refcount: Cell::new(1), + readers: Cell::new(0), + data: UnsafeHeapData(UnsafeCell::new(empty_tuple)), + color: Cell::new(CcColor::Black), + }; + + let empty_tuple = this.entries.allocate(new_entry); + debug_assert_eq!(empty_tuple, EMPTY_TUPLE_ID); + this + } + + /// The ids of the live entries `keep` accepts, in index order, for a one-off + /// pass over a loaded heap (`dump_upgrade`). + pub(crate) fn ids_where(&mut self, keep: impl Fn(&HeapData) -> bool) -> Vec { + (0..self.entries.len()) + .map(HeapId::from_index) + .filter(|&id| { + self.entries + .entry(id) + .is_some_and(|mut entry| keep(entry.get_mut().data.0.get_mut())) + }) + .collect() + } + + /// Number of entries in the heap (including freed slots). + pub fn size(&self) -> usize { + self.entries.len() + } + + /// Returns the number of GC-tracked allocations since the last cycle + /// collection. Reset to zero by [`collect_cycles`](Self::collect_cycles). + /// + /// Used by `run_ref_counts` to expose the GC trigger metric to tests: + /// a value much smaller than the configured `gc_interval` after many + /// allocations is evidence that collection ran. + #[cfg(feature = "ref-count-return")] + pub fn get_allocations_since_gc(&self) -> u32 { + self.allocations_since_gc.get() + } + + /// Allocates a new heap entry. + /// + /// GC-tracked types bump `allocations_since_gc` so that + /// [`should_gc`](Self::should_gc) eventually fires; trial deletion's own + /// candidate enrollment happens later, at `dec_ref` time. Leaf types + /// (strings, bytes, …) cannot participate in cycles and don't count + /// against the GC interval. + pub fn allocate(&self, data: HeapData) -> HeapId { + self.entries.allocate(self.new_entry(data)) + } + + /// Builds the initialized entry shared by typed and untyped allocation. + fn new_entry(&self, data: HeapData) -> HeapEntry { + if data.is_gc_tracked() { + self.allocations_since_gc + .set(self.allocations_since_gc.get().wrapping_add(1)); + } + + HeapEntry { + refcount: Cell::new(1), + readers: Cell::new(0), + data: UnsafeHeapData(UnsafeCell::new(data)), + color: Cell::new(CcColor::Black), + } + } + + /// Returns the singleton empty tuple. + /// + /// In Python, `() is ()` is always `True` because empty tuples are interned. + /// This method provides the same optimization by returning the same `HeapId` + /// for all empty tuple allocations. + /// + /// The returned `Value` has its reference count incremented, so the caller + /// owns a reference and must call `dec_ref` when done. + pub fn get_empty_tuple(&self) -> Value { + // Return existing singleton with incremented refcount + self.inc_ref(EMPTY_TUPLE_ID); + Value::Ref(EMPTY_TUPLE_ID) + } + + /// Returns the external function for `name`, reusing a live object when possible. + /// + /// The cache holds no reference count of its own. Its entry is removed when the + /// last owning reference is dropped, before the heap slot can be reused. + pub fn get_ext_function(&mut self, name: &str) -> Value { + if let Some(id) = self.ext_function_cache.get(name).copied() { + self.inc_ref(id); + Value::Ref(id) + } else { + let function = ExtFunction::new(name); + let cache_key = function.cache_key(); + let id = self.allocate(HeapData::ExtFunction(function)); + let previous = self.ext_function_cache.insert(cache_key, id); + debug_assert!(previous.is_none()); + Value::Ref(id) + } + } + + /// Removes `id` from the weak cache without disturbing a duplicate-name winner. + fn remove_ext_function_cache_entry(cache: &mut BTreeMap, HeapId>, name: &str, id: HeapId) { + if cache.get(name) == Some(&id) { + cache.remove(name); + } + } + + /// The key `data` holds in a weak index, read before its slot is freed so + /// the index entry can be cleared (see [`Heap::remove_weak_index_entry`]). + fn weak_index_key(data: &HeapData) -> Option { + match data { + HeapData::ExtFunction(function) => Some(WeakIndexKey::ExtFunction(function.cache_key())), + HeapData::Instance(instance) => instance.uuid().map(WeakIndexKey::Boundary), + HeapData::Class(class) => class.uuid().map(WeakIndexKey::Boundary), + HeapData::HostClassType(ty) => Some(WeakIndexKey::HostType(ty.type_id())), + _ => None, + } + } + + /// Clears the weak index entry for the object at `id` before its slot can + /// be reused, only if the entry still points at this exact object (a + /// restored dump may hold duplicates). + fn remove_weak_index_entry(&mut self, key: Option, id: HeapId) { + match key { + Some(WeakIndexKey::ExtFunction(name)) => { + Self::remove_ext_function_cache_entry(&mut self.ext_function_cache, &name, id); + } + Some(WeakIndexKey::Boundary(uuid)) if self.boundary_index.get(&uuid) == Some(&id) => { + self.boundary_index.remove(&uuid); + } + Some(WeakIndexKey::HostType(uuid)) if self.host_type_index.get(&uuid) == Some(&id) => { + self.host_type_index.remove(&uuid); + } + Some(WeakIndexKey::Boundary(_) | WeakIndexKey::HostType(_)) | None => {} + } + } + + /// Boundary uuid of the sandbox class or instance at `id`, generated and + /// indexed on its first crossing to the host so the host can hand the + /// object back by id (see [`Heap::resolve_boundary_uuid`]). + /// + /// # Panics + /// If `id` is not a live `Instance` or `Class` entry. + pub(crate) fn boundary_uuid(&mut self, id: HeapId) -> MontyUuid { + let mut entry = self + .entries + .entry(id) + .expect("Heap::boundary_uuid: entry already freed"); + let uuid = match entry.get_mut().data.0.get_mut() { + HeapData::Instance(instance) => instance.boundary_uuid(), + HeapData::Class(class) => class.boundary_uuid(), + _ => unreachable!("Heap::boundary_uuid: only classes and instances carry a boundary uuid"), + }; + self.boundary_index.insert(uuid, id); + uuid + } + + /// The live sandbox class or instance that crossed to the host as `uuid`, + /// if it still exists; the index holds no reference, so the returned id is + /// borrowed. + #[must_use] + pub(crate) fn resolve_boundary_uuid(&self, uuid: &MontyUuid) -> Option { + self.boundary_index.get(uuid).copied() + } + + /// The live type object for the host class `uuid`, if the sandbox holds + /// one; the index owns no reference, so the returned id is borrowed. + #[must_use] + pub(crate) fn resolve_host_type(&self, uuid: &MontyUuid) -> Option { + self.host_type_index.get(uuid).copied() + } + + /// Allocates and indexes the type object for a host class the sandbox has + /// not seen yet; callers must check [`Heap::resolve_host_type`] first so + /// the one-entry-per-class invariant holds. + pub(crate) fn allocate_host_type(&mut self, ty: HostClassType) -> HeapId { + let uuid = ty.type_id(); + let id = self.allocate(HeapData::HostClassType(Box::new(ty))); + let previous = self.host_type_index.insert(uuid, id); + debug_assert!( + previous.is_none(), + // bashkit fork: no uuid in the message (CodeQL cleartext-logging false positive). + "Heap::allocate_host_type: class already has a type object" + ); + id + } + + /// Returns the cached `datetime.timezone.utc` singleton, lazily creating it on first access. + /// + /// The returned `Value::Ref` has its refcount incremented so the caller can drop + /// it normally. The singleton itself is kept alive by the `timezone_utc` field. + pub fn get_timezone_utc(&mut self) -> Value { + if let Some(id) = self.timezone_utc { + self.inc_ref(id); + Value::Ref(id) + } else { + let tz = TimeZone::utc(); + let id = self.allocate(HeapData::TimeZone(tz)); + // Keep an extra refcount for the singleton cache + self.inc_ref(id); + self.timezone_utc = Some(id); + Value::Ref(id) + } + } + + /// The heap-owned `decimal` context in `slot`, if it has been created. + /// + /// The id is borrowed: callers handing it out as a `Value` must `inc_ref` it. + pub(crate) fn decimal_context(&self, slot: DecimalSlot) -> Option { + self.decimal_contexts[slot as usize] + } + + /// Stores an owned reference to a `decimal` context in `slot`, returning the owned + /// reference it replaces for the caller to release (callers may hold heap readers). + #[must_use] + pub(crate) fn replace_decimal_context(&mut self, slot: DecimalSlot, id: HeapId) -> Option { + self.decimal_contexts[slot as usize].replace(id) + } + + /// Increments the reference count for an existing heap entry. + /// + /// # Panics + /// Panics if the value ID is invalid or the value has already been freed. + pub fn inc_ref(&self, id: HeapId) { + let value = self.entries.get(id); + value.refcount.update(|r| r + 1); + } + + /// Decrements the reference count and frees the value (plus children) once it hits zero. + /// + /// This is the low-level release operation for an owned raw `HeapId`. Ordinary + /// control flow should instead keep local ownership in `Value::Ref` and use + /// `defer_drop!` or `DropGuard`. Heap-stored owners declare child references in + /// `HeapItem::py_dec_ref_ids`; direct calls are appropriate in cleanup for other + /// structures that own raw IDs. + /// + /// Uses an iterative work stack instead of recursion to avoid Rust stack overflow + /// when freeing deeply nested containers (e.g., a list nested 10,000 levels deep). + /// This is analogous to CPython's "trashcan" mechanism for safe deallocation. + /// + /// Implements the candidate-enrollment side of Bacon–Rajan trial deletion: any + /// GC-tracked entry whose refcount survives the decrement gets flagged + /// [`Purple`](CcColor::Purple), so the next [`collect_cycles`](Self::collect_cycles) + /// can investigate it. Entries that drop to zero are freed immediately on the + /// existing fast path; if such an entry was Purple, the heap-wide + /// `purple_count` is rebalanced so it stays in sync with the actual number + /// of Purple entries. + /// + /// # Panics + /// Panics if the value ID is invalid, the value has already been freed, or + /// the refcount would reach zero while active `HeapRead` readers exist. + pub fn dec_ref(&mut self, id: HeapId) { + HeapReader::with(self, &mut (), |reader, ()| { + let mut current_id = id; + // A fresh Vec is deliberate: it costs nothing unless children are + // actually pushed, whereas pooling it on the Heap was measured + // (CodSpeed, PR #536) to add take/restore traffic to every call. + let mut work_stack = Vec::new(); + loop { + // Using `HeapPtr` avoids the possibility of aliasing with live borrows + // held by `HeapRead` handles. + let ptr = reader.read_ptr(current_id); + let heap_entry = ptr.entry(reader); + if heap_entry.refcount.get() > 1 { + heap_entry.refcount.update(|r| r - 1); + + let is_gc_tracked = ptr.data(reader).is_gc_tracked(); + if is_gc_tracked && heap_entry.color.get() != CcColor::Purple { + // The refcount survived — a newly unreachable cycle could + // now be hiding. Flag it as a candidate for the next `collect_cycles`. + heap_entry.color.set(CcColor::Purple); + reader.heap.purple_count += 1; + } + } else { + debug_assert!( + current_id != EMPTY_TUPLE_ID, + "Heap::dec_ref: empty-tuple singleton's heap-owned refcount must never reach zero", + ); + assert!( + heap_entry.readers.get() == 0, + "Heap::dec_ref: cannot free HeapId({}) with {} active reader(s)", + current_id.index(), + heap_entry.readers.get(), + ); + // If the entry was a pending cycle candidate, decrement + // `purple_count` to reflect that it is leaving the heap before + // the collector reaches it. + if heap_entry.color.get() == CcColor::Purple { + reader.heap.purple_count -= 1; + } + // Remove weak-index entries before the slot becomes available for reuse. + let weak_key = Self::weak_index_key(ptr.data(reader)); + reader.heap.remove_weak_index_entry(weak_key, current_id); + + // It is not possible to free from `HeapPtr` because it is created through + // a &self borrow on `StableHeap`. At least this repeated lookup is already + // on the slow path. + let mut value = reader.heap.entries.entry(current_id).expect("already looked up").free(); + + // Collect child IDs and push onto work stack for iterative processing + py_dec_ref_ids_for_data(value.data.0.get_mut(), &mut work_stack); + } + + let Some(next_id) = work_stack.pop() else { + break; + }; + current_id = next_id; + } + }); + } + + /// Returns an immutable reference to the heap data stored at the given ID. This can be more efficient + /// than `.read()` for short-lived borrows that need read-only access (avoids reader bookkeeping). + /// + /// # Panics + /// Panics if the value ID is invalid, the value has already been freed, + /// or the data is currently borrowed via `with_entry_mut`/`call_attr`. + #[must_use] + pub fn get(&self, id: HeapId) -> &HeapData { + let data = &self.entries.get(id).data; + // SAFETY: (DH) no mutable references into `HeapData` is possible while the heap is borrowed + unsafe { &*data.0.get() } + } + + /// Returns the reference count for the heap entry at the given ID. + /// + /// This is primarily used for testing reference counting behavior. + /// + /// # Panics + /// Panics if the value ID is invalid or the value has already been freed. + #[must_use] + #[cfg(feature = "ref-count-return")] + pub fn get_refcount(&self, id: HeapId) -> usize { + self.entries.get(id).refcount.get() + } + + /// Returns the number of live (non-freed) values on the heap. + /// + /// This is primarily used for testing to verify that all heap entries + /// are accounted for in reference count tests. + /// + /// Excludes the empty tuple singleton since it's an internal optimization + /// detail that persists even when not explicitly used by user code. + #[must_use] + #[cfg(feature = "ref-count-return")] + pub fn entry_count(&self) -> usize { + // Skip index 0 which is the empty tuple singleton + self.entries.iter().skip(1).count() + } + + /// Returns whether cycle collection should run. + /// + /// True when the configured allocation interval has elapsed *and* at + /// least one [`Purple`](CcColor::Purple) candidate is pending. The + /// alloc-count check sets the maximum collector frequency the user + /// asked for; the `purple_count` check is an additional early-out so + /// programs that produce no cycle candidates pay no collector cost + /// regardless of their allocation rate. + /// + /// Always returns false when [`disable_gc`](Self::disable_gc) has been + /// called without a matching [`enable_gc`](Self::enable_gc); explicit + /// [`collect_cycles`](Self::collect_cycles) calls still run regardless. + #[inline] + pub fn should_gc(&self) -> bool { + #[cfg(feature = "test-hooks")] + if self.gc_disabled { + return false; + } + if self.purple_count == 0 { + return false; + } + let interval = self.tracker.gc_interval().unwrap_or(GC_INTERVAL); + (self.allocations_since_gc.get() as usize) >= interval + } + + /// Suppresses automatic garbage collection until [`enable_gc`](Self::enable_gc) + /// is called. + /// + /// Explicit [`collect_cycles`](Self::collect_cycles) calls still run while + /// disabled, so a script can build a known amount of garbage and then time + /// exactly one collection pass. + #[cfg(feature = "test-hooks")] + pub fn disable_gc(&mut self) { + self.gc_disabled = true; + } + + /// Resumes automatic garbage collection after a prior [`disable_gc`](Self::disable_gc). + /// + /// Calling [`enable_gc`](Self::enable_gc) on an already-enabled heap is a no-op. + #[cfg(feature = "test-hooks")] + pub fn enable_gc(&mut self) { + self.gc_disabled = false; + } + + /// Runs Bacon–Rajan trial-deletion cycle collection. + /// + /// Walks every entry currently flagged [`Purple`](CcColor::Purple) (the + /// candidates accumulated by `dec_ref`) and frees any references that turn + /// out to live entirely inside an unreachable cycle. Refcount math itself + /// proves liveness — entries reachable from outside the candidate set + /// (including those held only on the Rust stack and those with active + /// `HeapRead` readers) survive automatically because their refcount or + /// reader count remains non-zero — so no explicit root walk is required. + /// + /// Phases: + /// + /// 1. **`MarkRoots`** — single linear pass over `entries` that finds + /// Purple entries, runs `MarkGray` on each, and collects the resulting + /// seed list. Purple entries reached transitively by an earlier seed's + /// `MarkGray` turn Gray and are correctly skipped, so each cycle root + /// is only seeded once. + /// 2. **`Scan`** — for each seed, decide whether the subtree is alive + /// (`s.refcount > 0 || s.readers > 0`, resurrect to Black) or condemned + /// (mark White and recurse). + /// 3. **`CollectWhite`** — free White entries iteratively. Child + /// refcounts were already balanced by `MarkGray`/`ScanBlack`, so this + /// phase does **not** call `dec_ref` on children — it only walks them + /// to free transitively. + /// + /// All four phases iterate via explicit work stacks instead of recursion + /// (the textbook formulation is recursive); a 10 000-deep nested cycle + /// must collect without a Rust stack overflow. + /// + /// Returns the number of unreachable entries that were freed during the sweep. + /// + /// # Caller Responsibility + /// The caller should check [`should_gc`](Self::should_gc) before calling + /// this method. With `purple_count == 0` the function returns immediately + /// without touching the heap. + pub fn collect_cycles(&mut self) -> usize { + if self.purple_count == 0 { + return 0; + } + // The mark/scan phases work in terms of `HeapPtr<'a>` to avoid re-indexing + // paged storage on every entry access; the brand `'a` comes from the + // surrounding `HeapReader::with` scope. + HeapReader::with(self, &mut (), |reader, ()| reader.collect_cycles_inner()) + } + + fn collect_white(&mut self, roots: Vec) -> usize { + let mut work_stack = roots; + let mut freed = 0; + while let Some(id) = work_stack.pop() { + let Some(mut entry) = self.entries.entry(id) else { + // Already freed via another seed's traversal — ignore. + continue; + }; + let heap_entry = entry.get_mut(); + if heap_entry.color.get() != CcColor::White { + // Either resurrected to Black by `Scan` or never visited + // (still Black/Gray from somewhere). Don't free. + continue; + } + debug_assert!( + heap_entry.readers.get() == 0, + "collect_white: cannot free HeapId({}) with {} active reader(s)", + id.index(), + heap_entry.readers.get(), + ); + let mut value = entry.free(); + // Clear weak entries before freeing their slots, just as `dec_ref`. + let weak_key = Self::weak_index_key(value.data.0.get_mut()); + self.remove_weak_index_entry(weak_key, id); + freed += 1; + // Walk children, marking child `Value::Ref`s as `Dereferenced` + // under `memory-model-checks` so dropping the freed entry's data + // doesn't trip a Drop-panic on a live `Value::Ref` payload. The + // pushed child IDs feed the work stack so we recursively walk + // White grandchildren — we do *not* `dec_ref` these children + // (`MarkGray`/`ScanBlack` already balanced their refcounts). + py_dec_ref_ids_for_data(value.data.0.get_mut(), &mut work_stack); + } + freed + } +} + +/// Cycle-collection inner phases. +/// +/// Implemented on [`HeapReader<'a>`] so the work stacks can carry +/// [`HeapPtr<'a>`] instead of [`HeapId`]: once an entry is reached, every +/// subsequent access is a pointer deref rather than a paged-storage lookup. +/// Entered only via [`Heap::collect_cycles`], which establishes the brand `'a` +/// through [`HeapReader::with`]. [`Heap::collect_white`] is intentionally kept +/// in `HeapId` space because freeing a slot requires consulting the free list, +/// which is keyed by id. +impl<'a> HeapReader<'a> { + /// Implementation of [`Heap::collect_cycles`]. Phase 1 (discover Purple + /// roots and `mark_gray` their subtrees), Phase 2 (`scan`), and Phase 3 + /// (`collect_white`) run sequentially. After `scan` the `HeapPtr` work + /// stack is drained, so no branded pointer escapes into Phase 3. + /// + /// Each phase iterates `for_each_child_id` inline rather than staging child + /// `HeapId`s through a scratch `Vec`. Mutation of entry fields goes through + /// the `Cell`/`UnsafeCell`-backed interior mutability on `HeapEntry`, so the + /// `&HeapEntry`/`&HeapData` borrows from [`HeapPtr::entry`]/[`HeapPtr::data`] + /// can coexist with the `&self.entry_ptr` calls in the closure body. + fn collect_cycles_inner(&mut self) -> usize { + let mut roots: Vec = Vec::new(); + let mut work_stack: Vec> = Vec::new(); + + // 1. Discover roots by finding Purple entries. Mark each root (and its subtree) Gray. + // The linear scan may legitimately encounter freed slots, so we use + // `try_entry` to skip them rather than panicking. + for i in 0..self.heap.entries.len() { + let id = HeapId(i); + let ptr = self.read_ptr(id); + let Some(entry) = ptr.try_entry(self) else { + continue; + }; + if entry.color.get() != CcColor::Purple { + continue; + } + if entry.readers.get() > 0 { + // This entry cannot possibly be a root since it has active readers; reset + // to Black so it won't be a candidate in the next cycle. + entry.color.set(CcColor::Black); + continue; + } + roots.push(id); + self.mark_gray(ptr, &mut work_stack); + debug_assert!(work_stack.is_empty(), "mark_gray must drain its work stack"); + } + + // 2. For each root, scan and resurrect if alive (refcount > 0 or active readers). + // Roots were live at Phase 1 and nothing has freed them between then and + // now, so `entry_ptr` returning `None` would indicate a bug. + work_stack.extend(roots.iter().map(|&id| self.read_ptr(id))); + self.scan(&mut work_stack); + debug_assert!(work_stack.is_empty(), "scan must drain its work stack"); + + // 3. Collect each root's White children as unreachable garbage. This phase + // keeps working in HeapId-space because `entry.free()` pushes to the + // free list, which is keyed by id. + let freed = self.heap.collect_white(roots); + + // After this pass no Purple entries remain in the heap; zero the + // counter so the next `dec_ref` event re-seeds from a clean baseline, + // and reset the alloc-count gate so the next interval starts now. + self.heap.purple_count = 0; + self.heap.allocations_since_gc.set(0); + freed + } + + /// `MarkGray` (iterative): paint `s` and its transitive children Gray, + /// decrementing each child's refcount once per traversal edge. + /// + /// After this completes for every root, every Gray entry's refcount equals + /// the count of *external* references into it (refs originating outside + /// the candidate subgraph). `Scan` uses that property to decide + /// alive/condemned. + fn mark_gray(&mut self, mut ptr: HeapPtr<'a>, work_stack: &mut Vec>) { + ptr.entry(self).color.set(CcColor::Gray); + loop { + for_each_child_id(ptr.data(self), |child_id| { + let child_ptr = self.read_ptr(child_id); + let entry = child_ptr.entry(self); + debug_assert!(entry.refcount.get() > 0, "mark_gray: refcount underflow"); + entry.refcount.update(|r| r - 1); + if entry.color.replace(CcColor::Gray) == CcColor::Gray { + // Already marked via another edge, don't push again + return; + } + work_stack.push(child_ptr); + }); + let Some(next_ptr) = work_stack.pop() else { + break; + }; + ptr = next_ptr; + } + } + + /// `Scan` (iterative): each Gray entry is either resurrected via + /// `ScanBlack` (external reference exists — refcount > 0 or active + /// `HeapRead` reader) or painted White and its Gray children recursed. + fn scan(&mut self, work_stack: &mut Vec>) { + let mut black_work_stack: Vec> = Vec::new(); + while let Some(ptr) = work_stack.pop() { + let entry = ptr.entry(self); + if entry.color.get() != CcColor::Gray { + // Already processed via another edge + continue; + } + if entry.refcount.get() == 0 && entry.readers.get() == 0 { + entry.color.set(CcColor::White); + for_each_child_id(ptr.data(self), |child_id| { + let child_ptr = self.read_ptr(child_id); + let entry = child_ptr.entry(self); + if entry.color.get() != CcColor::Gray { + // Already processed via another edge + return; + } + work_stack.push(child_ptr); + }); + } else { + // External reference exists (either a refcount we couldn't + // account for inside the candidate set, or a live `HeapRead` + // pointing into the entry). Resurrect this entry and its + // transitive Gray children back to Black via `mark_black`. + self.mark_black(ptr, &mut black_work_stack); + debug_assert!(black_work_stack.is_empty()); + } + } + } + + /// `ScanBlack` (iterative): resurrect a subtree by re-incrementing + /// children's refcounts that `MarkGray` previously decremented, restoring + /// the heap to the state it would have had if no cycle was suspected. + /// + /// Children's refcounts are incremented once per traversal edge — even if + /// the child is already Black — so multi-edge graphs (a child reachable + /// from two parents in the resurrected subtree) balance the matching + /// per-edge decrements `MarkGray` performed. Recursion only descends into + /// non-Black children so each entry is processed at most once. + fn mark_black(&mut self, mut ptr: HeapPtr<'a>, work_stack: &mut Vec>) { + ptr.entry(self).color.set(CcColor::Black); + loop { + for_each_child_id(ptr.data(self), |child_id| { + let child_ptr = self.read_ptr(child_id); + let entry = child_ptr.entry(self); + entry.refcount.update(|r| r + 1); + if entry.color.replace(CcColor::Black) == CcColor::Black { + // Already marked via another edge + return; + } + work_stack.push(child_ptr); + }); + let Some(next_ptr) = work_stack.pop() else { + break; + }; + ptr = next_ptr; + } + } +} + +/// Leak detection for reference-counting tests. +/// +/// Implemented on [`HeapReader`] because reading an entry's children needs +/// [`HeapPtr::data`]. It borrows the cycle collector's [`for_each_child_id`] to +/// walk edges but is not part of collection: nothing here mutates the heap, and +/// it is reached only from `run_ref_counts`, never from [`Heap::collect_cycles`]. +#[cfg(feature = "ref-count-return")] +impl HeapReader<'_> { + /// Returns live heap entries unreachable from `roots`, with each entry's type + /// so callers holding `Interns` can name it ([`Type::name`]). + /// + /// `run_ref_counts` uses this to prove a test leaked nothing: an entry that + /// is alive but reachable from no named variable is a missed `drop_with`. + /// The walk is transitive, so an object owned by another object — a class's + /// `__annotations__`, a nested list, an instance attribute — is accounted + /// for by its owner and need not be bound to a name by the test itself. + /// + /// Unlike the cycle collector's [`mark_gray`](Self::mark_gray) this touches + /// no colors or refcounts, so it cannot perturb the state under test. + pub(crate) fn unreachable_entries(&self, roots: impl IntoIterator) -> Vec<(HeapId, Type)> { + let mut seen: HashSet = HashSet::new(); + let mut work_stack: Vec = Vec::new(); + // The heap owns the session's decimal contexts, so they are live without a name. + let held = self.decimal_contexts.iter().flatten().copied(); + for root in roots.into_iter().chain(held) { + if seen.insert(root) { + work_stack.push(root); + } + } + + // A root's subtree is live by construction, but `try_entry` keeps the + // walk total in case a test observes the heap mid-teardown. + while let Some(id) = work_stack.pop() { + let ptr = self.read_ptr(id); + if ptr.try_entry(self).is_none() { + continue; + } + for_each_child_id(ptr.data(self), |child_id| { + if seen.insert(child_id) { + work_stack.push(child_id); + } + }); + } + + self.entries + .iter() + // The empty tuple singleton is an internal optimisation that is + // always live and never named, so it is not a leak. See `entry_count`. + .filter(|(id, _)| *id != EMPTY_TUPLE_ID && !seen.contains(id)) + .map(|(id, _)| (id, self.read_ptr(id).data(self).py_type())) + .collect() + } +} + +// With `memory-model-checks` enabled, need to manually clean up the heap to avoid the +// bookkeeping causing panics at shutdown. +#[cfg(feature = "memory-model-checks")] +impl Drop for Heap { + fn drop(&mut self) { + for id in 0..self.entries.len() { + if let Some(mut entry) = self.entries.entry(HeapId::from_index(id)) { + // Mark all `Value::Ref` payloads as `Dereferenced` so they don't panic when dropped + py_dec_ref_ids_for_data(entry.get_mut().data.0.get_mut(), &mut Vec::new()); + entry.free(); + } + } + } +} + +/// Walks the GC-relevant children of a `HeapData` value and calls `on_child` +/// for each contained `HeapId`. +/// +/// The cycle collector's mark/scan phases use this directly, combining the +/// child-id iteration with a `HeapId → HeapPtr` conversion in the closure +/// body — that's why this is closure-shaped rather than producing a `Vec`. +/// [`py_dec_ref_ids_for_data`] mirrors the same match arms for the +/// freeing/decref paths; the two must stay in sync. +fn for_each_child_id(data: &HeapData, mut on_child: F) { + match data { + HeapData::List(list) => { + // Skip iteration if no refs - major GC optimization for lists of primitives + if !list.contains_refs() { + return; + } + for value in list.as_slice() { + if let Value::Ref(id) = value { + on_child(*id); + } + } + } + // MUST report exactly the same ids as `Deque::py_dec_ref_ids` — reporting + // fewer leaks, reporting more is a use-after-free. + HeapData::Deque(deque) => { + if !deque.contains_refs() { + return; + } + for value in deque.iter() { + if let Value::Ref(id) = value { + on_child(*id); + } + } + } + HeapData::Tuple(tuple) => { + // Skip iteration if no refs - GC optimization for tuples of primitives + if !tuple.contains_refs() { + return; + } + for value in tuple.as_slice() { + if let Value::Ref(id) = value { + on_child(*id); + } + } + } + HeapData::NamedTuple(nt) => { + // Report the owned reference to the class object (factory instances + // only) before the `contains_refs` early-out — that flag is computed + // from `items` alone, so an all-primitive instance like `Point(1, 2)` + // still has a live class edge. MUST report exactly the same ids as + // `NamedTuple::py_dec_ref_ids`. + if let Some(class_id) = nt.class_id() { + on_child(class_id); + } + // Skip iteration if no refs - GC optimization for namedtuples of primitives + if !nt.contains_refs() { + return; + } + for value in nt.as_vec() { + if let Value::Ref(id) = value { + on_child(*id); + } + } + } + // A namedtuple *class* owns its default values and its `__module__`. + // MUST report the same ids as `NamedTupleClass::py_dec_ref_ids`. + HeapData::NamedTupleClass(class) => { + if !class.contains_refs() { + return; + } + for value in class.defaults().iter().chain(once(class.module())) { + if let Value::Ref(id) = value { + on_child(*id); + } + } + } + HeapData::Dict(dict) => { + // Report the default_factory (a defaultdict with a heap-ref factory, + // e.g. a lambda) before the `has_refs` early-out. MUST report exactly + // the same ids as `Dict::py_dec_ref_ids`: reporting fewer leaks, + // reporting more is a use-after-free. + if let Some(Value::Ref(id)) = dict.default_factory() { + on_child(*id); + } + // Skip iteration if no refs - major GC optimization for dicts of primitives + if !dict.has_refs() { + return; + } + for (k, v) in dict { + if let Value::Ref(id) = k { + on_child(*id); + } + if let Value::Ref(id) = v { + on_child(*id); + } + } + } + HeapData::DictKeysView(view) => { + on_child(view.dict_id()); + } + HeapData::DictItemsView(view) => { + on_child(view.dict_id()); + } + HeapData::DictValuesView(view) => { + on_child(view.dict_id()); + } + HeapData::Set(set) => { + for value in set.storage().iter() { + if let Value::Ref(id) = value { + on_child(*id); + } + } + } + HeapData::FrozenSet(frozenset) => { + for value in frozenset.storage().iter() { + if let Value::Ref(id) = value { + on_child(*id); + } + } + } + HeapData::Closure(closure) => { + // Add captured cells to work list + for cell_id in &closure.cells { + on_child(*cell_id); + } + // Add default values that are heap references + for default in &closure.defaults { + if let Value::Ref(id) = default { + on_child(*id); + } + } + if let Some(globals) = closure.globals { + on_child(globals); + } + } + HeapData::FunctionDefaults(fd) => { + // Add default values that are heap references + for default in &fd.defaults { + if let Value::Ref(id) = default { + on_child(*id); + } + } + if let Some(globals) = fd.globals { + on_child(globals); + } + } + HeapData::Cell(cell) => { + // Cell can contain a reference to another heap value + if let Value::Ref(id) = &cell.0 { + on_child(*id); + } + } + HeapData::HostClass(dc) => { + // The owned class entry, then the attrs Dict — MUST report exactly + // the same ids as `HostClass::py_dec_ref_ids`. + on_child(dc.class_id()); + for (k, v) in dc.attrs() { + if let Value::Ref(id) = k { + on_child(*id); + } + if let Value::Ref(id) = v { + on_child(*id); + } + } + } + HeapData::HostClassType(t) => { + // Eager class attrs can hold containers the sandbox can reach + // (`Klass.data`) and mutate to close a cycle back to this type + // object, so they must be traced like `HostClass` attrs. + for (k, v) in t.attrs() { + if let Value::Ref(id) = k { + on_child(*id); + } + if let Value::Ref(id) = v { + on_child(*id); + } + } + } + HeapData::Class(class) => { + // The class namespace holds method/class-variable values. + for (k, v) in class.namespace() { + if let Value::Ref(id) = k { + on_child(*id); + } + if let Value::Ref(id) = v { + on_child(*id); + } + } + } + HeapData::Instance(instance) => { + // An instance references its class plus its attribute dict's entries. + on_child(instance.class()); + for (k, v) in instance.attrs() { + if let Value::Ref(id) = k { + on_child(*id); + } + if let Value::Ref(id) = v { + on_child(*id); + } + } + } + HeapData::BoundMethod(bm) => { + if let Value::Ref(id) = &bm.instance { + on_child(*id); + } + if let Value::Ref(id) = &bm.func { + on_child(*id); + } + } + HeapData::DataclassField(field) => { + // A captured default or factory can reach back to the class the + // field belongs to (`x: object = SomeInstanceOfIt`, or a factory + // closure capturing the class), closing a cycle. + for value in field.ref_children() { + on_child(value); + } + } + HeapData::DataclassMethod(method) => { + // A generated `__init__` holds the captured defaults and factories, + // which can reach back to the class it lives in. + for id in method.ref_children() { + on_child(id); + } + } + HeapData::ListIterator(iter) => on_child(iter.list_id()), + HeapData::DequeIterator(iter) => on_child(iter.deque_id()), + HeapData::TupleIterator(iter) => on_child(iter.source_id()), + HeapData::StringIterator(iter) => { + if let Some(id) = iter.source_id() { + on_child(id); + } + } + HeapData::BytesIterator(iter) => { + if let Some(id) = iter.source_id() { + on_child(id); + } + } + HeapData::RangeIterator(_) => {} + HeapData::DictKeyIterator(iter) => on_child(iter.source_id()), + HeapData::DictItemIterator(iter) => on_child(iter.source_id()), + HeapData::DictValueIterator(iter) => on_child(iter.source_id()), + HeapData::SetIterator(iter) => on_child(iter.source_id()), + HeapData::CallableIterator(iter) => iter.for_each_child_id(on_child), + HeapData::DirScan(scan) => scan.for_each_child_id(on_child), + HeapData::Itertools(iter) => iter.for_each_child_id(on_child), + HeapData::Csv(csv) => csv.for_each_child_id(on_child), + HeapData::Partial(partial) => partial.for_each_child_id(on_child), + HeapData::GenericAlias(alias) => alias.for_each_child_id(on_child), + HeapData::Union(union) => union.for_each_child_id(on_child), + HeapData::LruCache(cache) => cache.for_each_child_id(on_child), + HeapData::Module(m) => { + // Module attrs can contain references to heap values + if !m.has_refs() { + return; + } + for (k, v) in m.attrs() { + if let Value::Ref(id) = k { + on_child(*id); + } + if let Value::Ref(id) = v { + on_child(*id); + } + } + } + HeapData::Coroutine(coro) => { + // Add namespace values that are heap references + for value in &coro.namespace { + if let Value::Ref(id) = value { + on_child(*id); + } + } + if let Some(globals) = coro.globals { + on_child(globals); + } + } + HeapData::GatherFuture(gather) => { + // Add inc_ref'd item HeapIds. Both coroutines and external + // futures are owned by the gather for its entire lifecycle. + for item in &gather.items { + on_child(*item); + } + // Walk per-state heap refs: in-flight slot results plus this + // gather's own awaiter (if `GatherSlot`, it owns an inc_ref on + // the outer gather), or the cached result list once the gather + // has completed successfully. `Pending` and `Failed` carry no + // heap refs. + match &gather.state { + GatherState::Awaited(awaited) => { + if let Awaiter::GatherSlot { gather, .. } = &awaited.awaiter { + on_child(*gather); + } + for result in awaited.results.iter().flatten() { + if let Value::Ref(id) = result { + on_child(*id); + } + } + } + GatherState::Completed(Value::Ref(id)) => on_child(*id), + GatherState::Pending | GatherState::Failed(_) | GatherState::Completed(_) => {} + } + } + HeapData::ExternalFuture(fut) => { + // `Pending { awaiter: Some(GatherSlot { gather, .. }) }` owns an + // inc_ref on `gather`. `Awaiter::Task` / `None` and the `Failed` + // state carry no heap refs. `Resolved` owns the cached value, and + // a pending sleep owns the `result` it will resolve with. + if let Some(Value::Ref(id)) = &fut.sleep_result { + on_child(*id); + } + match &fut.state { + ExternalFutureState::Resolved(Value::Ref(id)) => on_child(*id), + ExternalFutureState::Pending { + awaiter: Some(Awaiter::GatherSlot { gather, .. }), + } => on_child(*gather), + _ => {} + } + } + HeapData::DateTime(dt) => { + // Aware datetimes retain a heap reference to the tzinfo object so that + // `dt.tzinfo is tz` identity is preserved across attribute lookups. + // GC must follow that reference, otherwise the timezone gets swept + // while the datetime still points at the freed slot. + if let Some(tz_id) = dt.tzinfo_ref() { + on_child(tz_id); + } + } + HeapData::Time(t) => { + // Same retained-tzinfo contract as `DateTime` above. + if let Some(tz_id) = t.tzinfo_ref() { + on_child(tz_id); + } + } + HeapData::OpenFile(file) => { + // Kept in sync with `py_dec_ref_ids_for_data`: the file owns one + // ref on its loaded buffer. (`OpenFile` is not GC-tracked today, so + // this arm is not reached by the collector, but the two walkers must + // mirror each other per the contract above.) + if let Some(buffer_id) = file.buffer_id() { + on_child(buffer_id); + } + } + HeapData::ReMatch(m) => { + // Mirror `py_dec_ref_ids_for_data`: a match holds one ref on its + // shared subject string (`None` for an interned subject). + if let Value::Ref(id) = m.subject_ref() { + on_child(*id); + } + } + // Mirror `py_dec_ref_ids_for_data`: both own references to decimal contexts. + HeapData::DecimalSignalDict(dict) => on_child(dict.context_id()), + HeapData::DecimalContextManager(manager) => manager.context_ids().for_each(on_child), + // Leaf types with no heap references + _ => {} + } +} + +fn py_dec_ref_ids_for_data(data: &mut HeapData, stack: &mut Vec) { + match data { + HeapData::Str(s) => s.py_dec_ref_ids(stack), + HeapData::Bytes(b) => b.py_dec_ref_ids(stack), + HeapData::List(l) => l.py_dec_ref_ids(stack), + HeapData::Deque(d) => d.py_dec_ref_ids(stack), + HeapData::Tuple(t) => t.py_dec_ref_ids(stack), + HeapData::NamedTuple(nt) => nt.py_dec_ref_ids(stack), + HeapData::NamedTupleClass(class) => class.py_dec_ref_ids(stack), + HeapData::Dict(d) => d.py_dec_ref_ids(stack), + HeapData::DictKeysView(view) => view.py_dec_ref_ids(stack), + HeapData::DictItemsView(view) => view.py_dec_ref_ids(stack), + HeapData::DictValuesView(view) => view.py_dec_ref_ids(stack), + HeapData::Set(s) => s.py_dec_ref_ids(stack), + HeapData::FrozenSet(fs) => fs.py_dec_ref_ids(stack), + HeapData::Closure(closure) => { + // Decrement ref count for captured cells + stack.extend(closure.cells.iter().copied()); + // Decrement ref count for default values that are heap references + for default in &mut closure.defaults { + default.py_dec_ref_ids(stack); + } + stack.extend(closure.globals); + } + HeapData::FunctionDefaults(fd) => { + // Decrement ref count for default values that are heap references + for default in &mut fd.defaults { + default.py_dec_ref_ids(stack); + } + stack.extend(fd.globals); + } + HeapData::Cell(cell) => cell.0.py_dec_ref_ids(stack), + HeapData::HostClass(dc) => dc.py_dec_ref_ids(stack), + HeapData::HostClassType(t) => t.py_dec_ref_ids(stack), + HeapData::Class(class) => class.py_dec_ref_ids(stack), + HeapData::Instance(instance) => instance.py_dec_ref_ids(stack), + HeapData::BoundMethod(bm) => bm.py_dec_ref_ids(stack), + HeapData::DataclassField(field) => field.py_dec_ref_ids(stack), + HeapData::DataclassMethod(method) => method.py_dec_ref_ids(stack), + HeapData::DataclassParams(params) => params.py_dec_ref_ids(stack), + HeapData::ListIterator(iter) => iter.py_dec_ref_ids(stack), + HeapData::DequeIterator(iter) => iter.py_dec_ref_ids(stack), + HeapData::TupleIterator(iter) => iter.py_dec_ref_ids(stack), + HeapData::StringIterator(iter) => iter.py_dec_ref_ids(stack), + HeapData::BytesIterator(iter) => iter.py_dec_ref_ids(stack), + HeapData::RangeIterator(iter) => iter.py_dec_ref_ids(stack), + HeapData::DictKeyIterator(iter) => iter.py_dec_ref_ids(stack), + HeapData::DictItemIterator(iter) => iter.py_dec_ref_ids(stack), + HeapData::DictValueIterator(iter) => iter.py_dec_ref_ids(stack), + HeapData::SetIterator(iter) => iter.py_dec_ref_ids(stack), + HeapData::CallableIterator(iter) => iter.py_dec_ref_ids(stack), + HeapData::DirScan(scan) => scan.py_dec_ref_ids(stack), + HeapData::Itertools(iter) => iter.py_dec_ref_ids(stack), + HeapData::Csv(csv) => csv.py_dec_ref_ids(stack), + HeapData::Partial(partial) => partial.py_dec_ref_ids(stack), + HeapData::GenericAlias(alias) => alias.py_dec_ref_ids(stack), + HeapData::Union(union) => union.py_dec_ref_ids(stack), + HeapData::LruCache(cache) => cache.py_dec_ref_ids(stack), + HeapData::Module(m) => m.py_dec_ref_ids(stack), + HeapData::Coroutine(coro) => { + // Decrement ref count for namespace values that are heap references + for value in &mut coro.namespace { + value.py_dec_ref_ids(stack); + } + stack.extend(coro.globals); + } + HeapData::GatherFuture(gather) => { + // Decrement ref count for owned item HeapIds (coroutines and + // external futures are both owned by the gather). + stack.extend(gather.items.iter().copied()); + // Release per-state heap refs: in-flight slot results plus this + // gather's own awaiter (if `GatherSlot`, it owns an inc_ref on + // the outer gather), or the cached result list once the gather + // has completed successfully. `Pending` and `Failed` carry no + // heap refs. + match &mut gather.state { + GatherState::Awaited(awaited) => { + if let Awaiter::GatherSlot { gather, .. } = &awaited.awaiter { + stack.push(*gather); + } + for result in awaited.results.iter_mut().flatten() { + result.py_dec_ref_ids(stack); + } + } + GatherState::Completed(value) => value.py_dec_ref_ids(stack), + GatherState::Pending | GatherState::Failed(_) => {} + } + } + HeapData::ExternalFuture(fut) => { + // Mirror `for_each_child_id`: a pending sleep's `result` is owned too. + if let Some(result) = &mut fut.sleep_result { + result.py_dec_ref_ids(stack); + } + match &mut fut.state { + ExternalFutureState::Resolved(value) => value.py_dec_ref_ids(stack), + ExternalFutureState::Pending { + awaiter: Some(Awaiter::GatherSlot { gather, .. }), + } => stack.push(*gather), + ExternalFutureState::Pending { + awaiter: None | Some(Awaiter::Task(_)), + } + | ExternalFutureState::Failed(_) => {} + } + } + HeapData::DateTime(dt) => { + // Mirror `for_each_child_id`: when an aware datetime is freed we must + // also drop the retained tzinfo reference so its refcount is balanced. + if let Some(tz_id) = dt.tzinfo_ref() { + stack.push(tz_id); + } + } + HeapData::Time(t) => { + // Mirror `for_each_child_id`: an aware time owns its tzinfo reference. + if let Some(tz_id) = t.tzinfo_ref() { + stack.push(tz_id); + } + } + HeapData::OpenFile(f) => { + // Kept in sync with `for_each_child_id`: release the file's owned + // ref on its loaded buffer when the file is freed (e.g. read but + // never `close()`d). + f.py_dec_ref_ids(stack); + } + // Release the shared subject reference (mirrors `for_each_child_id`). + HeapData::ReMatch(m) => m.py_dec_ref_ids(stack), + // Release the owned decimal context references (mirrors `for_each_child_id`). + HeapData::DecimalSignalDict(dict) => dict.py_dec_ref_ids(stack), + HeapData::DecimalContextManager(manager) => manager.py_dec_ref_ids(stack), + // other types have no nested heap references + _ => {} + } +} + +/// Compile-fail soundness tests for [`HeapReader`]. +/// +/// Gated behind `--cfg heap_reader_compile_fail_tests` so they are only compiled +/// when the integration test harness runs `cargo rustc` with the appropriate flags. +#[cfg(heap_reader_compile_fail_tests)] +#[path = "../../tests/heap_reader_compile_fail_cases/cases.rs"] +mod heap_reader_compile_fail_cases; + +/// Valid borrowed-handle usage, kept here to exercise the private production API under Miri. +#[cfg(test)] +#[path = "../../tests/heap_reader/borrowed.rs"] +mod borrowed_tests; + +/// Cycle-collector unit tests. +/// +/// These live inside `heap.rs` (rather than under `crates/monty/tests/`) +/// because they need to manipulate `Heap` state directly — building a cycle +/// without a VM, peeking at `purple_count`, and rooting an entry only via a +/// Rust local binding. The integration-test surface only exposes +/// Python-driven execution and cannot construct any of those scenarios. +/// +/// In particular, the [`cstack_only_cycle_survives_collection`] test +/// validates the central correctness property of trial deletion: a heap +/// entry referenced *only* from the Rust C stack survives a cycle +/// collection because its non-zero refcount is itself proof of liveness. +/// That behavior was previously a known soundness gap of the explicit-roots +/// mark–sweep collector. +#[cfg(test)] +mod tests { + use monty_types::ResourceTracker; + + use super::*; + use crate::{ + types::{List, callable_iterator::CallableIterator}, + value::Value, + }; + + /// Returns whether a heap entry is still allocated at `id`. + fn is_alive(heap: &Heap, id: HeapId) -> bool { + heap.entries.iter().any(|(other, _)| other == id) + } + + /// Allocates a self-referencing one-element list and returns its id. + /// + /// The list's items become `[Value::Ref(id)]` and its refcount is bumped + /// to 2 to reflect both the caller's ref and the new self-reference. + fn alloc_self_cycle(heap: &Heap) -> HeapId { + let id = heap.allocate(HeapData::List(List::new(vec![]))); + let entry = heap + .entries + .iter() + .find(|(other, _)| *other == id) + .map(|(_, e)| e) + .expect("entry just allocated"); + // SAFETY: no other borrow into this entry's data exists during the test. + let data = unsafe { &mut *entry.data.0.get() }; + match data { + HeapData::List(list) => { + list.set_contains_refs(); + list.as_vec_mut().push(Value::Ref(id)); + } + _ => unreachable!(), + } + // The new self-pointer counts as one more reference into the entry. + heap.inc_ref(id); + id + } + + /// Allocates a two-element cycle where one direction has multiplicity 3: + /// `P → [A, A, A]` and `A → [P]`. Returns `(p_id, a_id)`. + /// + /// Final refcounts: `P.rc = 2` (alloc + one edge from A), `A.rc = 4` + /// (alloc + three edges from P). The caller "owns" one of each — both + /// can be dropped via `dec_ref` to isolate the cycle. + /// + /// Exercises the duplicate-edges-within-one-element shape that + /// `mark_gray`/`mark_black` must handle correctly: each edge from P + /// to A is one independent decrement (or increment), but the work + /// stack must not grow with edge multiplicity — otherwise the outer + /// pop processes A's children multiple times and over-counts. + fn alloc_dup_child_cycle(heap: &Heap) -> (HeapId, HeapId) { + let p_id = heap.allocate(HeapData::List(List::new(vec![]))); + let a_id = heap.allocate(HeapData::List(List::new(vec![]))); + + let push_refs = |target: HeapId, refs: &[HeapId]| { + let entry = heap + .entries + .iter() + .find(|(other, _)| *other == target) + .map(|(_, e)| e) + .expect("entry just allocated"); + // SAFETY: no other borrow into this entry's data exists during the test. + let data = unsafe { &mut *entry.data.0.get() }; + match data { + HeapData::List(list) => { + list.set_contains_refs(); + for r in refs { + list.as_vec_mut().push(Value::Ref(*r)); + } + } + _ => unreachable!(), + } + for r in refs { + heap.inc_ref(*r); + } + }; + + push_refs(p_id, &[a_id, a_id, a_id]); + push_refs(a_id, &[p_id]); + (p_id, a_id) + } + + #[test] + fn cstack_only_cycle_survives_collection() { + let mut heap = Heap::new(16, ResourceTracker::default()); + let id = alloc_self_cycle(&heap); + + // Simulate a Rust-side local `Value::Ref` binding by bumping the + // refcount one extra time. Then `dec_ref` it back down to 2 — that + // dec_ref is what enrolls the entry as a Purple candidate, mimicking + // exactly the situation under the old GC where the local binding + // wasn't published in any explicit root set. + heap.inc_ref(id); // rc = 3 + heap.dec_ref(id); // rc = 2, flagged Purple + assert_eq!(heap.purple_count, 1); + + // Cycle collection must not free the entry: the local "C-stack" ref + // contributes one of its two surviving refcount units, so trial + // deletion sees rc > 0 after MarkGray and resurrects the subtree. + heap.collect_cycles(); + assert_eq!(heap.purple_count, 0); + assert!(is_alive(&heap, id), "C-stack-rooted cycle was freed"); + assert!(matches!(heap.get(id), HeapData::List(_))); + + // Drop the simulated Rust local. Now the cycle is genuinely isolated + // (rc 1 = self-pointer only). The next collection must reclaim it. + heap.dec_ref(id); // rc = 1, re-flagged Purple + assert_eq!(heap.purple_count, 1); + heap.collect_cycles(); + assert_eq!(heap.purple_count, 0); + assert!(!is_alive(&heap, id), "isolated cycle should have been freed"); + } + + #[test] + fn heap_read_rooted_cycle_survives_collection() { + let mut heap = Heap::new(16, ResourceTracker::default()); + let id = alloc_self_cycle(&heap); + + // Bump `readers` manually to mimic a live `HeapRead` pointing into + // the entry. The borrow checker prevents holding a real `HeapRead` + // across `collect_cycles` (which requires `&mut Heap`), so we + // splice the same counter that `HeapRead::Drop` decrements. + let readers_before = heap.entries.get(id).readers.get(); + heap.entries.get(id).readers.set(readers_before + 1); + + // Drive the entry into Purple via dec_ref: rc 2 → 1. Without the + // `readers > 0` special-case in `Scan`, the resulting cycle would + // be condemned to White and freed. + heap.dec_ref(id); // rc = 1, flagged Purple + assert_eq!(heap.purple_count, 1); + + heap.collect_cycles(); + assert!( + is_alive(&heap, id), + "entry with active HeapRead reader was freed by collect_cycles" + ); + + // Restore the simulated reader so `Heap::drop` can clean up + // without tripping the `dec_ref` active-readers assertion. + heap.entries.get(id).readers.set(readers_before); + // The entry is leaked here on purpose (rc = 1 from the self-ref, + // no external root remains, but the collector ran already and the + // color is Black — the next dec_ref would try to recurse into the + // self-pointer after freeing the entry). `Heap::drop` walks every + // slot and tears them down regardless of refcount, so leaking + // here is safe for the duration of the test. + } + + /// Regression test for a soundness gap in [`Heap::dec_ref`]'s trial-deletion + /// candidate-enrollment path. + /// + /// The surviving-refcount branch calls `heap_entry.data.0.get_mut()` to + /// check `is_gc_tracked`, even though [`HeapData::is_gc_tracked`] only + /// needs `&self`. That `UnsafeCell::get_mut()` is a fresh `&mut HeapData` + /// (Unique) retag of the same allocation the live `HeapRead` is already + /// pointing into via a `SharedReadWrite` raw pointer, so it invalidates + /// the prior pointer under Stacked / Tree Borrows. + /// + /// Pure `cargo test` cannot observe this — the pointer arithmetic still + /// reads valid bytes — but `cargo +nightly miri test` flags the access. + /// The branch is reachable from normal Monty code (e.g. `list.remove` + /// on a self-referential list holds a `HeapObjectRead`, clones the + /// matching element, and the deferred drop of that clone calls + /// `dec_ref` on the same `HeapId` while the list reader is still live). + #[test] + fn dec_ref_must_not_invalidate_live_heap_read() { + let mut heap = Heap::new(16, ResourceTracker::default()); + let id = heap.allocate(HeapData::List(List::new(vec![]))); + // Bump refcount so `dec_ref` enters the non-freeing branch where + // the offending `data.0.get_mut()` lives. `List` is GC-tracked, so + // `is_gc_tracked` returns true and the branch is fully exercised. + heap.inc_ref(id); + + HeapReader::with(&mut heap, &mut (), |heap, ()| { + let HeapReadOutput::List(list) = heap.read(id) else { + unreachable!() + }; + // Holding `list` does NOT borrow the heap — only `list.get(heap)` + // does. That is what lets the borrow checker accept this + // sequence, while the underlying raw-pointer aliasing is + // nevertheless violated by the next call. + heap.dec_ref(id); + // Read through the now-invalidated `SharedReadWrite` raw pointer. + // Miri's aliasing model fails here. + let _ = list.get(heap).as_slice().len(); + }); + } + + #[test] + fn isolated_simple_cycle_is_collected() { + // Sanity check: a self-reference cycle with no external rooting + // gets collected on the next `collect_cycles` call. + let mut heap = Heap::new(16, ResourceTracker::default()); + let id = alloc_self_cycle(&heap); + // After alloc_self_cycle: rc = 2 (allocate's 1 + self-ref's 1). + // Drop the caller's reference. rc 2 → 1, marks Purple. + heap.dec_ref(id); + assert_eq!(heap.purple_count, 1); + heap.collect_cycles(); + assert!(!is_alive(&heap, id)); + assert_eq!(heap.purple_count, 0); + } + + #[test] + fn empty_tuple_singleton_survives_collection() { + // The empty-tuple singleton is no longer rooted explicitly by the + // collector. Its refcount stays ≥ 1 forever (initial heap-owned + // ref), which is what keeps it alive — verify the collector does + // not accidentally free it even after spurious Purple flagging. + let mut heap = Heap::new(16, ResourceTracker::default()); + // Fake a dec_ref event that would mark the empty tuple Purple. + heap.inc_ref(EMPTY_TUPLE_ID); + heap.dec_ref(EMPTY_TUPLE_ID); + heap.collect_cycles(); + assert!( + is_alive(&heap, EMPTY_TUPLE_ID), + "empty tuple singleton must survive collection" + ); + } + + #[test] + fn pending_purple_cycle_round_trips_through_serde() { + // A snapshot can be taken between any two bytecode instructions, so + // entries flagged Purple by `dec_ref` but not yet visited by the + // collector must survive serde round-trips. Otherwise a cycle that + // becomes garbage just before snapshot would leak permanently after + // restore (the post-restore VM would never re-touch it). + let mut heap = Heap::new(16, ResourceTracker::default()); + let id = alloc_self_cycle(&heap); + // Drop the caller's external ref so the entry is genuinely + // unreachable except via its self-pointer. dec_ref flags Purple. + heap.dec_ref(id); // rc 2 → 1 + assert_eq!(heap.purple_count, 1); + assert_eq!(heap.entries.get(id).color.get(), CcColor::Purple); + + // Round-trip through the dump codec. + let bytes = minicbor_serde::to_vec(&heap).expect("serialize"); + let mut restored: Heap = minicbor_serde::from_slice(&bytes).expect("deserialize"); + + // `purple_count` and the per-entry color must round-trip. + assert_eq!(restored.purple_count, 1); + assert_eq!(restored.entries.get(id).color.get(), CcColor::Purple); + + // Run the collector on the restored heap; the cycle is unreachable + // and must be reclaimed. + restored.collect_cycles(); + assert!(!is_alive(&restored, id)); + assert_eq!(restored.purple_count, 0); + } + + #[test] + fn isolated_cycle_with_duplicate_child_refs_is_collected() { + // Regression: an unreachable cycle where one element references its + // sibling multiple times within its child list. The mark phase must + // (a) decrement the sibling's refcount once per edge, and (b) push + // the sibling onto the work stack at most once, even when many + // edges from the same parent target it. + // + // Without (b), the outer pop walks the sibling's children once per + // duplicate edge, over-decrementing the *sibling's* children's + // refcounts. In debug builds this trips `mark_gray`'s + // refcount-underflow `debug_assert`; in release it wraps the + // refcount to `usize::MAX` and `scan` resurrects the cycle — + // either way, the cycle is not collected. + let mut heap = Heap::new(16, ResourceTracker::default()); + let (p_id, a_id) = alloc_dup_child_cycle(&heap); + // After construction: P.rc = 2, A.rc = 4. + + // Drop the caller's refs; the cycle is now genuinely unreachable. + heap.dec_ref(p_id); // P.rc 2 → 1, flagged Purple + heap.dec_ref(a_id); // A.rc 4 → 3, flagged Purple + assert_eq!(heap.purple_count, 2); + + heap.collect_cycles(); + + assert!(!is_alive(&heap, p_id), "P should be collected"); + assert!(!is_alive(&heap, a_id), "A should be collected"); + assert_eq!(heap.purple_count, 0); + } + + #[test] + fn cstack_rooted_cycle_with_duplicate_child_refs_collects_after_pin_dropped() { + // Regression: when `scan` resurrects a Purple cycle via `mark_black`, + // the per-edge refcount *increment* must mirror `mark_gray`'s + // per-edge decrement. Duplicate edges from one element to its + // sibling must not over-increment via repeated outer pops of the + // sibling. + // + // We pin P externally (extra inc_ref) so `scan` is forced to take + // the resurrect path through `mark_black`. After collection the + // refcounts must be exactly the pre-collection values — verified by + // dropping the pin and confirming the next `collect_cycles` reclaims + // the cycle. If `mark_black` over-incremented during resurrection, + // dropping the pin leaves the refcounts artificially high and the + // cycle leaks. + let mut heap = Heap::new(16, ResourceTracker::default()); + let (p_id, a_id) = alloc_dup_child_cycle(&heap); + // After construction: P.rc = 2, A.rc = 4. + + // Pin P externally. After the inc_ref + dec_ref pair, P is Purple + // but its refcount still includes one unit not accounted for by + // any in-cycle edge — `scan` must resurrect via `mark_black`. + heap.inc_ref(p_id); // P.rc = 3 (alloc + from A + pin) + heap.dec_ref(p_id); // P.rc = 2, flagged Purple + heap.dec_ref(a_id); // A.rc = 3, flagged Purple + + heap.collect_cycles(); + + // First pass: cycle survives because of P's external pin. + assert!(is_alive(&heap, p_id), "P should survive (external pin)"); + assert!(is_alive(&heap, a_id), "A should survive (reachable via P)"); + + // Drop the pin. If `mark_black` correctly restored refcounts during + // resurrection, the cycle is now isolated and the next collection + // reclaims it. Over-incrementing in `mark_black` leaves P's + // refcount artificially high so `scan` resurrects it again. + heap.dec_ref(p_id); + heap.collect_cycles(); + + assert!(!is_alive(&heap, p_id), "P should be collected after pin dropped"); + assert!(!is_alive(&heap, a_id), "A should be collected after pin dropped"); + } + + /// The GC must see BOTH refs a `callable_iterator` owns, with correct + /// multiplicity: under-tracing here would let a live object be collected. + #[test] + fn callable_iterator_traces_callable_and_sentinel() { + let heap = Heap::new(16, ResourceTracker::default()); + let c = heap.allocate(HeapData::List(List::new(vec![]))); + let s = heap.allocate(HeapData::List(List::new(vec![]))); + + heap.inc_ref(c); + heap.inc_ref(s); + let iter = heap.allocate(HeapData::CallableIterator(CallableIterator::new( + Value::Ref(c), + Value::Ref(s), + ))); + + let mut traced = vec![]; + for_each_child_id(heap.get(iter), |id| traced.push(id)); + assert_eq!(traced, vec![c, s], "callable and sentinel are both traced"); + + // Multiplicity: when callable IS sentinel, two counted refs point at one + // object, so the id must be reported twice or trial deletion + // under-decrements and frees a live object. + heap.inc_ref(c); + heap.inc_ref(c); + let shared = heap.allocate(HeapData::CallableIterator(CallableIterator::new( + Value::Ref(c), + Value::Ref(c), + ))); + + let mut dup = vec![]; + for_each_child_id(heap.get(shared), |id| dup.push(id)); + assert_eq!(dup, vec![c, c], "a shared callable/sentinel is traced twice"); + } + + /// End-to-end: a cycle through the callable must be collected and the + /// non-cycle sentinel released — exercising the mark phase + /// (`for_each_child_id`) and the free phase (`py_dec_ref_ids`) together. + #[test] + fn callable_iterator_cycle_is_collected() { + let mut heap = Heap::new(16, ResourceTracker::default()); + let sentinel = heap.allocate(HeapData::List(List::new(vec![]))); + let list = heap.allocate(HeapData::List(List::new(vec![]))); + heap.inc_ref(list); + heap.inc_ref(sentinel); + let iter = heap.allocate(HeapData::CallableIterator(CallableIterator::new( + Value::Ref(list), + Value::Ref(sentinel), + ))); + + // Close the cycle: the callable list references the iterator back. + heap.inc_ref(iter); + HeapReader::with(&mut heap, &mut (), |reader, ()| { + let HeapReadOutput::List(l) = reader.read(list) else { + unreachable!("just allocated a list") + }; + let l = l.get_mut(reader); + l.set_contains_refs(); + l.as_vec_mut().push(Value::Ref(iter)); + }); + // list.rc = 2, iter.rc = 2, sentinel.rc = 2. + + // Drop the allocation refs: {iter, list} is now an unreachable cycle and + // the sentinel is held only by the iterator. + heap.dec_ref(list); + heap.dec_ref(iter); + heap.dec_ref(sentinel); + + heap.collect_cycles(); + + assert!(!is_alive(&heap, iter), "callable_iterator in a cycle must be collected"); + assert!(!is_alive(&heap, list), "the cycle's other node must be collected"); + assert!( + !is_alive(&heap, sentinel), + "sentinel held only by the freed iterator must be released" + ); + } +} diff --git a/crates/bashkit-monty/src/heap/stable_heap.rs b/crates/bashkit-monty/src/heap/stable_heap.rs new file mode 100644 index 000000000..a5f446fe4 --- /dev/null +++ b/crates/bashkit-monty/src/heap/stable_heap.rs @@ -0,0 +1,503 @@ +use std::{ + cell::{Cell, UnsafeCell}, + fmt, + mem::MaybeUninit, +}; + +use crate::heap::{HeapId, free_list::FreeList, stable_heap::iter::HeapEntriesIter}; + +/// Number of entries per page. Chosen to balance between wasted memory (from +/// partially-filled last pages) and the frequency of page allocations. +const PAGE_SIZE: usize = 256; + +/// A single page of heap entries. Each page is a fixed-size boxed slice of +/// `MaybeUninit` slots — only slots at indices below `HeapEntries::len` are +/// initialized. +type Page = Box<[Slot; PAGE_SIZE]>; +type Slot = MaybeUninit>; + +/// Paged storage for heap entries that guarantees address stability. This also +/// has other conveniences like only needing `&self` to allocate, and a free list +/// for reuse of freed slots. +/// +/// Entries are stored in fixed-size pages of `MaybeUninit>`. +/// Only slots that have been `push`ed are initialized — new pages are allocated +/// without touching the memory, avoiding the cost of writing `None` to every slot. +/// +/// Once a page is allocated, it is never reallocated or moved in memory. +/// This is the key invariant that makes `&self` allocation sound: a reference +/// derived from an entry's data will remain valid for the entry's entire lifetime, +/// even as new pages are appended via `allocate(&self)`. +/// +/// The free list tracks slot IDs freed by `dec_ref` for reuse by `allocate`, +/// keeping memory usage roughly constant for long-running loops that repeatedly +/// allocate and free values. +/// +/// ## Interior mutability and safety +/// +/// `pages`, `len`, and `free_list` use interior mutability (`UnsafeCell`/`Cell`) +/// so that `allocate` can take `&self` instead of `&mut self`. This is sound because: +/// +/// - **`allocate(&self)`** only writes to the slot at index `len` (never readable +/// by anyone, since all reads require `index < len`) or to a freed slot from the +/// free list (no active borrows exist on freed slots). +/// - **`Vec::push` on `pages`** during allocation reallocates the page pointer array, +/// but not the page contents. Any existing `&T` reference points into a +/// `Box`'s heap allocation, not into the `Vec`'s buffer. +/// +/// Index `i` maps to `pages[i / PAGE_SIZE][i % PAGE_SIZE]`. +pub(crate) struct StableHeap { + /// Fixed-size pages of heap entries. Each page is heap-allocated once and + /// never moved, providing address stability for all contained entries. + /// Wrapped in `UnsafeCell` to allow `allocate(&self)` to append new pages. + pages: UnsafeCell>>, + /// Total number of initialized slots (including freed ones). + /// Uses `Cell` for interior mutability so `allocate(&self)` can increment. + len: Cell, + /// IDs of freed slots available for reuse. Populated by `free`, consumed by `allocate`. + free_list: FreeList, +} + +impl fmt::Debug for StableHeap { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list() + // SAFETY: [DH] - debug formatting the `None` values never calls `.allocate()`, and `HeapEntries` is not `Sync`, + // so there can be no re-entrancy which observes a `None` value at the same time which allocates. + .entries(unsafe { HeapEntriesIter::new(self) }) + .finish() + } +} + +impl StableHeap { + /// Creates a new paged storage pre-allocating enough pages for `capacity` entries. + pub fn with_capacity(capacity: usize) -> Self { + let num_pages = capacity.div_ceil(PAGE_SIZE); + let mut pages = Vec::with_capacity(num_pages); + for _ in 0..num_pages { + pages.push(create_page()); + } + Self { + pages: UnsafeCell::new(pages), + len: Cell::new(0), + free_list: FreeList::new(), + } + } + + /// Returns the total number of initialized slots (including freed ones). + #[inline] + pub fn len(&self) -> usize { + self.len.get() + } + + /// Returns a shared reference to the entry at `index`. + /// + /// # Panics + /// Panics if `index >= len`, or if the slot is freed. + #[inline] + #[track_caller] + pub fn get(&self, id: HeapId) -> &T { + // SAFETY: [DH] - this call panics rather than expose free slots which could be invalidated + // by calls to `.allocate()`. + let slot = unsafe { self.slot_at(id) }; + let Some(entry) = slot else { + // bashkit fork: no id in the message (CodeQL cleartext-logging false positive). + panic!("StableHeap::get - id out of bounds"); + }; + entry.as_ref().expect("HeapEntries::get - data already freed") + } + + /// Returns a mutable reference to the entry at `index`. Entries can also be + /// freed via the returned `StableHeapEntry`'s `free` method. + /// + /// Does *not* go through [`Self::entry_ptr`]: that path derives its pointer via + /// `&self` so it only carries Shared / SharedReadOnly provenance under SB/TB, + /// and dereferencing it as `&mut` is UB. Instead this method takes the safe + /// `&mut self` → `pages.get_mut()` route, producing a `&mut Option` with + /// Unique provenance suitable for `StableHeapEntry::free`'s `value.take()`. + /// + /// # Panics + /// Panics if `index >= len`. + #[inline] + #[track_caller] + pub fn entry(&mut self, id: HeapId) -> Option> { + assert!(id.index() < self.len.get(), "StableHeap::entry - {id:?} out of bounds"); + let (page_idx, slot_idx) = Self::page_slot_indices(id); + let pages = self.pages.get_mut(); + let slot = &mut pages[page_idx][slot_idx]; + // SAFETY: [DH] - all slots at indices < self.len have been initialized via `allocate`. + let value = unsafe { slot.assume_init_mut() }; + StableHeapEntry::new(id, value, &mut self.free_list) + } + + /// Allocates a slot — reusing from the free list or appending — and returns its ID. + /// + /// Takes `&self` instead of `&mut self`, enabling allocation while holding shared + /// borrows to other heap entries. This is the core operation that makes + /// `Heap::allocate(&self)` possible. + pub fn allocate(&self, value: T) -> HeapId { + self.allocate_with_slot(value).0 + } + + /// Allocates a value and also returns its stable arena slot. + /// + /// The slot lets the heap immediately project a newly allocated payload + /// without repeating the page and slot lookup. + pub fn allocate_with_slot(&self, value: T) -> (HeapId, &Option) { + // SAFETY: [DH] + // - This is the only `&self` method which uses `pages.get()` to create a mutable reference to `pages`. + // - This method is not re-entrant, and not `Sync`, so cannot have a global `StableHeap` where + // allocator re-entrancy on `pages.push` could cause a problem. + // - No `&T` borrows derived from `pages` can be invalidated by `allocate`; only borrows to `None` + // entries can be invalidated. Other callsites (e.g. iteration) have safety contracts that + // forbid calling `allocate` while borrows which may be `None` are live. + // + // TODO: use `UnsafeCell::as_mut_unchecked` when stable. + let pages = unsafe { self.pages.get().as_mut_unchecked() }; + let (id, slot) = if let Some(id) = self.free_list.pop() { + let (page_idx, slot_idx) = Self::page_slot_indices(id); + let slot = &mut pages[page_idx][slot_idx]; + debug_assert!( + // SAFETY: [DH] - previously freed slots must have previously been initialized. + unsafe { slot.assume_init_ref() }.is_none(), + "allocate - popped free slot {id:?} is not actually free" + ); + (id, slot) + } else { + let id = HeapId::from_index(self.len.get()); + let (page_idx, slot_idx) = Self::page_slot_indices(id); + if page_idx >= pages.len() { + pages.push(create_page()); + } + self.len.set(id.index() + 1); + (id, &mut pages[page_idx][slot_idx]) + }; + + // Write to the new slot. No need to worry about initializedness / the destructor - either the slot was + // free (in which case the slot is `None` and has no meaningful destructor), or the slot is not + // initialized yet. + let slot = slot.write(Some(value)); + + (id, slot) + } + + /// Iterates the live values + #[cfg(any(feature = "ref-count-return", test))] + pub fn iter(&self) -> impl Iterator { + // SAFETY: [DH] - iterating only the live entries ensures that caller + // can never observe `None` entries which could be invalidated by + // calls to `allocate()`. Entries can only be freed by `&mut self` methods. + unsafe { HeapEntriesIter::new(self) }.filter_map(|(idx, slot)| slot.map(|s| (HeapId::from_index(idx), s))) + } + + /// Accesses the slot at `id` with an immutable borrow on self. Returns `None` if the slot + /// is out of bounds. + /// + /// # Safety: + /// - Caller must ensure that `Some(&None)` references do not overlap with any calls to `allocate()`, + /// as these will be invalidated by the reuse of freed slots. + #[track_caller] + pub unsafe fn slot_at(&self, id: HeapId) -> Option<&Option> { + if id.index() >= self.len.get() { + return None; + } + let (page_idx, slot_idx) = Self::page_slot_indices(id); + // SAFETY: [DH] - modification to pages Vec only occur in allocate, which only writes to `None` entries + // and doesn't cause reallocation of the boxed contents of existing pages, so temporary read of `pages` here is ok. + // + // TODO: use `UnsafeCell::as_ref_unchecked` when stable. + let pages = unsafe { self.pages.get().as_ref_unchecked() }; + let slot = &pages[page_idx][slot_idx]; + // SAFETY: [DH] - all slots at indices < self.len have been initialized via `allocate`. + Some(unsafe { slot.assume_init_ref() }) + } + + fn page_slot_indices(id: HeapId) -> (usize, usize) { + let index = id.index(); + (index / PAGE_SIZE, index % PAGE_SIZE) + } +} + +/// Allocates a new page of uninitialized slots directly on the heap. +fn create_page() -> Box<[Slot; PAGE_SIZE]> { + let raw = Box::into_raw(Box::<[Slot]>::new_uninit_slice(PAGE_SIZE)).cast(); + // SAFETY: [DH] - allocation is known to be exactly PAGE_SIZE slots, so + // the cast-ed pointer can still be used with `Box::from_raw` + unsafe { Box::from_raw(raw) } +} + +/// Submodule for `StableHeapEntry` to help enforce a safety boundary around the `new` constructor. +mod stable_heap_entry { + use std::ops::{Deref, DerefMut}; + + use crate::heap::{HeapId, free_list::FreeList}; + + pub struct StableHeapEntry<'a, T> { + id: HeapId, + value: &'a mut Option, + free_list: &'a mut FreeList, + } + + impl<'a, T> StableHeapEntry<'a, T> { + // Only way to construct a `StableHeapEntry`. Returns `None` if the slot is already freed. + pub fn new(id: HeapId, value: &'a mut Option, free_list: &'a mut FreeList) -> Option { + value.is_some().then_some(Self { id, value, free_list }) + } + + pub fn free(self) -> T { + self.free_list.push(self.id); + // SAFETY: [DH] - impossible to get a `StableHeapEntry` with `None` slot - `new` + // is the only constructor + unsafe { self.value.take().unwrap_unchecked() } + } + + pub fn get(&self) -> &T { + // SAFETY: [DH] - impossible to get a `StableHeapEntry` with `None` slot - `new` + // is the only constructor + unsafe { self.value.as_ref().unwrap_unchecked() } + } + + pub fn get_mut(&mut self) -> &mut T { + // SAFETY: [DH] - impossible to get a `StableHeapEntry` with `None` slot - `new` + // is the only constructor + unsafe { self.value.as_mut().unwrap_unchecked() } + } + } + + impl Deref for StableHeapEntry<'_, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + self.get() + } + } + + impl DerefMut for StableHeapEntry<'_, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.get_mut() + } + } +} + +use stable_heap_entry::StableHeapEntry; + +/// Serializes as a struct with two fields: `entries` (flat vec of all initialized +/// slots) and `free_list` (vec of freed slot IDs). This avoids exposing the +/// internal paged layout in the wire format. +impl serde::Serialize for StableHeap +where + T: serde::Serialize, +{ + fn serialize(&self, serializer: S) -> Result { + // SAFETY: [DH] - serializing `None` data cannot cause allocation, so `None` entries + // cannot be observed by serialization, even if reentrant. + serializer.collect_seq(unsafe { HeapEntriesIter::new(self) }.map(|(_idx, slot)| slot)) + } +} + +impl<'de, T> serde::Deserialize<'de> for StableHeap +where + T: serde::Deserialize<'de>, +{ + fn deserialize>(deserializer: D) -> Result { + let entries: Vec> = Vec::deserialize(deserializer)?; + let mut this = Self::with_capacity(entries.len()); + + // Re-initialize the freelist from none entries + this.free_list = entries + .iter() + .enumerate() + .filter(|(_, entry)| entry.is_none()) + .map(|(idx, _)| HeapId::from_index(idx)) + .collect::>() + .into(); + + // Set the initialized region + this.len.set(entries.len()); + + // Write all pages from the entries vec + let pages = this.pages.get_mut(); + for (index, entry) in entries.into_iter().enumerate() { + let (page_idx, slot_idx) = Self::page_slot_indices(HeapId::from_index(index)); + pages[page_idx][slot_idx].write(entry); + } + Ok(this) + } +} + +impl Drop for StableHeap { + fn drop(&mut self) { + let len = self.len.get(); + let pages = self.pages.get_mut(); + for i in 0..len { + let slot = &mut pages[i / PAGE_SIZE][i % PAGE_SIZE]; + // SAFETY: [DH] - all slots at indices < self.len have been initialized via `allocate`. + unsafe { slot.assume_init_drop() }; + } + } +} + +/// Place iterator inside a submodule to create a safety boundary on `new` constructor +mod iter { + use super::StableHeap; + use crate::heap::HeapId; + + pub(super) struct HeapEntriesIter<'a, T> { + entries: &'a StableHeap, + index: usize, + } + + impl<'a, T> HeapEntriesIter<'a, T> { + /// # Safety: + /// + /// The caller must ensure that `HeapEntries::allocate()` + /// is never called for the lifetime `'a` for which this iterator and its + /// yielded elements exist. + /// + /// Allocation may write to `None` entries, which would cause unsafe + /// aliasing. + pub unsafe fn new(entries: &'a StableHeap) -> Self { + Self { entries, index: 0 } + } + } + + impl<'a, T> Iterator for HeapEntriesIter<'a, T> { + type Item = (usize, Option<&'a T>); + + fn next(&mut self) -> Option { + let current_index = self.index; + // SAFETY: [DH] - caller guaranteed no aliasing when calling `HeapEntriesIter::new` + let entry = unsafe { self.entries.slot_at(HeapId::from_index(current_index)) }?; + self.index += 1; + Some((current_index, entry.as_ref())) + } + + fn size_hint(&self) -> (usize, Option) { + let remaining = self.entries.len().saturating_sub(self.index); + (remaining, Some(remaining)) + } + } +} + +#[cfg(test)] +mod tests { + + use super::*; + + #[test] + fn allocate_while_reference_alive() { + // Allocate a value, hold a shared reference to it, then allocate + // another value. The first reference must remain valid. + let entries = StableHeap::with_capacity(16); + let id_a = entries.allocate("a"); + let ref_a = entries.get(id_a); + + // Allocate while ref_a is live + let id_b = entries.allocate("b"); + + // Both references must be readable + assert_eq!(*ref_a, "a"); + assert_eq!(*entries.get(id_b), "b"); + } + + #[test] + fn allocate_triggers_new_page_while_reference_alive() { + // Fill the first page, hold a reference into it, then allocate into a + // second page. The reference must survive the Vec::push. + let entries = StableHeap::with_capacity(PAGE_SIZE); + + // Fill the first page. + for _ in 0..PAGE_SIZE { + entries.allocate("fill"); + } + assert_eq!(entries.len(), PAGE_SIZE); + + // Hold a reference into the first page. + let first_ref = entries.get(HeapId::from_index(0)); + + // This allocation creates a second page — the pages Vec reallocates + // its pointer buffer, but Box contents must not move. + let overflow_id = entries.allocate("overflow"); + + // The reference into the first page must still be valid. + assert_eq!(*first_ref, "fill"); + assert_eq!(*entries.get(overflow_id), "overflow"); + } + + #[test] + fn free_list_reuse_while_reference_alive() { + // Allocate three values, free the middle one, then reallocate while + // holding a reference to a different live slot. + let mut entries = StableHeap::with_capacity(16); + let id_a = entries.allocate("a"); + let id_b = entries.allocate("b"); + let _id_c = entries.allocate("c"); + + // Free slot b (simulates dec_ref taking the value and calling free). + entries.entry(id_b).unwrap().free(); + + // Hold a reference to slot a. + let ref_a = entries.get(id_a); + + // Reallocate into the freed slot while ref_a is live. + let id_reused = entries.allocate("reused"); + assert_eq!(id_reused, id_b); // should reuse the freed slot + + // ref_a must still be valid. + assert_eq!(*ref_a, "a"); + // Reused slot has new data. + assert_eq!(*entries.get(id_reused), "reused"); + } + + #[test] + fn multiple_live_references_during_allocation() { + // Hold references to multiple slots across different pages, then + // allocate. All references must survive. + let entries = StableHeap::with_capacity(PAGE_SIZE * 2); + + // Fill two pages. + for _ in 0..PAGE_SIZE * 2 { + entries.allocate("filler"); + } + + // Hold references in both pages. + let ref_first_page = entries.get(HeapId::from_index(0)); + let ref_second_page = entries.get(HeapId::from_index(PAGE_SIZE)); + + // Allocate a third page. + let new_id = entries.allocate("new"); + + // All references must be readable. + assert_eq!(*ref_first_page, "filler"); + assert_eq!(*ref_second_page, "filler"); + assert_eq!(*entries.get(new_id), "new"); + } + + #[test] + fn allocate_into_freed_slot_does_not_alias_other_slots() { + // Free several slots, then reallocate into them while holding live + // references to other slots. Reallocation must not disturb those + // references — using distinct values lets a stray alias surface as + // a value mismatch. + let mut entries = StableHeap::with_capacity(16); + + let ids: Vec<_> = (0..8).map(|_| entries.allocate("original")).collect(); + + // Free even-indexed slots. + for &id in ids.iter().step_by(2) { + entries.entry(id).unwrap().free(); + } + + // Hold references to odd-indexed (live) slots. + let live_refs: Vec<_> = ids.iter().skip(1).step_by(2).map(|id| entries.get(*id)).collect(); + + // Reallocate into freed slots with a different value. + for _ in 0..4 { + entries.allocate("realloc"); + } + + // Live references must still see the original value. + for r in &live_refs { + assert_eq!(**r, "original"); + } + } +} diff --git a/crates/bashkit-monty/src/heap_data.rs b/crates/bashkit-monty/src/heap_data.rs new file mode 100644 index 000000000..428204b45 --- /dev/null +++ b/crates/bashkit-monty/src/heap_data.rs @@ -0,0 +1,1074 @@ +use std::{ + borrow::Cow, + collections::hash_map::DefaultHasher, + fmt::Write, + hash::{Hash, Hasher}, + mem, + ops::Deref, +}; + +use monty_types::ExcType; + +use crate::{ + args::ArgValues, + asyncio::{Awaiter, Coroutine, ExternalFuture, ExternalFutureState, GatherFuture, GatherState}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcTypeExt, RunResult, SimpleException}, + expressions::CmpOperator, + hash::{HashValue, identity_hash}, + heap::{DropWithContext, HeapId, HeapItem, HeapObjectRead, HeapReadOutput}, + intern::FunctionId, + types::{LazyHeapSet, LongInt, PyTrait, Type}, + value::{EitherStr, Value}, +}; + +macro_rules! heap_storage_type { + (inline $payload:ty) => { + $payload + }; + (boxed $payload:ty) => { + Box<$payload> + }; +} + +/// Invokes a consumer macro with every concrete payload stored by the heap. +/// +/// This is the single payload registry. Dumps tag each variant by its serde name, so +/// renaming a variant needs an alias; hot variants take one letter to keep dumps small. +macro_rules! heap_payloads { + ($consumer:ident) => { + $consumer! { + #[serde(rename = "S")] + Str(inline $crate::types::Str), + #[serde(rename = "B")] + Bytes(inline $crate::types::Bytes), + #[serde(rename = "L")] + List(inline $crate::types::List), + /// `collections.deque` — a double-ended queue with an optional `maxlen`. + #[serde(rename = "Q")] + Deque(inline $crate::types::Deque), + #[serde(rename = "T")] + Tuple(inline $crate::types::Tuple), + #[serde(rename = "N")] + NamedTuple(boxed $crate::types::NamedTuple), + /// A `collections.namedtuple` class object (the callable that builds instances). + NamedTupleClass(boxed $crate::types::NamedTupleClass), + #[serde(rename = "D")] + Dict(inline $crate::types::Dict), + DictKeysView(inline $crate::types::DictKeysView), + DictItemsView(inline $crate::types::DictItemsView), + DictValuesView(inline $crate::types::DictValuesView), + #[serde(rename = "E")] + Set(inline $crate::types::Set), + #[serde(rename = "F")] + FrozenSet(inline $crate::types::FrozenSet), + #[serde(rename = "C")] + Closure(inline $crate::heap_data::Closure), + #[serde(rename = "U")] + FunctionDefaults(inline $crate::heap_data::FunctionDefaults), + /// A cell wrapping a single mutable value for closure support. + #[serde(rename = "K")] + Cell(inline $crate::heap_data::CellValue), + /// A range object such as `range(1, 10, 2)`. + Range(inline $crate::types::Range), + /// A slice object such as `slice(1, 10, 2)`. + Slice(inline $crate::types::Slice), + /// An exception instance such as `ValueError('message')`. + #[serde(rename = "X")] + Exception(inline $crate::exception_private::SimpleException), + /// A host-backed class instance (the heap form of the wire `ClassInstance`). + HostClass(boxed $crate::types::HostClass), + /// The lightweight type object `type(x)` materializes for a `HostClass` + /// instance — the real class lives on the host, so this is a named + /// stand-in (see `HostClassType`). + HostClassType(boxed $crate::types::HostClassType), + /// A user-defined class object created by a `class` statement. + #[serde(rename = "A")] + Class(boxed $crate::types::Class), + /// An instance of a user-defined class. + #[serde(rename = "I")] + Instance(boxed $crate::types::Instance), + /// A method bound to an instance. + #[serde(rename = "M")] + BoundMethod(inline $crate::types::BoundMethod), + /// One `dataclasses.Field` held by a class's `__dataclass_fields__` dictionary. + /// Boxed: a name, an annotation and a default or factory are already + /// wider than the 32-bit ceiling, and `Field` has attributes left to gain. + DataclassField(boxed $crate::modules::dataclasses::DataclassField), + /// A method `@dataclass` generated into a class namespace. + /// Boxed: its `__init__` form carries every field's captured default. + DataclassMethod(boxed $crate::modules::dataclasses::DataclassMethod), + /// A `list_iterator` object. + ListIterator(inline $crate::types::list::ListIterator), + /// A `_collections._deque_iterator` object. + DequeIterator(inline $crate::types::deque::DequeIterator), + /// A `tuple_iterator` object. + TupleIterator(inline $crate::types::TupleIterator), + /// A `str_ascii_iterator` or `str_iterator` object. + StringIterator(inline $crate::types::StringIterator), + /// A `bytes_iterator` object. + BytesIterator(inline $crate::types::BytesIterator), + /// A `range_iterator` object. + RangeIterator(inline $crate::types::RangeIterator), + /// A `dict_keyiterator` object. + DictKeyIterator(inline $crate::types::DictKeyIterator), + /// A `dict_itemiterator` object. + DictItemIterator(inline $crate::types::DictItemIterator), + /// A `dict_valueiterator` object. + DictValueIterator(inline $crate::types::DictValueIterator), + /// A `set_iterator` object. + SetIterator(inline $crate::types::SetIterator), + /// A `callable_iterator` object from `iter(callable, sentinel)`. + CallableIterator(inline $crate::types::callable_iterator::CallableIterator), + /// An arbitrary-precision integer used when a Python `int` does not fit in `i64`. + #[serde(rename = "G")] + LongInt(inline $crate::types::LongInt), + /// A `complex` number: two doubles, too wide for an immediate `Value`. + #[serde(rename = "J")] + Complex(inline $crate::types::Complex), + /// A Python module and its attributes. + Module(boxed $crate::types::Module), + /// A coroutine object from an async function call. + #[serde(rename = "O")] + Coroutine(inline $crate::asyncio::Coroutine), + /// An `asyncio.gather()` result tracking multiple coroutines or tasks. + GatherFuture(boxed $crate::asyncio::GatherFuture), + /// An external future driven by the host. + ExternalFuture(boxed $crate::asyncio::ExternalFuture), + /// A filesystem path from `pathlib.Path`. + Path(inline $crate::types::Path), + /// A path-backed file object returned by `open()`. + OpenFile(boxed $crate::types::OpenFile), + /// A compiled regular-expression pattern. + RePattern(boxed $crate::types::RePattern), + /// A regular-expression match result. + ReMatch(boxed $crate::types::ReMatch), + /// A reference to an external function supplied by the host. + ExtFunction(inline $crate::types::ExtFunction), + /// A `datetime.date` value. + Date(inline $crate::types::date::Date), + /// A `datetime.datetime` value. + DateTime(inline $crate::types::datetime::DateTime), + /// A `datetime.timedelta` value. + TimeDelta(inline $crate::types::timedelta::TimeDelta), + /// A fixed-offset `datetime.timezone` value. + TimeZone(inline $crate::types::timezone::TimeZone), + /// Any `itertools` iterator (`count`, `repeat`, and others). + Itertools(inline $crate::types::ItertoolsIter), + /// The options of a `@dataclass`, held in `__dataclass_params__`. + DataclassParams(inline $crate::modules::dataclasses::DataclassParams), + /// A `datetime.time` value stored with narrow integer fields. + Time(inline $crate::types::time::Time), + /// A `functools.partial` object. + Partial(boxed $crate::types::Partial), + /// A `types.GenericAlias` such as `list[int]`. + GenericAlias(inline $crate::types::GenericAlias), + /// A `typing.Union` such as `int | None`. + Union(inline $crate::types::Union), + /// A `random.Random` generator instance. + Random(boxed $crate::types::Random), + /// A `functools.lru_cache` / `functools.cache` wrapper. + LruCache(boxed $crate::types::LruCache), + /// A `hashlib` hash object mid-stream. + HashObject(boxed $crate::types::HashObject), + /// An `os.DirEntry`, `os.scandir()` iterator or `os.walk()` iterator. + DirScan(boxed $crate::types::DirScan), + /// Any `csv` object: a reader, writer, `DictReader`, `DictWriter` or dialect. + Csv(boxed $crate::types::CsvObject), + /// A `decimal.Decimal` value. + Decimal(inline $crate::types::decimal::Decimal), + /// A mutable `decimal.Context`. + DecimalContext(inline $crate::types::decimal::DecContext), + /// A context's `flags` or `traps` mapping. + DecimalSignalDict(inline $crate::types::decimal::py_context::SignalDict), + /// The manager `decimal.localcontext()` returns. + DecimalContextManager(inline $crate::types::decimal::py_context::ContextManager), + } + }; +} + +pub(crate) use heap_payloads; + +macro_rules! define_heap_data { + ($( + $(#[$meta:meta])* + $variant:ident($storage:ident $payload:ty) + ),* $(,)?) => { + /// Every runtime value that can be stored in the heap arena. + #[derive(Debug, serde::Serialize, serde::Deserialize)] + pub(crate) enum HeapData { + $( + $(#[$meta])* + $variant(heap_storage_type!($storage $payload)), + )* + } + }; +} + +heap_payloads!(define_heap_data); + +/// The widest `HeapData` may be, per target. +/// +/// `Dict` sets it on 64-bit hosts. On 32-bit (the wasm worker) `Dict` halves +/// while `Value`-built payloads do not, so the itertools family sets it instead +/// — see the budget those adaptors are held to in `types::itertools`. +const MAX_HEAP_DATA_SIZE: usize = if cfg!(target_pointer_width = "64") { 80 } else { 56 }; + +// `HeapData` is copied on every allocate and free, and every byte past the +// ceiling widens every slot of every heap page. Box the variant that trips +// this, not the enum: growing the budget here charges the hot variants too. +const _: () = assert!(mem::size_of::() <= MAX_HEAP_DATA_SIZE); + +impl HeapData { + /// Returns whether this heap data type can participate in reference cycles. + /// + /// Only container types that can hold references to other heap objects need to be + /// tracked for GC purposes. Leaf types like Str, Bytes, Range, and Exception cannot + /// form cycles and should not count toward the GC allocation threshold. + /// + /// This optimization allows programs that allocate many leaf objects (like strings) + /// to avoid triggering unnecessary GC cycles. + /// + /// Matched exhaustively so new variants must choose. + #[inline] + pub(crate) fn is_gc_tracked(&self) -> bool { + match self { + Self::Itertools(iter) => iter.is_gc_tracked(), + Self::DirScan(scan) => scan.is_gc_tracked(), + Self::List(_) + | Self::Deque(_) + | Self::Tuple(_) + | Self::NamedTuple(_) + | Self::NamedTupleClass(_) + | Self::Dict(_) + | Self::DictKeysView(_) + | Self::DictItemsView(_) + | Self::DictValuesView(_) + | Self::Set(_) + | Self::FrozenSet(_) + | Self::Closure(_) + | Self::FunctionDefaults(_) + | Self::Cell(_) + | Self::HostClass(_) + | Self::HostClassType(_) + | Self::Class(_) + | Self::Instance(_) + | Self::BoundMethod(_) + | Self::DataclassField(_) + | Self::DataclassMethod(_) + | Self::ListIterator(_) + | Self::DequeIterator(_) + | Self::TupleIterator(_) + | Self::DictKeyIterator(_) + | Self::DictItemIterator(_) + | Self::DictValueIterator(_) + | Self::SetIterator(_) + | Self::CallableIterator(_) + | Self::Module(_) + | Self::Coroutine(_) + | Self::GatherFuture(_) + | Self::ExternalFuture(_) + | Self::Partial(_) + | Self::GenericAlias(_) + | Self::Union(_) + | Self::LruCache(_) + | Self::Csv(_) => true, + // Leaf types, plus iterators whose heap refs only point at leaves and so + // cannot close a cycle. Move one up if it gains a container-valued field. + Self::Str(_) + | Self::Bytes(_) + | Self::Range(_) + | Self::Slice(_) + | Self::Exception(_) + | Self::DataclassParams(_) + | Self::StringIterator(_) + | Self::BytesIterator(_) + | Self::RangeIterator(_) + | Self::LongInt(_) + | Self::Complex(_) + | Self::Path(_) + | Self::OpenFile(_) + | Self::RePattern(_) + | Self::ReMatch(_) + | Self::ExtFunction(_) + | Self::Date(_) + | Self::DateTime(_) + | Self::Time(_) + | Self::TimeDelta(_) + | Self::TimeZone(_) + | Self::Random(_) + | Self::HashObject(_) + // A signal dict and a `localcontext()` manager only hold contexts, which are leaves. + | Self::Decimal(_) + | Self::DecimalContext(_) + | Self::DecimalSignalDict(_) + | Self::DecimalContextManager(_) => false, + } + } + + /// Whether calling a `Ref` to this heap data would succeed at dispatch. + /// + /// A conservative subset of the types overriding [`PyTrait::py_call`]: it + /// is what `partial()` and friends screen a callable argument with, and it + /// has never admitted `HostClassType` or `NamedTupleClass`, both of which + /// dispatch perfectly well. Widening it changes what those builtins accept, + /// so it is not simply the list of `py_call` overrides. + #[must_use] + pub(crate) fn is_callable(&self) -> bool { + matches!( + self, + Self::Class(_) + | Self::BoundMethod(_) + | Self::DataclassMethod(_) + | Self::Closure(_) + | Self::FunctionDefaults(_) + | Self::ExtFunction(_) + | Self::Partial(_) + | Self::GenericAlias(_) + | Self::LruCache(_) + ) + } + + /// Returns the Python `Type` for this heap data without requiring VM access. + /// + /// This is a lightweight alternative to the `PyTrait::py_type` dispatch on + /// `HeapReadOutput`, useful in error messages and diagnostics where only a + /// `&Heap` is available (not a full `&VM`). + #[must_use] + pub(crate) fn py_type(&self) -> Type { + match self { + Self::Str(_) => Type::Str, + Self::Bytes(_) => Type::Bytes, + Self::List(_) => Type::List, + Self::Deque(_) => Type::Deque, + Self::Tuple(_) | Self::NamedTuple(_) => Type::Tuple, + Self::NamedTupleClass(_) => Type::Type, + Self::Dict(_) => Type::Dict, + Self::Partial(_) => Type::Partial, + Self::Random(_) => Type::Random, + Self::HashObject(hash) => hash.algorithm().py_type(), + Self::GenericAlias(_) => Type::GenericAlias, + Self::Union(_) => Type::Union, + Self::LruCache(_) => Type::LruCacheWrapper, + Self::DictKeysView(_) => Type::DictKeys, + Self::DictItemsView(_) => Type::DictItems, + Self::DictValuesView(_) => Type::DictValues, + Self::Set(_) => Type::Set, + Self::FrozenSet(_) => Type::FrozenSet, + Self::Closure(_) | Self::FunctionDefaults(_) | Self::ExtFunction(_) => Type::Function, + Self::Cell(_) => Type::Cell, + Self::Range(_) => Type::Range, + Self::Slice(_) => Type::Slice, + Self::Exception(e) => Type::Exception(e.exc_type()), + Self::HostClass(_) => Type::HostClass, + Self::HostClassType(_) => Type::Type, + // A class object's type is `type`; an instance's carries its class id. + Self::Class(_) => Type::Type, + Self::Instance(instance) => Type::Instance(instance.class()), + Self::BoundMethod(_) => Type::Function, + Self::DataclassField(_) => Type::DataclassField, + Self::DataclassMethod(_) => Type::Function, + Self::DataclassParams(_) => Type::DataclassParams, + Self::LongInt(_) => Type::Int, + Self::Complex(_) => Type::Complex, + Self::Module(_) => Type::Module, + Self::Coroutine(_) | Self::GatherFuture(_) | Self::ExternalFuture(_) => Type::Coroutine, + Self::Path(_) => Type::Path, + Self::OpenFile(file) => file.file_type(), + Self::RePattern(_) => Type::RePattern, + Self::ReMatch(_) => Type::ReMatch, + Self::Date(_) => Type::Date, + Self::DateTime(_) => Type::DateTime, + Self::Time(_) => Type::Time, + Self::TimeDelta(_) => Type::TimeDelta, + Self::TimeZone(_) => Type::TimeZone, + Self::ListIterator(_) => Type::ListIterator, + Self::DequeIterator(_) => Type::DequeIterator, + Self::TupleIterator(_) => Type::TupleIterator, + Self::StringIterator(iter) => iter.py_type(), + Self::BytesIterator(_) => Type::BytesIterator, + Self::RangeIterator(_) => Type::RangeIterator, + Self::DictKeyIterator(_) => Type::DictKeyIterator, + Self::DictItemIterator(_) => Type::DictItemIterator, + Self::DictValueIterator(_) => Type::DictValueIterator, + Self::SetIterator(_) => Type::SetIterator, + Self::CallableIterator(_) => Type::CallableIterator, + Self::Itertools(i) => i.py_type(), + Self::DirScan(scan) => scan.py_type(), + Self::Csv(csv) => csv.py_type(), + Self::Decimal(_) => Type::Decimal, + Self::DecimalContext(_) => Type::DecimalContext, + Self::DecimalSignalDict(_) => Type::DecimalSignalDict, + Self::DecimalContextManager(_) => Type::DecimalContextManager, + } + } +} + +/// Thin wrapper around `Value` which is used in the `Cell` variant above. +/// +/// The inner value is the cell's mutable payload. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +#[repr(transparent)] +pub(crate) struct CellValue(pub(crate) Value); + +impl Deref for CellValue { + type Target = Value; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +/// A closure: a function that captures variables from enclosing scopes. +/// +/// Contains a reference to the function definition, a vector of captured cell HeapIds, +/// evaluated default values (if any) and the globals dict it was defined under +/// (if any). When the closure is called, the cells are passed to the frame for +/// variable access. When the closure is dropped, we must decrement the ref +/// count on each captured cell, each default value and the globals dict. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct Closure { + /// The function definition being captured. + #[serde(rename = "F")] + pub func_id: FunctionId, + /// Captured cells from enclosing scopes. Boxed slices rather than `Vec`s + /// (never grown after construction) keep this the size of the largest + /// `HeapData` variant, not larger. + #[serde(rename = "C")] + pub cells: Box<[HeapId]>, + /// Evaluated default parameter values (if any). + #[serde(rename = "D")] + pub defaults: Box<[Value]>, + /// Owned reference to the `exec()` / `eval()` globals dict the closure was + /// defined under; `None` when its globals are module slots. + #[serde(rename = "G")] + pub globals: Option, +} + +/// A `def` that needs a heap object but captures nothing: it has evaluated +/// default values, an explicit globals dict, or both. +/// +/// When the function is called, defaults are cloned for missing optional +/// parameters and the frame resolves globals through the dict. When dropped, +/// we must decrement the ref count on each default value and the dict. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct FunctionDefaults { + /// The function definition being captured. + #[serde(rename = "F")] + pub func_id: FunctionId, + /// Evaluated default parameter values (if any). + #[serde(rename = "D")] + pub defaults: Vec, + /// Owned reference to the `exec()` / `eval()` globals dict the function + /// was defined under; `None` when its globals are module slots. + #[serde(rename = "G")] + pub globals: Option, +} + +impl HeapItem for CellValue { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + self.0.py_dec_ref_ids(stack); + } +} + +impl HeapItem for Closure { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + // Decrement ref count for captured cells + stack.extend(self.cells.iter().copied()); + // Decrement ref count for default values that are heap references + for default in &mut self.defaults { + default.py_dec_ref_ids(stack); + } + stack.extend(self.globals); + } +} + +impl HeapItem for FunctionDefaults { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + // Decrement ref count for default values that are heap references + for default in &mut self.defaults { + default.py_dec_ref_ids(stack); + } + stack.extend(self.globals); + } +} + +/// The shared tail of calling a `def`: both function representations differ only +/// in whether they carry captured cells. +/// +/// The cells and defaults are copied out before dispatching, so no borrow on the +/// callable is live while its body runs and the body may reach it again. +fn call_def( + func_id: FunctionId, + cells: &[HeapId], + defaults: Vec, + globals: Option, + args: ArgValues, + vm: &mut VM<'_>, +) -> RunResult { + defer_drop!(defaults, vm); + vm.call_def_function(func_id, cells, defaults, globals, args) +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, Closure> { + fn py_type(&self, _: &VM<'h>) -> Type { + Type::Function + } + + fn py_len(&self, _: &VM<'h>) -> Option { + None + } + + /// Two closures over the same `def` are equal only if they captured the + /// same cells; the defaults play no part, as in CPython. + fn py_eq_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + Ok(match other.read_heap(vm) { + Some(HeapReadOutput::Closure(other)) => { + let this = self.get(vm.heap); + let other = other.get(vm.heap); + Some(this.func_id == other.func_id && this.cells == other.cells) + } + _ => None, + }) + } + + /// Hashes by `def`, so a closure and its equal share a bucket. + fn py_hash(&self, vm: &mut VM<'h>) -> RunResult> { + Ok(Some(hash_func_id(self.get(vm.heap).func_id))) + } + + fn py_bool(&self, _: &mut VM<'h>) -> RunResult { + Ok(true) + } + + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, _: &mut LazyHeapSet) -> RunResult<()> { + let func_id = self.get(vm.heap).func_id; + Ok(vm.interns.get_function(func_id).py_repr_fmt(f, vm.interns, 0)?) + } + + fn py_call(&mut self, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let closure = self.get(vm.heap); + let (func_id, cells, globals) = (closure.func_id, closure.cells.clone(), closure.globals); + let defaults = closure.defaults.iter().map(|v| v.clone_with_heap(vm)).collect(); + call_def(func_id, &cells, defaults, globals, args, vm) + } +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, FunctionDefaults> { + fn py_type(&self, _: &VM<'h>) -> Type { + Type::Function + } + + fn py_len(&self, _: &VM<'h>) -> Option { + None + } + + /// Equal when they decorate the same `def`: with no captured scope, the + /// defaults are all that could differ and CPython ignores those too. + fn py_eq_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + Ok(match other.read_heap(vm) { + Some(HeapReadOutput::FunctionDefaults(other)) => { + Some(self.get(vm.heap).func_id == other.get(vm.heap).func_id) + } + _ => None, + }) + } + + fn py_hash(&self, vm: &mut VM<'h>) -> RunResult> { + Ok(Some(hash_func_id(self.get(vm.heap).func_id))) + } + + fn py_bool(&self, _: &mut VM<'h>) -> RunResult { + Ok(true) + } + + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, _: &mut LazyHeapSet) -> RunResult<()> { + let func_id = self.get(vm.heap).func_id; + Ok(vm.interns.get_function(func_id).py_repr_fmt(f, vm.interns, 0)?) + } + + fn py_call(&mut self, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let function = self.get(vm.heap); + let (func_id, globals) = (function.func_id, function.globals); + let defaults = function.defaults.iter().map(|v| v.clone_with_heap(vm)).collect(); + call_def(func_id, &[], defaults, globals, args, vm) + } +} + +/// Hashes a function identity, the hash both `def` representations report. +fn hash_func_id(func_id: FunctionId) -> HashValue { + let mut hasher = DefaultHasher::new(); + func_id.hash(&mut hasher); + HashValue::new(hasher.finish()) +} + +impl HeapItem for SimpleException { + fn py_dec_ref_ids(&mut self, _stack: &mut Vec) { + // Exceptions don't contain heap references + } +} + +impl HeapItem for LongInt { + fn py_dec_ref_ids(&mut self, _stack: &mut Vec) { + // LongInt doesn't contain heap references + } +} + +impl HeapItem for Coroutine { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + // Decrement ref count for namespace values that are heap references + for value in &mut self.namespace { + value.py_dec_ref_ids(stack); + } + stack.extend(self.globals); + } +} + +impl HeapItem for GatherFuture { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + // Decrement ref count for items the gather owns (every entry in + // `items` is inc_ref'd at construction time). + stack.extend(self.items.iter().copied()); + // Release per-state heap refs: in-flight slot results plus this + // gather's own awaiter (if `GatherSlot`, it owns an inc_ref on the + // outer gather), or the cached result list once the gather has + // completed successfully. `Pending` and `Failed` carry no heap refs. + match &mut self.state { + GatherState::Awaited(awaited) => { + if let Awaiter::GatherSlot { gather, .. } = &awaited.awaiter { + stack.push(*gather); + } + for result in awaited.results.iter_mut().flatten() { + result.py_dec_ref_ids(stack); + } + } + GatherState::Completed(Value::Ref(id)) => stack.push(*id), + GatherState::Pending | GatherState::Failed(_) | GatherState::Completed(_) => {} + } + } +} + +impl HeapItem for ExternalFuture { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + // `Pending { awaiter: Some(Awaiter::GatherSlot { gather, .. }) }` + // owns an inc_ref on `gather` — release it when this entry is + // freed. `Awaiter::Task` and `None` own nothing. `Resolved` owns + // the cached value; `Failed` carries no heap refs. A pending sleep + // result is owned until resolution takes it. + if let Some(result) = &mut self.sleep_result { + result.py_dec_ref_ids(stack); + } + match &mut self.state { + ExternalFutureState::Resolved(value) => value.py_dec_ref_ids(stack), + ExternalFutureState::Pending { + awaiter: Some(Awaiter::GatherSlot { gather, .. }), + } => stack.push(*gather), + ExternalFutureState::Pending { + awaiter: None | Some(Awaiter::Task(_)), + } + | ExternalFutureState::Failed(_) => {} + } + } +} + +/// Exhaustive concrete-type dispatch shared by storage and logical views. +macro_rules! heap_read_output_py_trait_forward { + ($self:expr, |$value:ident| $body:expr, else $fallback:expr) => { + $crate::heap_data::heap_read_output_py_trait_forward!( + $self, |$value| $body, { + Self::LongInt($value) => $body, + Self::Cell(_) + | Self::Exception(_) + | Self::Module(_) + | Self::Coroutine(_) + | Self::GatherFuture(_) + | Self::ExternalFuture(_) => $fallback, + } + ) + }; + ($self:expr, |$value:ident| $body:expr, {$($custom:tt)*}) => { + match $self { + Self::Str($value) => $body, + Self::Bytes($value) => $body, + Self::List($value) => $body, + Self::Deque($value) => $body, + Self::ListIterator($value) => $body, + Self::DequeIterator($value) => $body, + Self::TupleIterator($value) => $body, + Self::StringIterator($value) => $body, + Self::BytesIterator($value) => $body, + Self::RangeIterator($value) => $body, + Self::DictKeyIterator($value) => $body, + Self::DictItemIterator($value) => $body, + Self::DictValueIterator($value) => $body, + Self::SetIterator($value) => $body, + Self::CallableIterator($value) => $body, + Self::Itertools($value) => $body, + Self::DirScan($value) => $body, + Self::Csv($value) => $body, + Self::Partial($value) => $body, + Self::Random($value) => $body, + Self::HashObject($value) => $body, + Self::GenericAlias($value) => $body, + Self::Union($value) => $body, + Self::LruCache($value) => $body, + Self::Tuple($value) => $body, + Self::NamedTuple($value) => $body, + Self::NamedTupleClass($value) => $body, + Self::Dict($value) => $body, + Self::DictKeysView($value) => $body, + Self::DictItemsView($value) => $body, + Self::DictValuesView($value) => $body, + Self::Set($value) => $body, + Self::FrozenSet($value) => $body, + Self::Range($value) => $body, + Self::Slice($value) => $body, + Self::HostClass($value) => $body, + Self::HostClassType($value) => $body, + Self::Class($value) => $body, + Self::Instance($value) => $body, + Self::BoundMethod($value) => $body, + Self::DataclassField($value) => $body, + Self::DataclassMethod($value) => $body, + Self::DataclassParams($value) => $body, + Self::Complex($value) => $body, + Self::Path($value) => $body, + Self::OpenFile($value) => $body, + Self::RePattern($value) => $body, + Self::ReMatch($value) => $body, + Self::Date($value) => $body, + Self::DateTime($value) => $body, + Self::Time($value) => $body, + Self::TimeDelta($value) => $body, + Self::TimeZone($value) => $body, + Self::Closure($value) => $body, + Self::FunctionDefaults($value) => $body, + Self::ExtFunction($value) => $body, + Self::Decimal($value) => $body, + Self::DecimalContext($value) => $body, + Self::DecimalSignalDict($value) => $body, + Self::DecimalContextManager($value) => $body, + $($custom)* + } + }; +} + +pub(crate) use heap_read_output_py_trait_forward; + +// Only unmigrated protocols dispatch here; normalized operations use PyValue. +impl<'h> PyTrait<'h> for HeapReadOutput<'h> { + fn py_len(&self, vm: &VM<'h>) -> Option { + heap_read_output_py_trait_forward!(self, |value| value.py_len(vm), else None) + } + + /// Forwards so host class instances and named tuples name their real class. + fn py_type_name(&self, vm: &VM<'h>) -> Cow<'h, str> { + heap_read_output_py_trait_forward!( + self, + |value| value.py_type_name(vm), + else self.py_type(vm).name(vm.heap, vm.interns) + ) + } + + fn py_matmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + heap_read_output_py_trait_forward!(self, |value| value.py_matmul_impl(other, vm), else Ok(None)) + } + + fn py_rmatmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + heap_read_output_py_trait_forward!(self, |value| value.py_rmatmul_impl(other, vm), else Ok(None)) + } + + fn py_call(&mut self, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + heap_read_output_py_trait_forward!( + self, + |value| value.py_call(args, vm), + else { + args.drop_with(vm); + Err(ExcType::type_error_not_callable_object(&self.py_type_name(vm))) + } + ) + } + + fn py_is_iterator(&self, vm: &VM<'h>) -> bool { + match self { + // A user-defined class is an iterator only if it defines `__next__`. + Self::Instance(inst) => inst.py_is_iterator(vm), + // Every built-in iterator is identified by its type, so there is no + // list to keep in step with new iterator types here. + other => other.py_type(vm).is_iterator(), + } + } + + fn py_is_iterable(&self, vm: &VM<'h>) -> bool { + heap_read_output_py_trait_forward!(self, |value| value.py_is_iterable(vm), else false) + } + + fn py_is_context_manager(&self, vm: &VM<'h>) -> bool { + // Only types that implement the protocol return true; everything else + // inherits the default `false`. The `with` statement gates `py_enter` + // / `py_exit` on this check, so a real context manager whose + // `__enter__` happens to raise `AttributeError` is no longer + // misdiagnosed as "not a context manager". + heap_read_output_py_trait_forward!(self, |value| value.py_is_context_manager(vm), else false) + } + + fn py_enter(&mut self, vm: &mut VM<'h>) -> RunResult { + // Only types that override the trait default need explicit arms; all + // others fall through to the catch-all `AttributeError`, matching how + // `py_call_attr` is structured. + heap_read_output_py_trait_forward!( + self, + |value| value.py_enter(vm), + else { Err(ExcType::attribute_error(self.py_type_name(vm), "__enter__")) } + ) + } + + fn py_exit(&mut self, vm: &mut VM<'h>, exc: Option) -> RunResult { + heap_read_output_py_trait_forward!( + self, + |value| value.py_exit(vm, exc), + else { Err(ExcType::attribute_error(self.py_type_name(vm), "__exit__")) } + ) + } + + fn py_type(&self, vm: &VM<'h>) -> Type { + heap_read_output_py_trait_forward!( + self, + |value| value.py_type(vm), + else { + match self { + Self::Cell(_) => Type::Cell, + Self::Exception(e) => e.py_type(vm), + Self::Module(_) => Type::Module, + Self::Coroutine(_) | Self::GatherFuture(_) | Self::ExternalFuture(_) => Type::Coroutine, + _ => unreachable!("py-trait variants handled by heap_read_output_py_trait_forward"), + } + } + ) + } + + fn py_eq_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + heap_read_output_py_trait_forward!( + self, + |value| value.py_eq_impl(other, vm), + else { + match self { + Self::Cell(_) + | Self::Exception(_) + | Self::Module(_) + | Self::Coroutine(_) + | Self::GatherFuture(_) + | Self::ExternalFuture(_) => Ok(None), + _ => unreachable!("py-trait variants handled by heap_read_output_py_trait_forward"), + } + } + ) + } + + /// Dispatches hashing to per-type `PyTrait` implementations where possible. + fn py_hash(&self, vm: &mut VM<'h>) -> RunResult> { + heap_read_output_py_trait_forward!( + self, + |value| value.py_hash(vm), + else { + match self { + Self::Cell(value) => Ok(Some(identity_hash(value.id()))), + // modules hash by identity, as CPython's do + Self::Module(value) => Ok(Some(identity_hash(value.id()))), + Self::Exception(_) + | Self::Coroutine(_) + | Self::GatherFuture(_) + | Self::ExternalFuture(_) => Ok(None), + _ => unreachable!("py-trait variants handled by heap_read_output_py_trait_forward"), + } + } + ) + } + + fn py_iadd_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + heap_read_output_py_trait_forward!(self, |value| value.py_iadd_impl(other, vm), else Ok(false)) + } + + fn py_isub_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + heap_read_output_py_trait_forward!(self, |value| value.py_isub_impl(other, vm), else Ok(false)) + } + + fn py_iand_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + heap_read_output_py_trait_forward!(self, |value| value.py_iand_impl(other, vm), else Ok(false)) + } + + fn py_ior_impl(&mut self, other: &Value, vm: &mut VM<'h>) -> RunResult { + heap_read_output_py_trait_forward!(self, |value| value.py_ior_impl(other, vm), else Ok(false)) + } + + fn py_cmp_op(&self, other: &Value, op: CmpOperator, vm: &mut VM<'h>) -> RunResult> { + heap_read_output_py_trait_forward!(self, |value| value.py_cmp_op(other, op, vm), else Ok(None)) + } + + fn py_setitem(&mut self, key: Value, value: Value, vm: &mut VM<'h>) -> RunResult<()> { + heap_read_output_py_trait_forward!( + self, + |item| item.py_setitem(key, value, vm), + else { + key.drop_with(vm); + value.drop_with(vm); + Err(ExcType::type_error_not_sub_assignment( + &self.py_type_name(vm), + )) + } + ) + } + + fn py_set_attr(&mut self, name: &EitherStr, value: Value, vm: &mut VM<'h>) -> RunResult<()> { + heap_read_output_py_trait_forward!( + self, + |item| item.py_set_attr(name, value, vm), + else { + value.drop_with(vm); + let type_name = self.py_type_name(vm); + Err(ExcType::attribute_error_no_setattr( + &type_name, + name.as_str(vm.interns), + )) + } + ) + } + + fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { + heap_read_output_py_trait_forward!( + self, + |value| value.py_getattr(attr, vm), + else { + match self { + Self::Module(m) => Ok(m.py_getattr(attr, vm)), + Self::Exception(e) => Ok(e.py_getattr(attr, vm)), + _ => Ok(None), + } + } + ) + } + + fn py_iter(&self, vm: &mut VM<'h>) -> RunResult { + match self { + Self::Str(value) => value.py_iter(vm), + Self::Bytes(value) => value.py_iter(vm), + Self::List(value) => value.py_iter(vm), + Self::Deque(value) => value.py_iter(vm), + Self::ListIterator(value) => value.py_iter(vm), + Self::DequeIterator(value) => value.py_iter(vm), + Self::TupleIterator(value) => value.py_iter(vm), + Self::StringIterator(value) => value.py_iter(vm), + Self::BytesIterator(value) => value.py_iter(vm), + Self::RangeIterator(value) => value.py_iter(vm), + Self::DictKeyIterator(value) => value.py_iter(vm), + Self::DictItemIterator(value) => value.py_iter(vm), + Self::DictValueIterator(value) => value.py_iter(vm), + Self::SetIterator(value) => value.py_iter(vm), + Self::CallableIterator(value) => value.py_iter(vm), + Self::Itertools(value) => value.py_iter(vm), + Self::DirScan(value) => value.py_iter(vm), + Self::Csv(value) => value.py_iter(vm), + Self::Tuple(value) => value.py_iter(vm), + Self::NamedTuple(value) => value.py_iter(vm), + Self::Dict(value) => value.py_iter(vm), + Self::DictKeysView(value) => value.py_iter(vm), + Self::DictItemsView(value) => value.py_iter(vm), + Self::DictValuesView(value) => value.py_iter(vm), + Self::Set(value) => value.py_iter(vm), + Self::FrozenSet(value) => value.py_iter(vm), + Self::Range(value) => value.py_iter(vm), + Self::Slice(value) => value.py_iter(vm), + Self::HostClass(value) => value.py_iter(vm), + Self::HostClassType(value) => value.py_iter(vm), + Self::Class(value) => value.py_iter(vm), + Self::Instance(value) => value.py_iter(vm), + Self::BoundMethod(value) => value.py_iter(vm), + Self::DataclassField(value) => value.py_iter(vm), + Self::DataclassMethod(value) => value.py_iter(vm), + Self::DataclassParams(value) => value.py_iter(vm), + Self::Path(value) => value.py_iter(vm), + Self::OpenFile(value) => value.py_iter(vm), + Self::ReMatch(value) => value.py_iter(vm), + Self::RePattern(value) => value.py_iter(vm), + Self::Date(value) => value.py_iter(vm), + Self::DateTime(value) => value.py_iter(vm), + Self::Time(value) => value.py_iter(vm), + Self::TimeDelta(value) => value.py_iter(vm), + Self::TimeZone(value) => value.py_iter(vm), + Self::DecimalSignalDict(value) => value.py_iter(vm), + Self::Decimal(_) + | Self::DecimalContext(_) + | Self::DecimalContextManager(_) + | Self::NamedTupleClass(_) + | Self::Closure(_) + | Self::FunctionDefaults(_) + | Self::ExtFunction(_) + | Self::Partial(_) + | Self::Random(_) + | Self::HashObject(_) + | Self::GenericAlias(_) + | Self::Union(_) + | Self::LruCache(_) + | Self::Cell(_) + | Self::Exception(_) + | Self::LongInt(_) + | Self::Complex(_) + | Self::Module(_) + | Self::Coroutine(_) + | Self::GatherFuture(_) + | Self::ExternalFuture(_) => Err(ExcType::type_error_not_iterable(&self.py_type_name(vm))), + } + } + + fn py_next(&mut self, vm: &mut VM<'h>) -> RunResult> { + match self { + Self::Str(value) => value.py_next(vm), + Self::Bytes(value) => value.py_next(vm), + Self::List(value) => value.py_next(vm), + Self::ListIterator(value) => value.py_next(vm), + Self::DequeIterator(value) => value.py_next(vm), + Self::TupleIterator(value) => value.py_next(vm), + Self::StringIterator(value) => value.py_next(vm), + Self::BytesIterator(value) => value.py_next(vm), + Self::RangeIterator(value) => value.py_next(vm), + Self::DictKeyIterator(value) => value.py_next(vm), + Self::DictItemIterator(value) => value.py_next(vm), + Self::DictValueIterator(value) => value.py_next(vm), + Self::SetIterator(value) => value.py_next(vm), + Self::CallableIterator(value) => value.py_next(vm), + Self::Itertools(value) => value.py_next(vm), + Self::DirScan(value) => value.py_next(vm), + Self::Csv(value) => value.py_next(vm), + Self::Tuple(value) => value.py_next(vm), + Self::NamedTuple(value) => value.py_next(vm), + Self::Dict(value) => value.py_next(vm), + Self::DictKeysView(value) => value.py_next(vm), + Self::DictItemsView(value) => value.py_next(vm), + Self::DictValuesView(value) => value.py_next(vm), + Self::Set(value) => value.py_next(vm), + Self::FrozenSet(value) => value.py_next(vm), + Self::Range(value) => value.py_next(vm), + Self::Slice(value) => value.py_next(vm), + Self::HostClass(value) => value.py_next(vm), + Self::HostClassType(value) => value.py_next(vm), + Self::Class(value) => value.py_next(vm), + Self::Instance(value) => value.py_next(vm), + Self::BoundMethod(value) => value.py_next(vm), + Self::DataclassField(value) => value.py_next(vm), + Self::DataclassMethod(value) => value.py_next(vm), + Self::DataclassParams(value) => value.py_next(vm), + Self::Path(value) => value.py_next(vm), + Self::OpenFile(value) => value.py_next(vm), + Self::ReMatch(value) => value.py_next(vm), + Self::RePattern(value) => value.py_next(vm), + Self::Date(value) => value.py_next(vm), + Self::DateTime(value) => value.py_next(vm), + Self::Time(value) => value.py_next(vm), + Self::TimeDelta(value) => value.py_next(vm), + Self::TimeZone(value) => value.py_next(vm), + other => Err(ExcType::type_error_not_iterator(&other.py_type_name(vm))), + } + } +} diff --git a/crates/bashkit-monty/src/heap_traits.rs b/crates/bashkit-monty/src/heap_traits.rs new file mode 100644 index 000000000..99b853085 --- /dev/null +++ b/crates/bashkit-monty/src/heap_traits.rs @@ -0,0 +1,273 @@ +use std::{ + mem::ManuallyDrop, + ptr::addr_of, + vec::{Drain, IntoIter}, +}; + +use smallvec::SmallVec; + +use crate::{ + heap::{Heap, HeapId}, + value::Value, +}; + +/// Collects owned heap references when a heap entry is released. +/// +/// `HeapData` variants owning heap references implement this trait (or are +/// handled inline in `py_dec_ref_ids_for_data`) so reference-count cleanup can +/// walk children iteratively without requiring the Python-level `PyTrait` API; +/// leaf variants with no children fall through the dispatch's `_ => {}` arm. +pub(crate) trait HeapItem { + /// Pushes every owned heap reference onto the iterative cleanup stack. + /// + /// Owned `HeapId` fields must be documented as owned and pushed exactly + /// once. With `memory-model-checks`, delegation also marks contained + /// `Value`s as `Dereferenced`. + fn py_dec_ref_ids(&mut self, stack: &mut Vec); +} + +/// Gives cleanup machinery access to an owned heap. +pub(crate) trait ContainsHeap { + fn heap(&self) -> &Heap; + fn heap_mut(&mut self) -> &mut Heap; +} + +impl ContainsHeap for Heap { + fn heap(&self) -> &Self { + self + } + #[inline] + fn heap_mut(&mut self) -> &mut Self { + self + } +} + +/// Cleanup for types holding heap (and possibly VM-side) references that must be +/// released explicitly — Rust's `Drop` cannot, since it has no heap access. +/// +/// `C` is whatever cleanup context the caller has on hand: a [`Heap`], a +/// [`HeapReader`](crate::heap::HeapReader), the [`VM`](crate::bytecode::VM), or the +/// json `Encoder`. The bound on each impl states the capability the value needs: +/// heap-only values bound `C` by [`ContainsHeap`] (satisfied by all of those), +/// while values holding a [`RecursionToken`](crate::bytecode::RecursionToken) bound +/// `C` by [`ContainsVM`](crate::bytecode::ContainsVM) (satisfied only by `VM` / +/// `Encoder`, since the recursion counter is unreachable through a bare heap). +/// +/// **All implementers must be cleaned up on every code path** — not just the happy +/// path, but early returns via `?`, `continue`, conditional branches, etc. A missed +/// call leaks reference counts. Prefer [`defer_drop!`] or [`DropGuard`] to guarantee +/// cleanup automatically rather than inserting manual calls in every branch. +pub(crate) trait DropWithContext { + /// Consume `self`, releasing every heap/VM reference it owns through `ctx`. + /// + /// Implementations owning raw `HeapId`s may call `Heap::dec_ref` here. Callers + /// should prefer a guard unless this is a simple, linear cleanup path. + fn drop_with(self, ctx: &mut C); +} + +impl> DropWithContext for Option { + #[inline] + fn drop_with(self, ctx: &mut C) { + if let Some(value) = self { + value.drop_with(ctx); + } + } +} + +impl> DropWithContext for Vec { + fn drop_with(self, ctx: &mut C) { + for value in self { + value.drop_with(ctx); + } + } +} + +impl DropWithContext for SmallVec +where + A::Item: DropWithContext, +{ + fn drop_with(self, ctx: &mut C) { + for value in self { + value.drop_with(ctx); + } + } +} + +impl> DropWithContext for IntoIter { + fn drop_with(self, ctx: &mut C) { + for value in self { + value.drop_with(ctx); + } + } +} + +impl> DropWithContext for Drain<'_, U> { + fn drop_with(self, ctx: &mut C) { + for value in self { + value.drop_with(ctx); + } + } +} + +impl DropWithContext for [Value; N] +where + Value: DropWithContext, +{ + fn drop_with(self, ctx: &mut C) { + for value in self { + // Qualified call: `Value`'s inherent `drop_with` would otherwise + // shadow the trait method and demand `C: ContainsHeap` here. + DropWithContext::drop_with(value, ctx); + } + } +} + +impl, V: DropWithContext> DropWithContext for (U, V) { + fn drop_with(self, ctx: &mut C) { + let (left, right) = self; + left.drop_with(ctx); + right.drop_with(ctx); + } +} + +/// RAII guard that ensures a [`DropWithContext`] value is cleaned up on every code path. +/// +/// The guard's `Drop` impl calls [`DropWithContext::drop_with`] automatically, so +/// cleanup happens whether the scope exits normally, via `?`, `continue`, early return, +/// or any other branch. This eliminates the need to manually insert `drop_with` +/// calls in every branch. +/// +/// `C` is the cleanup context (`Heap` / `HeapReader` / `VM` / `Encoder`); it is *not* +/// bounded here, so a single guard type serves both heap-only values and +/// recursion-token holders — the `V: DropWithContext` bound is what constrains the +/// pairing, exactly as on a bare `drop_with` call. +/// +/// On the normal path, the guarded value can be borrowed via [`as_parts`](Self::as_parts) / +/// [`as_parts_mut`](Self::as_parts_mut), or reclaimed via [`into_inner`](Self::into_inner) / +/// [`into_parts`](Self::into_parts) (which consume the guard without dropping the value). +/// +/// Prefer the [`defer_drop!`] macro for the common case where you just need to ensure a +/// value is dropped at scope exit. Use `DropGuard` directly when you need to conditionally +/// reclaim the value (e.g. push it back onto the stack on success) or need mutable access +/// to both the value and context through [`as_parts_mut`](Self::as_parts_mut). +pub(crate) struct DropGuard<'a, C, V: DropWithContext> { + // manually dropped because it needs to be dropped by move. + value: ManuallyDrop, + ctx: &'a mut C, +} + +impl<'a, C, V: DropWithContext> DropGuard<'a, C, V> { + /// Creates a new `DropGuard` for the given value and context. + #[inline] + pub fn new(value: V, ctx: &'a mut C) -> Self { + Self { + value: ManuallyDrop::new(value), + ctx, + } + } + + /// Consumes the guard and returns the contained value without dropping it. + /// + /// Use this when the value should survive beyond the guard's scope (e.g. returning + /// a computed result from a function that used the guard for error-path safety). + #[inline] + pub fn into_inner(self) -> V { + let mut this = ManuallyDrop::new(self); + // SAFETY: [DH] - `ManuallyDrop::new(self)` prevents `Drop` on self, so we can take the value out + #[expect(unsafe_code)] + unsafe { + ManuallyDrop::take(&mut this.value) + } + } + + /// Borrows the value (immutably) and context (mutably) out of the guard. + /// + /// This is what [`defer_drop!`] calls internally. The returned references are tied + /// to the guard's lifetime, so the value cannot escape. + #[inline] + pub fn as_parts(&mut self) -> (&V, &mut C) { + (&self.value, self.ctx) + } + + /// Borrows the value (mutably) and context (mutably) out of the guard. + /// + /// This is what [`defer_drop_mut!`] calls internally. Use this when the value needs + /// to be mutated in place (e.g. advancing an iterator, swapping during min/max). + #[inline] + pub fn as_parts_mut(&mut self) -> (&mut V, &mut C) { + (&mut self.value, self.ctx) + } + + /// Consumes the guard and returns the value and context separately, without dropping. + /// + /// Use this when you need to reclaim both the value *and* the context reference — for + /// example, to push the value back onto the VM stack via the heap owner. + #[inline] + pub fn into_parts(self) -> (V, &'a mut C) { + let mut this = ManuallyDrop::new(self); + // SAFETY: [DH] - `ManuallyDrop` prevents `Drop` on self, so we can recover the parts + #[expect(unsafe_code)] + unsafe { + (ManuallyDrop::take(&mut this.value), addr_of!(this.ctx).read()) + } + } + + /// Borrows just the context out of the guard + #[inline] + pub fn ctx(&mut self) -> &mut C { + self.ctx + } +} + +impl> Drop for DropGuard<'_, C, V> { + fn drop(&mut self) { + // SAFETY: [DH] - value is never manually dropped until this point + #[expect(unsafe_code)] + unsafe { ManuallyDrop::take(&mut self.value) }.drop_with(self.ctx); + } +} + +/// The preferred way to ensure a [`DropWithContext`] value is cleaned up on every code path. +/// +/// Creates a [`DropGuard`] and immediately rebinds `$value` as `&V` and `$ctx` as +/// `&mut C` via [`DropGuard::as_parts`]. The original owned value is moved into the +/// guard, which will call [`DropWithContext::drop_with`] when scope exits — whether +/// that's normal completion, early return via `?`, `continue`, or any other branch. +/// +/// Beyond safety, this is often much more concise than inserting `drop_with` calls +/// in every branch of complex control flow. For mutable access to the value, use +/// [`defer_drop_mut!`](crate::defer_drop_mut). +/// +/// # Limitation +/// +/// The macro rebinds `$ctx` as a new `let` binding, so it cannot be used when `$ctx` +/// is `self`. In `&mut self` methods, first assign `let this = self;` and pass `this`. +#[macro_export] +macro_rules! defer_drop { + ($value:ident, $ctx:ident) => { + let mut _guard = $crate::heap::DropGuard::new($value, $ctx); + #[allow( + clippy::allow_attributes, + reason = "the reborrowed parts may not both be used in every case, so allow unused vars to avoid warnings" + )] + #[allow(unused_variables)] + let ($value, $ctx) = _guard.as_parts(); + }; +} + +/// Like [`defer_drop!`](crate::defer_drop), but rebinds `$value` as `&mut V` via [`DropGuard::as_parts_mut`]. +/// +/// Use this when the value needs to be mutated in place — for example, advancing an +/// iterator with `for_next()`, or swapping values during a min/max comparison. +#[macro_export] +macro_rules! defer_drop_mut { + ($value:ident, $ctx:ident) => { + let mut _guard = $crate::heap::DropGuard::new($value, $ctx); + #[allow( + clippy::allow_attributes, + reason = "the reborrowed parts may not both be used in every case, so allow unused vars to avoid warnings" + )] + #[allow(unused_variables)] + let ($value, $ctx) = _guard.as_parts_mut(); + }; +} diff --git a/crates/bashkit-monty/src/identity.rs b/crates/bashkit-monty/src/identity.rs new file mode 100644 index 000000000..8812d7619 --- /dev/null +++ b/crates/bashkit-monty/src/identity.rs @@ -0,0 +1,176 @@ +//! Structural identities and their injective Python integer encoding. +//! +//! Immediate values need allocation-free identity comparison, while `id()` +//! must distinguish every identity category. Compact identities remain inline +//! Python integers; only encodings outside `i64` require a heap `LongInt`. + +use serde::Serialize; + +use crate::{ + builtins::Builtins, + heap::{Heap, HeapId}, + modules::ModuleFunctions, + types::{LongInt, Property}, + value::{Marker, Value}, +}; + +/// Number of low bits reserved for the identity category. +const TAG_BITS: u8 = 5; +/// Largest byte payload that can be shifted into a `u128` after adding its sentinel. +const MAX_FIXED_BYTES: usize = 14; + +/// Complete identity key for a runtime value. +/// +/// Equality is the implementation of Python's `is`; the integer encoding is +/// injective and used to expose the same key through `id()`. `Hash` lets +/// identity sets answer "seen this object?" in O(1) (see the dict/set probes). +#[derive(PartialEq, Eq, Hash)] +pub(crate) enum Identity { + /// Internal uninitialized-value sentinel. + Undefined, + /// Python's `Ellipsis` singleton. + Ellipsis, + /// Python's `NotImplemented` singleton. + NotImplemented, + /// Python's `None` singleton. + None, + /// Boolean singleton identity. + Bool(bool), + /// Value-based identity for an immediate integer. + Int(i64), + /// Bitwise identity for an immediate float. + Float(u64), + /// Identity of an interned string. + InternString(usize), + /// Identity of an interned bytes value. + InternBytes(usize), + /// Identity of an interned long integer literal. + InternLongInt(usize), + /// Identity of an interpreter builtin. + Builtin(Builtins), + /// Identity of a standard-library function. + ModuleFunction(ModuleFunctions), + /// Identity of a sandbox-defined function. + DefFunction(usize), + /// Identity of an interpreter marker. + Marker(Marker), + /// Identity of an interpreter property descriptor. + Property(Property), + /// Identity of an arena-allocated object. + Heap(usize), +} + +impl Identity { + /// Builds the structural identity used by both `is` and `id()`. + pub(crate) fn new(value: &Value) -> Self { + match value { + Value::Undefined => Self::Undefined, + Value::Ellipsis => Self::Ellipsis, + Value::NotImplemented => Self::NotImplemented, + Value::None => Self::None, + Value::Bool(value) => Self::Bool(*value), + Value::Int(value) => Self::Int(*value), + Value::Float(value) => Self::Float(value.to_bits()), + Value::InternString(id) => Self::InternString(id.index()), + Value::InternBytes(id) => Self::InternBytes(id.index()), + Value::InternLongInt(id) => Self::InternLongInt(id.index()), + Value::Builtin(builtin) => Self::Builtin(*builtin), + Value::ModuleFunction(function) => Self::ModuleFunction(*function), + Value::DefFunction(id) => Self::DefFunction(id.index()), + Value::Marker(marker) => Self::Marker(*marker), + Value::Property(property) => Self::Property(*property), + Value::Ref(id) => Self::Heap(id.index()), + #[cfg(feature = "memory-model-checks")] + Value::Dereferenced => panic!("Cannot get identity of Dereferenced object"), + } + } + + /// Builds the identity of an arena-allocated object. + pub(crate) fn from_heap_id(id: HeapId) -> Self { + Self::Heap(id.index()) + } + + /// Encodes this key as the nonnegative integer exposed by Python's `id()`. + pub(crate) fn encoded(&self) -> u128 { + let payload = match self { + Self::Undefined | Self::Ellipsis | Self::NotImplemented | Self::None => 0, + Self::Bool(value) => u128::from(*value), + Self::Int(value) => u128::from(zigzag_i64(*value)), + Self::Float(bits) => u128::from(compact_float_bits(*bits)), + Self::InternString(index) + | Self::InternBytes(index) + | Self::InternLongInt(index) + | Self::DefFunction(index) + | Self::Heap(index) => u128::try_from(*index).expect("usize fits in u128"), + Self::Builtin(value) => fixed_serde_payload(value), + Self::ModuleFunction(value) => fixed_serde_payload(value), + Self::Marker(value) => fixed_serde_payload(value), + Self::Property(value) => fixed_serde_payload(value), + }; + (payload << TAG_BITS) | u128::from(self.tag()) + } + + /// Encodes this key as a Python integer. + /// + /// Returns an immediate integer when possible, otherwise allocating a `LongInt`. + pub(crate) fn into_value(self, heap: &Heap) -> Value { + LongInt::value_from_u128(self.encoded(), heap) + } + + /// Returns the stable low-bit category tag for this identity variant. + fn tag(&self) -> u8 { + match self { + Self::Undefined => 0, + Self::Ellipsis => 1, + Self::NotImplemented => 2, + Self::None => 3, + Self::Bool(_) => 4, + Self::Int(_) => 5, + Self::Float(_) => 6, + Self::InternString(_) => 7, + Self::InternBytes(_) => 8, + Self::InternLongInt(_) => 9, + Self::Builtin(_) => 10, + Self::ModuleFunction(_) => 11, + Self::DefFunction(_) => 12, + Self::Marker(_) => 14, + Self::Property(_) => 15, + Self::Heap(_) => 16, + } + } +} + +/// Returns a prefix-preserving integer for a short byte sequence. +fn bytes_payload(bytes: &[u8]) -> u128 { + bytes + .iter() + .fold(1, |payload, byte| (payload << u8::BITS) | u128::from(*byte)) +} + +/// Serializes a small enum payload into a stack buffer and preserves its length. +fn fixed_serde_payload(value: &impl Serialize) -> u128 { + let mut buffer = [0; MAX_FIXED_BYTES]; + let serialized = postcard::to_slice(value, &mut buffer).expect("identity enum payload fits in 14 bytes"); + bytes_payload(serialized) +} + +/// Maps signed integers into `u64` while keeping small magnitudes compact. +fn zigzag_i64(value: i64) -> u64 { + if value >= 0 { + value.unsigned_abs() << 1 + } else { + ((value.unsigned_abs() - 1) << 1) | 1 + } +} + +/// Reorders float fields so common powers of two have compact identities. +fn compact_float_bits(bits: u64) -> u64 { + const MANTISSA_BITS: u8 = 52; + const EXPONENT_MASK: u64 = (1 << 11) - 1; + const MANTISSA_MASK: u64 = (1 << MANTISSA_BITS) - 1; + + let sign = bits >> 63; + let exponent = (bits >> MANTISSA_BITS) & EXPONENT_MASK; + let mantissa = bits & MANTISSA_MASK; + (mantissa << 12) | (sign << 11) | exponent +} diff --git a/crates/bashkit-monty/src/intern.rs b/crates/bashkit-monty/src/intern.rs new file mode 100644 index 000000000..7b14f8443 --- /dev/null +++ b/crates/bashkit-monty/src/intern.rs @@ -0,0 +1,3005 @@ +//! String, bytes, and long integer interning for efficient storage of literals and identifiers. +//! +//! This module provides interners that store unique strings, bytes, and long integers in vectors +//! and return indices (`StringId`, `BytesId`, `LongIntId`) for efficient storage and comparison. +//! This avoids the overhead of cloning strings or using atomic reference counting. +//! +//! One table serves parsing, preparation, compilation and execution. Runtime paths +//! can append static strings without invalidating existing borrows. +//! +//! StringIds are laid out as follows: +//! * 0 to 127 - single character strings for all 128 ASCII characters +//! * 128 - the empty string +//! * 129 to 2³¹-1 - strings interned per executor +//! * 2³¹ and above - snippet filename identities, never Python string values +//! +//! Other static strings occupy ordinary executor-local slots. Their interner entries +//! retain a [`StaticStrings`] tag for dispatch, while snapshots serialize only +//! their text so another build can load an unknown static string as owned text. + +mod compile; +mod storage; + +use std::{ + cell::{Cell, RefCell}, + collections::BTreeMap, + mem, + slice::from_ref, + str::FromStr, + sync::{Arc, LazyLock}, +}; + +use ahash::{AHashMap, AHashSet}; +pub(crate) use compile::CompileInterns; +use num_bigint::BigInt; +use storage::Entries; +use strum::{EnumString, FromRepr, IntoStaticStr}; + +use crate::{ + frozen::FrozenFunction, + function::Function, + hash::{HashValue, RESERVED_STRING_HASHES, WithHash, hash_python_str}, +}; + +/// Index into the string interner's storage. +/// +/// Uses `u32` to save space (4 bytes vs 8 bytes for `usize`). This limits us to +/// ~4 billion unique interns, which is more than sufficient. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)] +pub struct StringId(u32); + +impl StringId { + /// Executor-independent ID for the empty string, immediately after ASCII. + pub const EMPTY: Self = Self(128); + + /// Creates a StringId from a raw index value. + /// + /// Used by the bytecode VM to reconstruct StringIds from operands stored + /// in bytecode. The caller is responsible for ensuring the index is valid. + #[inline] + pub fn from_index(index: u16) -> Self { + Self(u32::from(index)) + } + + /// Returns the raw index value. + #[inline] + pub fn index(self) -> usize { + self.0 as usize + } + + /// Returns the StringId for an ASCII byte. + #[must_use] + pub const fn from_ascii(byte: u8) -> Self { + Self(byte as u32) + } +} + +/// Executor-local intern IDs follow ASCII and the empty string. +const INTERN_STRING_ID_OFFSET: usize = RESERVED_STRS.len(); + +/// Strings runtime paths can materialize without a corresponding source name. +const CORE_STATIC_STRINGS: &[StaticStrings] = &[ + StaticStrings::Module, + StaticStrings::NoneRepr, + StaticStrings::TrueRepr, + StaticStrings::FalseRepr, + StaticStrings::EllipsisRepr, + StaticStrings::NotImplementedRepr, + StaticStrings::DunderMain, + StaticStrings::DunderDoc, +]; + +/// Executor-independent text for ASCII IDs 0–127 and the empty-string ID 128. +/// Hashes in [`crate::hash::RESERVED_STRING_HASHES`] use the same indices. +pub(crate) static RESERVED_STRS: [&str; 129] = const { + // Initialize array of 128 bytes which will be used as the raw storage + const ASCII_BYTES: [u8; 128] = const { + let mut bytes: [u8; 128] = [0; 128]; + let mut i: u8 = 0; + while i < 128 { + bytes[i as usize] = i; + i += 1; + } + bytes + }; + // Index into the above array to build the `&'static str` forms + let mut strs: [&str; 129] = [""; 129]; + let mut i = 0; + while i < 128 { + strs[i] = match str::from_utf8(from_ref(&ASCII_BYTES[i])) { + Ok(s) => s, + Err(_) => panic!("invalid ascii byte"), + }; + i += 1; + } + strs +}; + +/// Static string values known at compile time. +/// +/// The `Ascii*` variants and [`Self::EmptyString`] pin the discriminants +/// [`get_static_string`] reverses with [`FromRepr`](strum::FromRepr), so they +/// stay in code-point order. Every variant after them is in alphabetical +/// order by variant name, purely so that two branches adding a string rarely +/// touch the same line; nothing reads those discriminants. Interner entries +/// serialize as text and recover a tag only when the loading build recognizes +/// that text, so reordering them does not invalidate a dump. +/// +/// `use_phf` makes the derived `FromStr` (run for every string interned, compiled +/// or loaded from a dump) a compile-time perfect-hash lookup. strum's default is +/// a `match` that LLVM turns into a chain of comparisons per text length. +#[repr(u16)] +#[derive(Debug, Clone, Copy, EnumString, FromRepr, IntoStaticStr, PartialEq, Eq, Hash)] +#[strum(serialize_all = "snake_case", use_phf)] +pub enum StaticStrings { + /// ASCII character 0x00. + #[strum(serialize = "\x00")] + AsciiNull = 0, + /// ASCII character 0x01. + #[strum(serialize = "\x01")] + AsciiStartOfHeading = 1, + /// ASCII character 0x02. + #[strum(serialize = "\x02")] + AsciiStartOfText = 2, + /// ASCII character 0x03. + #[strum(serialize = "\x03")] + AsciiEndOfText = 3, + /// ASCII character 0x04. + #[strum(serialize = "\x04")] + AsciiEndOfTransmission = 4, + /// ASCII character 0x05. + #[strum(serialize = "\x05")] + AsciiEnquiry = 5, + /// ASCII character 0x06. + #[strum(serialize = "\x06")] + AsciiAcknowledge = 6, + /// ASCII character 0x07. + #[strum(serialize = "\x07")] + AsciiBell = 7, + /// ASCII character 0x08. + #[strum(serialize = "\x08")] + AsciiBackspace = 8, + /// ASCII character 0x09. + #[strum(serialize = "\x09")] + AsciiTab = 9, + /// ASCII character 0x0a. + #[strum(serialize = "\x0a")] + AsciiLineFeed = 10, + /// ASCII character 0x0b. + #[strum(serialize = "\x0b")] + AsciiVerticalTab = 11, + /// ASCII character 0x0c. + #[strum(serialize = "\x0c")] + AsciiFormFeed = 12, + /// ASCII character 0x0d. + #[strum(serialize = "\x0d")] + AsciiCarriageReturn = 13, + /// ASCII character 0x0e. + #[strum(serialize = "\x0e")] + AsciiShiftOut = 14, + /// ASCII character 0x0f. + #[strum(serialize = "\x0f")] + AsciiShiftIn = 15, + /// ASCII character 0x10. + #[strum(serialize = "\x10")] + AsciiDataLinkEscape = 16, + /// ASCII character 0x11. + #[strum(serialize = "\x11")] + AsciiDeviceControl1 = 17, + /// ASCII character 0x12. + #[strum(serialize = "\x12")] + AsciiDeviceControl2 = 18, + /// ASCII character 0x13. + #[strum(serialize = "\x13")] + AsciiDeviceControl3 = 19, + /// ASCII character 0x14. + #[strum(serialize = "\x14")] + AsciiDeviceControl4 = 20, + /// ASCII character 0x15. + #[strum(serialize = "\x15")] + AsciiNegativeAcknowledge = 21, + /// ASCII character 0x16. + #[strum(serialize = "\x16")] + AsciiSynchronousIdle = 22, + /// ASCII character 0x17. + #[strum(serialize = "\x17")] + AsciiEndOfTransmissionBlock = 23, + /// ASCII character 0x18. + #[strum(serialize = "\x18")] + AsciiCancel = 24, + /// ASCII character 0x19. + #[strum(serialize = "\x19")] + AsciiEndOfMedium = 25, + /// ASCII character 0x1a. + #[strum(serialize = "\x1a")] + AsciiSubstitute = 26, + /// ASCII character 0x1b. + #[strum(serialize = "\x1b")] + AsciiEscape = 27, + /// ASCII character 0x1c. + #[strum(serialize = "\x1c")] + AsciiFileSeparator = 28, + /// ASCII character 0x1d. + #[strum(serialize = "\x1d")] + AsciiGroupSeparator = 29, + /// ASCII character 0x1e. + #[strum(serialize = "\x1e")] + AsciiRecordSeparator = 30, + /// ASCII character 0x1f. + #[strum(serialize = "\x1f")] + AsciiUnitSeparator = 31, + /// ASCII character 0x20. + #[strum(serialize = "\x20")] + AsciiSpace = 32, + /// ASCII character 0x21. + #[strum(serialize = "\x21")] + AsciiExclamationMark = 33, + /// ASCII character 0x22. + #[strum(serialize = "\x22")] + AsciiDoubleQuote = 34, + /// ASCII character 0x23. + #[strum(serialize = "\x23")] + AsciiHash = 35, + /// ASCII character 0x24. + #[strum(serialize = "\x24")] + AsciiDollar = 36, + /// ASCII character 0x25. + #[strum(serialize = "\x25")] + AsciiPercent = 37, + /// ASCII character 0x26. + #[strum(serialize = "\x26")] + AsciiAmpersand = 38, + /// ASCII character 0x27. + #[strum(serialize = "\x27")] + AsciiSingleQuote = 39, + /// ASCII character 0x28. + #[strum(serialize = "\x28")] + AsciiLeftParen = 40, + /// ASCII character 0x29. + #[strum(serialize = "\x29")] + AsciiRightParen = 41, + /// ASCII character 0x2a. + #[strum(serialize = "\x2a")] + AsciiAsterisk = 42, + /// ASCII character 0x2b. + #[strum(serialize = "\x2b")] + AsciiPlus = 43, + /// ASCII character 0x2c. + #[strum(serialize = "\x2c")] + AsciiComma = 44, + /// ASCII character 0x2d. + #[strum(serialize = "\x2d")] + AsciiHyphen = 45, + /// ASCII character 0x2e. + #[strum(serialize = "\x2e")] + AsciiDot = 46, + /// ASCII character 0x2f. + #[strum(serialize = "\x2f")] + AsciiSlash = 47, + /// ASCII character 0x30. + #[strum(serialize = "\x30")] + AsciiDigit0 = 48, + /// ASCII character 0x31. + #[strum(serialize = "\x31")] + AsciiDigit1 = 49, + /// ASCII character 0x32. + #[strum(serialize = "\x32")] + AsciiDigit2 = 50, + /// ASCII character 0x33. + #[strum(serialize = "\x33")] + AsciiDigit3 = 51, + /// ASCII character 0x34. + #[strum(serialize = "\x34")] + AsciiDigit4 = 52, + /// ASCII character 0x35. + #[strum(serialize = "\x35")] + AsciiDigit5 = 53, + /// ASCII character 0x36. + #[strum(serialize = "\x36")] + AsciiDigit6 = 54, + /// ASCII character 0x37. + #[strum(serialize = "\x37")] + AsciiDigit7 = 55, + /// ASCII character 0x38. + #[strum(serialize = "\x38")] + AsciiDigit8 = 56, + /// ASCII character 0x39. + #[strum(serialize = "\x39")] + AsciiDigit9 = 57, + /// ASCII character 0x3a. + #[strum(serialize = "\x3a")] + AsciiColon = 58, + /// ASCII character 0x3b. + #[strum(serialize = "\x3b")] + AsciiSemicolon = 59, + /// ASCII character 0x3c. + #[strum(serialize = "\x3c")] + AsciiLessThan = 60, + /// ASCII character 0x3d. + #[strum(serialize = "\x3d")] + AsciiEquals = 61, + /// ASCII character 0x3e. + #[strum(serialize = "\x3e")] + AsciiGreaterThan = 62, + /// ASCII character 0x3f. + #[strum(serialize = "\x3f")] + AsciiQuestionMark = 63, + /// ASCII character 0x40. + #[strum(serialize = "\x40")] + AsciiAt = 64, + /// ASCII character 0x41. + #[strum(serialize = "\x41")] + AsciiA = 65, + /// ASCII character 0x42. + #[strum(serialize = "\x42")] + AsciiB = 66, + /// ASCII character 0x43. + #[strum(serialize = "\x43")] + AsciiC = 67, + /// ASCII character 0x44. + #[strum(serialize = "\x44")] + AsciiD = 68, + /// ASCII character 0x45. + #[strum(serialize = "\x45")] + AsciiE = 69, + /// ASCII character 0x46. + #[strum(serialize = "\x46")] + AsciiF = 70, + /// ASCII character 0x47. + #[strum(serialize = "\x47")] + AsciiG = 71, + /// ASCII character 0x48. + #[strum(serialize = "\x48")] + AsciiH = 72, + /// ASCII character 0x49. + #[strum(serialize = "\x49")] + AsciiI = 73, + /// ASCII character 0x4a. + #[strum(serialize = "\x4a")] + AsciiJ = 74, + /// ASCII character 0x4b. + #[strum(serialize = "\x4b")] + AsciiK = 75, + /// ASCII character 0x4c. + #[strum(serialize = "\x4c")] + AsciiL = 76, + /// ASCII character 0x4d. + #[strum(serialize = "\x4d")] + AsciiM = 77, + /// ASCII character 0x4e. + #[strum(serialize = "\x4e")] + AsciiN = 78, + /// ASCII character 0x4f. + #[strum(serialize = "\x4f")] + AsciiO = 79, + /// ASCII character 0x50. + #[strum(serialize = "\x50")] + AsciiP = 80, + /// ASCII character 0x51. + #[strum(serialize = "\x51")] + AsciiQ = 81, + /// ASCII character 0x52. + #[strum(serialize = "\x52")] + AsciiR = 82, + /// ASCII character 0x53. + #[strum(serialize = "\x53")] + AsciiS = 83, + /// ASCII character 0x54. + #[strum(serialize = "\x54")] + AsciiT = 84, + /// ASCII character 0x55. + #[strum(serialize = "\x55")] + AsciiU = 85, + /// ASCII character 0x56. + #[strum(serialize = "\x56")] + AsciiV = 86, + /// ASCII character 0x57. + #[strum(serialize = "\x57")] + AsciiW = 87, + /// ASCII character 0x58. + #[strum(serialize = "\x58")] + AsciiX = 88, + /// ASCII character 0x59. + #[strum(serialize = "\x59")] + AsciiY = 89, + /// ASCII character 0x5a. + #[strum(serialize = "\x5a")] + AsciiZ = 90, + /// ASCII character 0x5b. + #[strum(serialize = "\x5b")] + AsciiLeftBracket = 91, + /// ASCII character 0x5c. + #[strum(serialize = "\x5c")] + AsciiBackslash = 92, + /// ASCII character 0x5d. + #[strum(serialize = "\x5d")] + AsciiRightBracket = 93, + /// ASCII character 0x5e. + #[strum(serialize = "\x5e")] + AsciiCaret = 94, + /// ASCII character 0x5f. + #[strum(serialize = "\x5f")] + AsciiUnderscore = 95, + /// ASCII character 0x60. + #[strum(serialize = "\x60")] + AsciiBacktick = 96, + /// ASCII character 0x61. + #[strum(serialize = "\x61")] + AsciiLowerA = 97, + /// ASCII character 0x62. + #[strum(serialize = "\x62")] + AsciiLowerB = 98, + /// ASCII character 0x63. + #[strum(serialize = "\x63")] + AsciiLowerC = 99, + /// ASCII character 0x64. + #[strum(serialize = "\x64")] + AsciiLowerD = 100, + /// ASCII character 0x65. + #[strum(serialize = "\x65")] + AsciiLowerE = 101, + /// ASCII character 0x66. + #[strum(serialize = "\x66")] + AsciiLowerF = 102, + /// ASCII character 0x67. + #[strum(serialize = "\x67")] + AsciiLowerG = 103, + /// ASCII character 0x68. + #[strum(serialize = "\x68")] + AsciiLowerH = 104, + /// ASCII character 0x69. + #[strum(serialize = "\x69")] + AsciiLowerI = 105, + /// ASCII character 0x6a. + #[strum(serialize = "\x6a")] + AsciiLowerJ = 106, + /// ASCII character 0x6b. + #[strum(serialize = "\x6b")] + AsciiLowerK = 107, + /// ASCII character 0x6c. + #[strum(serialize = "\x6c")] + AsciiLowerL = 108, + /// ASCII character 0x6d. + #[strum(serialize = "\x6d")] + AsciiLowerM = 109, + /// ASCII character 0x6e. + #[strum(serialize = "\x6e")] + AsciiLowerN = 110, + /// ASCII character 0x6f. + #[strum(serialize = "\x6f")] + AsciiLowerO = 111, + /// ASCII character 0x70. + #[strum(serialize = "\x70")] + AsciiLowerP = 112, + /// ASCII character 0x71. + #[strum(serialize = "\x71")] + AsciiLowerQ = 113, + /// ASCII character 0x72. + #[strum(serialize = "\x72")] + AsciiLowerR = 114, + /// ASCII character 0x73. + #[strum(serialize = "\x73")] + AsciiLowerS = 115, + /// ASCII character 0x74. + #[strum(serialize = "\x74")] + AsciiLowerT = 116, + /// ASCII character 0x75. + #[strum(serialize = "\x75")] + AsciiLowerU = 117, + /// ASCII character 0x76. + #[strum(serialize = "\x76")] + AsciiLowerV = 118, + /// ASCII character 0x77. + #[strum(serialize = "\x77")] + AsciiLowerW = 119, + /// ASCII character 0x78. + #[strum(serialize = "\x78")] + AsciiLowerX = 120, + /// ASCII character 0x79. + #[strum(serialize = "\x79")] + AsciiLowerY = 121, + /// ASCII character 0x7a. + #[strum(serialize = "\x7a")] + AsciiLowerZ = 122, + /// ASCII character 0x7b. + #[strum(serialize = "\x7b")] + AsciiLeftBrace = 123, + /// ASCII character 0x7c. + #[strum(serialize = "\x7c")] + AsciiPipe = 124, + /// ASCII character 0x7d. + #[strum(serialize = "\x7d")] + AsciiRightBrace = 125, + /// ASCII character 0x7e. + #[strum(serialize = "\x7e")] + AsciiTilde = 126, + /// ASCII character 0x7f. + #[strum(serialize = "\x7f")] + AsciiDelete = 127, + /// The empty string, addressed by [`StringId::EMPTY`] immediately after ASCII. + #[strum(serialize = "")] + EmptyString = 128, + /// `binascii.a2b_base64()` function. + #[strum(serialize = "a2b_base64")] + A2bBase64, + /// `binascii.a2b_hex()` function, an alias of `unhexlify`. + #[strum(serialize = "a2b_hex")] + A2bHex, + /// `binascii.a2b_qp()` function. + #[strum(serialize = "a2b_qp")] + A2bQp, + /// `binascii.a2b_uu()` function. + #[strum(serialize = "a2b_uu")] + A2bUu, + /// `base64.a85decode()` function. + #[strum(serialize = "a85decode")] + A85Decode, + /// `base64.a85encode()` function. + #[strum(serialize = "a85encode")] + A85Encode, + /// `sys.abiflags` attribute. + Abiflags, + /// Kwarg name `abs_tol` — `math.isclose(abs_tol=...)`. + AbsTol, + /// `Path.absolute()` method — yields a host call. + Absolute, + /// `os.path.abspath()` function. + Abspath, + /// `itertools.accumulate()` function. + Accumulate, + /// `math.acos()` function. + Acos, + /// `math.acosh()` function. + Acosh, + /// `set.add()` method. + Add, + /// `adobe` parameter of `base64.a85encode()` / `a85decode()`. + #[strum(serialize = "adobe")] + Adobe, + /// `hashlib.algorithms_available`, equal to `algorithms_guaranteed`. + AlgorithmsAvailable, + /// `hashlib.algorithms_guaranteed`. + AlgorithmsGuaranteed, + /// `json.dumps(allow_nan=...)` keyword. + #[strum(serialize = "allow_nan")] + AllowNan, + /// `alpha` parameter of `random.gammavariate()` and the other shape variates. + Alpha, + /// `altchars` parameter of `base64.b64encode()` / `b64decode()`. + #[strum(serialize = "altchars")] + Altchars, + /// `os.altsep` constant name. + Altsep, + /// `time.altzone` constant. + Altzone, + /// `typing.Annotated` marker. + #[strum(serialize = "Annotated")] + Annotated, + /// `typing.Any` marker. + #[strum(serialize = "Any")] + Any, + /// `sys.api_version` attribute. + ApiVersion, + /// `list.append()` method. + Append, + /// `Path.append_bytes()` method — yields a host call. + AppendBytes, + /// `Path.append_text()` method — yields a host call. + AppendText, + /// `deque.appendleft()` method. + Appendleft, + /// `BaseException.args` attribute. + Args, + /// `sys.argv` attribute. + Argv, + /// `Path.as_posix()` method, answered without host I/O. + AsPosix, + /// `re.ASCII` flag + #[strum(serialize = "ASCII")] + AsciiFlag, + /// `time.asctime()` function. + Asctime, + /// `math.asin()` function. + Asin, + /// `math.asinh()` function. + Asinh, + /// `datetime.astimezone()` method. + Astimezone, + /// Module name for `import asyncio`. + Asyncio, + /// `math.atan()` function. + Atan, + /// `math.atan2()` function. + Atan2, + /// `math.atanh()` function. + Atanh, + /// `base64.b16decode()` function. + #[strum(serialize = "b16decode")] + B16Decode, + /// `base64.b16encode()` function. + #[strum(serialize = "b16encode")] + B16Encode, + /// `binascii.b2a_base64()` function. + #[strum(serialize = "b2a_base64")] + B2aBase64, + /// `binascii.b2a_hex()` function, an alias of `hexlify`. + #[strum(serialize = "b2a_hex")] + B2aHex, + /// `binascii.b2a_qp()` function. + #[strum(serialize = "b2a_qp")] + B2aQp, + /// `binascii.b2a_uu()` function. + #[strum(serialize = "b2a_uu")] + B2aUu, + /// `base64.b32decode()` function. + #[strum(serialize = "b32decode")] + B32Decode, + /// `base64.b32encode()` function. + #[strum(serialize = "b32encode")] + B32Encode, + /// `base64.b32hexdecode()` function. + #[strum(serialize = "b32hexdecode")] + B32HexDecode, + /// `base64.b32hexencode()` function. + #[strum(serialize = "b32hexencode")] + B32HexEncode, + /// `base64.b64decode()` function. + #[strum(serialize = "b64decode")] + B64Decode, + /// `base64.b64encode()` function. + #[strum(serialize = "b64encode")] + B64Encode, + /// `base64.b85decode()` function. + #[strum(serialize = "b85decode")] + B85Decode, + /// `base64.b85encode()` function. + #[strum(serialize = "b85encode")] + B85Encode, + /// `backtick` parameter of `binascii.b2a_uu()`. + #[strum(serialize = "backtick")] + Backtick, + /// Kwarg name `base` — `pow(base=...)`. + Base, + /// Module name for `import base64`. + #[strum(serialize = "base64")] + Base64, + /// `sys.base_exec_prefix` attribute. + BaseExecPrefix, + /// `sys.base_prefix` attribute. + BasePrefix, + /// `os.path.basename()` function. + Basename, + /// `decimal.BasicContext` template context. + #[strum(serialize = "BasicContext")] + BasicContext, + /// `itertools.batched()` function. + Batched, + /// `beta` parameter of `random.gammavariate()` and the other shape variates. + Beta, + /// `random.betavariate()` function. + Betavariate, + /// Module name for `import binascii`. + #[strum(serialize = "binascii")] + Binascii, + /// `random.binomialvariate()` function. + Binomialvariate, + /// `bisect` in the bisect module. + Bisect, + /// `bisect_left` in the bisect module. + BisectLeft, + /// `bisect_right` in the bisect module. + BisectRight, + /// `hashlib.blake2b` type and hash name. + Blake2b, + /// `hashlib.blake2s` type and hash name. + Blake2s, + /// `block_size` attribute of a hash object. + BlockSize, + /// Kwarg name `buffering` — `open(buffering=...)`. + Buffering, + /// `sys.builtin_module_names` attribute. + BuiltinModuleNames, + /// `sys.byteorder` attribute. + Byteorder, + /// `bytes_per_sep` parameter of `binascii.hexlify()`. + #[strum(serialize = "bytes_per_sep")] + BytesPerSep, + /// `sys.flags.bytes_warning` field. + BytesWarning, + /// `functools.cache()` function and private helper parameter. + Cache, + /// Cached callable's `cache_clear()` method. + CacheClear, + /// Cached callable's `cache_info()` method. + CacheInfo, + /// The named tuple returned by `cache_info()`. + #[strum(serialize = "CacheInfo")] + CacheInfoName, + /// Cached callable's `cache_parameters()` method. + CacheParameters, + /// `typing.Callable` marker. + #[strum(serialize = "Callable")] + Callable, + /// `capitalize()` method, shared by `str` and `bytes`. + Capitalize, + /// Kwarg name `capitals` — `decimal.Context()`. + Capitals, + /// Kwarg name `case_sensitive` — `Path.glob(case_sensitive=...)`. + CaseSensitive, + /// `str.casefold()` method. + Casefold, + /// `unicodedata.category()` function. + Category, + /// `math.cbrt()` function. + Cbrt, + /// `math.ceil()` function. + Ceil, + /// `center()` method, shared by `str` and `bytes`. + Center, + /// `itertools.chain()` function. + Chain, + /// `os.chdir()` function. + Chdir, + /// `random.choice()` function. + Choice, + /// `random.choices()` function. + Choices, + /// Kwarg name `clamp` — `decimal.Context()`. + Clamp, + /// `decimal.Clamped` signal. + #[strum(serialize = "Clamped")] + Clamped, + /// `__class_getitem__`, the classmethod behind `list[int]`. + #[strum(serialize = "__class_getitem__")] + ClassGetitem, + /// `typing.ClassVar` marker. + #[strum(serialize = "ClassVar")] + ClassVar, + /// `clear()` method, shared by `list`, `dict` and `set`. + Clear, + /// `file.close()` method. + Close, + /// `file.closed` attribute. + Closed, + /// Kwarg name `closefd` — `open(closefd=...)`. + Closefd, + /// `closure` parameter of exec. + Closure, + /// The class parameter of the decorator `@dataclass(...)` returns, which + /// CPython spells `def wrap(cls)` and so accepts by keyword. + Cls, + /// `gc.collect()` function. + Collect, + /// Module name for `import collections`. + Collections, + /// `math.comb()` function. + Comb, + /// `itertools.combinations()` function. + Combinations, + /// `itertools.combinations_with_replacement()` function. + #[strum(serialize = "combinations_with_replacement")] + CombinationsWithReplacement, + /// `datetime.combine()` class method. + Combine, + /// `unicodedata.combining()` function. + Combining, + /// `os.path.commonpath()` function. + Commonpath, + /// `os.path.commonprefix()` function. + Commonprefix, + /// `field(compare=...)`. + Compare, + /// `re.compile()` function + Compile, + /// `itertools.compress()` function. + Compress, + /// `complex.conjugate()` method. + Conjugate, + /// Kwarg name `context` — the `decimal` methods. + Context, + /// `decimal.Context` class. + #[strum(serialize = "Context")] + ContextType, + /// `decimal.ConversionSyntax` condition. + #[strum(serialize = "ConversionSyntax")] + ConversionSyntax, + /// `copy()` method, shared by `list`, `dict` and `set`; also the `copy` module and `copy.copy()`. + Copy, + /// `sys.copyright` attribute. + Copyright, + /// `math.copysign()` function. + Copysign, + /// `math.cos()` function. + Cos, + /// `math.cosh()` function. + Cosh, + /// `count()` method, shared by `str`, `bytes`, `list` and `tuple`; also `itertools.count()`. + Count, + /// The `collections.Counter` type/factory. + #[strum(serialize = "Counter")] + Counter, + /// `counts` parameter of `random.sample()`. + Counts, + /// `crc` parameter of `binascii.crc32()`. + #[strum(serialize = "crc")] + Crc, + /// `binascii.crc32()` function. + #[strum(serialize = "crc32")] + Crc32, + /// `binascii.crc_hqx()` function. + #[strum(serialize = "crc_hqx")] + CrcHqx, + /// Module name for `import csv`. + Csv, + /// `time.ctime()` function. + Ctime, + /// Kwarg name `ctx` — `decimal.localcontext()`. + Ctx, + /// `cum_weights` parameter of `random.choices()`. + CumWeights, + /// `os.curdir` constant name. + Curdir, + /// `CacheInfo.currsize` field. + Currsize, + /// `Path.cwd()` classmethod: answered from the VM's working directory, no host call. + Cwd, + /// `itertools.cycle()` function. + Cycle, + /// `data` keyword argument of `itertools.compress()`. + Data, + /// `time.strptime()` parameter name `data_string`. + DataString, + /// `dataclasses.dataclass` decorator. + Dataclass, + /// The `__dataclass_fields__` class attribute `@dataclass` writes: the + /// name -> `Field` mapping the generated dunders were built from. + #[strum(serialize = "__dataclass_fields__")] + DataclassFields, + /// The `__dataclass_params__` class attribute `@dataclass` writes: the + /// options the class was decorated with. + #[strum(serialize = "__dataclass_params__")] + DataclassParams, + /// Module name for `import dataclasses`. + Dataclasses, + /// The `datetime.date` type. + Date, + /// Module name for `import datetime`, and the `datetime.datetime` type. + Datetime, + /// `date` / `datetime` `day` attribute and constructor kwarg. + Day, + /// `time.daylight` constant. + Daylight, + /// `timedelta.days` attribute and constructor kwarg. + Days, + /// `sys.flags.debug` field. + Debug, + /// `decimal.DecimalException` exception class. + #[strum(serialize = "DecimalException")] + DecimalException, + /// Module name for `import decimal`. + #[strum(serialize = "decimal")] + DecimalMod, + /// `decimal.DecimalTuple`, the named tuple `Decimal.as_tuple()` returns. + #[strum(serialize = "DecimalTuple")] + DecimalTuple, + /// `decimal.Decimal` class. + #[strum(serialize = "Decimal")] + DecimalType, + /// `bytes.decode()` method. + Decode, + /// `base64.decodebytes()` function. + #[strum(serialize = "decodebytes")] + Decodebytes, + /// `copy.deepcopy()`. The module name and `copy.copy()` reuse [`Self::Copy`]. + Deepcopy, + /// Kwarg name `default` — `os.getenv(default=...)`. + Default, + /// `decimal.DefaultContext` template context. + #[strum(serialize = "DefaultContext")] + DefaultContext, + /// `defaultdict.default_factory` attribute. + #[strum(serialize = "default_factory")] + DefaultFactory, + /// The `collections.defaultdict` factory function. + Defaultdict, + /// `namedtuple(..., defaults=...)` keyword argument. + Defaults, + /// `os.defpath` / `os.path.defpath` constant name. + Defpath, + /// Value of `os.defpath`. + #[strum(serialize = "/bin:/usr/bin")] + DefpathString, + /// `math.degrees()` function. + Degrees, + /// `delay` parameter of `asyncio.sleep()`. + Delay, + /// `delimiter` dialect attribute and `csv` format parameter. + Delimiter, + /// `depth` parameter of `hashlib.blake2b()`. + Depth, + /// The `collections.deque` type. + Deque, + /// `sys.flags.dev_mode` field. + DevMode, + /// Value of `os.devnull`. + #[strum(serialize = "/dev/null")] + DevNullString, + /// `os.devnull` constant name. + Devnull, + /// `dialect` parameter and attribute of the `csv` readers and writers. + Dialect, + /// `csv.Dialect`, the `_csv.Dialect` class. + #[strum(serialize = "Dialect")] + DialectClass, + /// `csv.DictReader` class. + #[strum(serialize = "DictReader")] + DictReader, + /// `typing.Dict` marker. + #[strum(serialize = "Dict")] + DictType, + /// `csv.DictWriter` class. + #[strum(serialize = "DictWriter")] + DictWriter, + /// `set.difference()` method. + Difference, + /// `sys.float_info.dig` field. + Dig, + /// `digest()` method of a hash object. + Digest, + /// `digest_size` attribute of a hash object, and the `blake2b()` parameter. + DigestSize, + /// `DecimalTuple.digits` field. + Digits, + /// Kwarg name `dir_fd` — `os.stat(dir_fd=...)`, `os.mkdir(dir_fd=...)`, etc. + DirFd, + /// `os.path.dirname()` function. + Dirname, + /// `gc.disable()` function. + Disable, + /// `set.discard()` method. + Discard, + /// `math.dist()` function. + Dist, + /// `decimal.DivisionByZero` signal. + #[strum(serialize = "DivisionByZero")] + DivisionByZero, + /// `decimal.DivisionImpossible` condition. + #[strum(serialize = "DivisionImpossible")] + DivisionImpossible, + /// `decimal.DivisionUndefined` condition. + #[strum(serialize = "DivisionUndefined")] + DivisionUndefined, + /// `dklen` parameter of `hashlib.pbkdf2_hmac()`. + Dklen, + /// `field(doc=...)`, CPython's per-field docstring. + Doc, + /// `sys.dont_write_bytecode` attribute. + DontWriteBytecode, + /// `re.DOTALL` flag + #[strum(serialize = "DOTALL")] + DotallFlag, + /// `doublequote` dialect attribute and `csv` format parameter. + Doublequote, + /// `itertools.dropwhile()` function. + Dropwhile, + /// Kwarg name `dst` — `os.rename(dst=...)`, `os.replace(dst=...)`. + Dst, + /// Kwarg name `dst_dir_fd` — `os.rename(dst_dir_fd=...)`. + DstDirFd, + /// `json.dump()` function. + Dump, + /// `json.dumps()` function. + Dumps, + /// `__args__` of a `types.GenericAlias`. + #[strum(serialize = "__args__")] + DunderArgs, + /// `__delattr__` — the frozen-dataclass hook `@dataclass` generates. + #[strum(serialize = "__delattr__")] + DunderDelattr, + /// `__doc__` — synthesized into the namespace of classes created by the + /// 3-arg `type()` builtin when the caller's dict omits it. + #[strum(serialize = "__doc__")] + DunderDoc, + /// `__eq__` — written into a class namespace by `@dataclass`. + #[strum(serialize = "__eq__")] + DunderEq, + /// `__getnewargs__` — the copy/pickle hook on named tuples. + #[strum(serialize = "__getnewargs__")] + DunderGetnewargs, + /// `__hash__` — written into a class namespace by `@dataclass`. + #[strum(serialize = "__hash__")] + DunderHash, + /// `__init__` — written into a class namespace by `@dataclass`. + #[strum(serialize = "__init__")] + DunderInit, + /// `decimal.__libmpdec_version__` attribute. + #[strum(serialize = "__libmpdec_version__")] + DunderLibmpdecVersion, + /// `__main__`, the `__name__` of the module being run. + #[strum(serialize = "__main__")] + DunderMain, + /// `defaultdict.__missing__` method. + #[strum(serialize = "__missing__")] + DunderMissing, + /// `__module__` — the defining module name, exposed on namedtuple classes. + #[strum(serialize = "__module__")] + DunderModule, + /// `__name__` attribute of a type. + #[strum(serialize = "__name__")] + DunderName, + /// `__origin__` of a `types.GenericAlias`. + #[strum(serialize = "__origin__")] + DunderOrigin, + /// `__parameters__` of a `types.GenericAlias`. + #[strum(serialize = "__parameters__")] + DunderParameters, + /// `__qualname__` — the qualified class name, exposed on namedtuple classes. + #[strum(serialize = "__qualname__")] + DunderQualname, + /// `__repr__` — written into a class namespace by `@dataclass`. + #[strum(serialize = "__repr__")] + DunderRepr, + /// `__setattr__` — the frozen-dataclass hook `@dataclass` generates. + #[strum(serialize = "__setattr__")] + DunderSetattr, + /// `decimal.__version__` attribute. + #[strum(serialize = "__version__")] + DunderVersion, + /// The uncached callable. + #[strum(serialize = "__wrapped__")] + DunderWrapped, + /// `Counter.elements()` method. + Elements, + /// `repr()`/`str()` text of `Ellipsis`, interned so rendering allocates nothing. + #[strum(serialize = "Ellipsis")] + EllipsisRepr, + /// Kwarg name `Emax` — `decimal.Context()`. + #[strum(serialize = "Emax")] + Emax, + /// Kwarg name `Emin` — `decimal.Context()`. + #[strum(serialize = "Emin")] + Emin, + /// `gc.enable()` function. + Enable, + /// `str.encode()` method. + Encode, + /// `base64.encodebytes()` function. + #[strum(serialize = "encodebytes")] + Encodebytes, + /// `file.encoding` attribute and the `open(encoding=...)` kwarg. + Encoding, + /// `match.end()` method + End, + /// `endswith()` method, shared by `str` and `bytes`. + Endswith, + /// `json.dumps(ensure_ascii=...)` keyword. + #[strum(serialize = "ensure_ascii")] + EnsureAscii, + /// `__enter__`, the context-manager entry method. + #[strum(serialize = "__enter__")] + Enter, + /// `os.environ` attribute. + Environ, + /// `sys.float_info.epsilon` field. + Epsilon, + /// `@dataclass(eq=...)`. + Eq, + /// `math.erf()` function. + Erf, + /// `math.erfc()` function. + Erfc, + /// `re.error` exception alias (same as `re.PatternError`) + #[strum(serialize = "error")] + Error, + /// `binascii.Error` exception class — distinct from [`Self::Error`], which + /// is the lowercase `re.error` alias. + #[strum(serialize = "Error")] + ErrorClass, + /// Kwarg name `errors` — `open(errors=...)`. + Errors, + /// `re.escape()` function + Escape, + /// `escapechar` dialect attribute and `csv` format parameter. + Escapechar, + /// `csv.excel` dialect. + Excel, + /// `csv.excel_tab` dialect. + ExcelTab, + /// `sys.exec_prefix` attribute. + ExecPrefix, + /// `sys.executable` attribute. + Executable, + /// Kwarg name `exist_ok` — `Path.mkdir(exist_ok=...)`. + ExistOk, + /// `Path.exists()` method — yields a host call. + Exists, + /// `__exit__`, the context-manager exit method. + #[strum(serialize = "__exit__")] + Exit, + /// `math.exp()` function. + Exp, + /// `math.exp2()` function. + Exp2, + /// `str.expandtabs()` method. + Expandtabs, + /// `os.path.expanduser()` function. + Expanduser, + /// `os.path.expandvars()` function. + Expandvars, + /// `math.expm1()` function. + Expm1, + /// `DecimalTuple.exponent` field. + Exponent, + /// `random.expovariate()` function. + Expovariate, + /// `extend()` method, shared by `list` and `deque`. + Extend, + /// `decimal.ExtendedContext` template context. + #[strum(serialize = "ExtendedContext")] + ExtendedContext, + /// `deque.extendleft()` method. + Extendleft, + /// `extrasaction` parameter and attribute of `csv.DictWriter`. + Extrasaction, + /// `os.extsep` constant name. + Extsep, + /// Kwarg name `f1` — `os.path.samefile(f1=...)`. + F1, + /// Kwarg name `f2` — `os.path.samefile(f2=...)`. + F2, + /// `math.fabs()` function. + Fabs, + /// `math.factorial()` function. + Factorial, + /// `repr()`/`str()` text of `False`, interned so rendering allocates nothing. + #[strum(serialize = "False")] + FalseRepr, + /// `fanout` parameter of `hashlib.blake2b()`. + Fanout, + /// `dataclasses.field()` function, and the `Field` type name. + Field, + /// `namedtuple(field_names=...)` keyword argument. + #[strum(serialize = "field_names")] + FieldNames, + /// `csv.field_size_limit()` function. + FieldSizeLimit, + /// `fieldnames` parameter and attribute of `csv.DictReader` / `csv.DictWriter`. + Fieldnames, + /// Kwarg name `file` — `open(file=...)`. + File, + /// Kwarg name `filename` — `os.path.getsize(filename=...)`, `os.path.realpath(filename=...)`. + Filename, + /// `zip_longest(fillvalue=...)` keyword. + Fillvalue, + /// `itertools.filterfalse()` function. + Filterfalse, + /// Value of `sys.version_info.releaselevel`. + Final, + /// `typing.Final` marker. + #[strum(serialize = "Final")] + FinalType, + /// `find()` method, shared by `str` and `bytes`. + Find, + /// `re.findall()` / `pattern.findall()` method + Findall, + /// `re.finditer()` / `pattern.finditer()` method + Finditer, + /// `pattern.flags` + Flags, + /// `sys.float_info` attribute. + FloatInfo, + /// `decimal.FloatOperation` signal. + #[strum(serialize = "FloatOperation")] + FloatOperation, + /// `sys.float_repr_style` attribute. + FloatReprStyle, + /// `math.floor()` function. + Floor, + /// `file.flush()` method. + Flush, + /// `math.fma()` function. + Fma, + /// `math.fmod()` function. + Fmod, + /// `datetime` / `time` `fold` attribute and constructor kwarg. + Fold, + /// `foldspaces` parameter of `base64.a85encode()` / `a85decode()`. + #[strum(serialize = "foldspaces")] + Foldspaces, + /// Kwarg name `follow_symlinks` — `os.stat(follow_symlinks=...)`. + FollowSymlinks, + /// Kwarg name `followlinks` — `os.walk(followlinks=...)`. + Followlinks, + /// Kwarg name `format` — `date.strftime(format=...)`, `datetime.strftime(format=...)`. + Format, + /// `fp` parameter of `json.load()` / `json.dump()`. + Fp, + /// `math.frexp()` function. + Frexp, + /// `chain.from_iterable` — the one attribute an `itertools` type carries. + #[strum(serialize = "from_iterable")] + FromIterable, + /// `complex.from_number()` classmethod. + FromNumber, + /// `bytes.fromhex()` classmethod. + Fromhex, + /// `date.fromisoformat()` / `datetime.fromisoformat()` classmethod. + Fromisoformat, + /// `dict.fromkeys()` classmethod. + Fromkeys, + /// `@dataclass(frozen=...)`. + Frozen, + /// `dataclasses.FrozenInstanceError` exception. + #[strum(serialize = "FrozenInstanceError")] + FrozenInstanceError, + /// `typing.FrozenSet` marker. + #[strum(serialize = "FrozenSet")] + FrozenSet, + /// `Path.__fspath__()` method, answered without host I/O. + #[strum(serialize = "__fspath__")] + Fspath, + /// `math.fsum()` function. + Fsum, + /// `re.fullmatch()` / `pattern.fullmatch()` method + Fullmatch, + /// `partial.func` attribute, and the `accumulate(func=...)` keyword. + Func, + /// Module name for `import functools`. + Functools, + /// `math.gamma()` function. + Gamma, + /// `random.gammavariate()` function. + Gammavariate, + /// `asyncio.gather()` function. + Gather, + /// `random.gauss()` function. + Gauss, + /// Module name for `import gc`. + Gc, + /// `math.gcd()` function. + Gcd, + /// `typing.Generator` marker. + #[strum(serialize = "Generator")] + Generator, + /// `typing.Generic` marker. + #[strum(serialize = "Generic")] + Generic, + /// `dict.get()` method. + Get, + /// `csv.get_dialect()` function. + GetDialect, + /// `os.path.getatime()` function. + Getatime, + /// `decimal.getcontext()` function. + Getcontext, + /// `os.path.getctime()` function. + Getctime, + /// `os.getcwd()` function. + Getcwd, + /// `os.getcwdb()` function. + Getcwdb, + /// `os.getenv()` function. + Getenv, + /// `os.path.getmtime()` function. + Getmtime, + /// `random.getrandbits()` function. + Getrandbits, + /// `os.path.getsize()` function. + Getsize, + /// `random.getstate()` function. + Getstate, + /// `Path.glob()` method — yields a host scan. + Glob, + /// `globals` parameter of eval/exec. + Globals, + /// `time.gmtime()` function. + Gmtime, + /// `match.group()` method + Group, + /// `itertools.groupby()` function. + Groupby, + /// `match.groupdict()` method + Groupdict, + /// `itertools._grouper`, the sub-iterator `groupby` hands out. + #[strum(serialize = "_grouper")] + Grouper, + /// `match.groups()` method + Groups, + /// `field(hash=...)`. + Hash, + /// `hash_name` parameter of `hashlib.pbkdf2_hmac()`. + HashName, + /// `sys.flags.hash_randomization` field. + HashRandomization, + /// Module name for `import hashlib`. + Hashlib, + /// `decimal.HAVE_CONTEXTVAR` constant. + #[strum(serialize = "HAVE_CONTEXTVAR")] + HaveContextvar, + /// `decimal.HAVE_THREADS` constant. + #[strum(serialize = "HAVE_THREADS")] + HaveThreads, + /// `header` parameter of the `binascii` quoted-printable pair. + #[strum(serialize = "header")] + Header, + /// `bytes.hex()` method. + Hex, + /// `hexdigest()` method of a hash object. + Hexdigest, + /// `binascii.hexlify()` function. + #[strum(serialize = "hexlify")] + Hexlify, + /// `hexstr` parameter of `binascii.unhexlify()`. + #[strum(serialize = "hexstr")] + Hexstr, + /// `sys.hexversion` attribute. + Hexversion, + /// `hi` in the bisect module. + Hi, + /// `high` parameter of `random.triangular()`. + High, + /// `CacheInfo.hits` field. + Hits, + /// `datetime` / `time` `hour` attribute and constructor kwarg. + Hour, + /// `timedelta(hours=...)` constructor kwarg. + Hours, + /// `math.hypot()` function. + Hypot, + /// `decimal.IEEEContext()` function. + #[strum(serialize = "IEEEContext")] + IeeeContext, + /// `decimal.IEEE_CONTEXT_MAX_BITS` constant. + #[strum(serialize = "IEEE_CONTEXT_MAX_BITS")] + IeeeContextMaxBits, + /// `sys.flags.ignore_environment` field. + IgnoreEnvironment, + /// `re.IGNORECASE` flag + #[strum(serialize = "IGNORECASE")] + Ignorecase, + /// `ignorechars` parameter of `base64.a85decode()`. + #[strum(serialize = "ignorechars")] + Ignorechars, + /// `complex.imag` attribute. + Imag, + /// `binascii.Incomplete` exception class. + #[strum(serialize = "Incomplete")] + IncompleteClass, + /// `json.dumps(indent=...)` keyword. + Indent, + /// `index()` method, shared by `str`, `bytes`, `list`, `tuple` and `deque`. + Index, + /// `decimal.Inexact` signal. + #[strum(serialize = "Inexact")] + Inexact, + /// `@dataclass(init=...)`. + Init, + /// `initial` keyword argument of `functools.reduce()` and + /// `itertools.accumulate()`. + Initial, + /// `inner_size` parameter of `hashlib.blake2b()`. + InnerSize, + /// `list.insert()` method. + Insert, + /// `insort` in the bisect module. + Insort, + /// `insort_left` in the bisect module. + InsortLeft, + /// `insort_right` in the bisect module. + InsortRight, + /// `sys.flags.inspect` field. + Inspect, + /// `sys.flags.int_max_str_digits` field. + IntMaxStrDigits, + /// `sys.flags.interactive` field. + Interactive, + /// `set.intersection()` method. + Intersection, + /// `decimal.InvalidContext` condition. + #[strum(serialize = "InvalidContext")] + InvalidContext, + /// `decimal.InvalidOperation` signal. + #[strum(serialize = "InvalidOperation")] + InvalidOperation, + /// `Path.is_absolute()` method, answered without host I/O. + IsAbsolute, + /// `dataclasses.is_dataclass()` function. + IsDataclass, + /// `Path.is_dir()` method — yields a host call. + IsDir, + /// `Path.is_file()` method — yields a host call. + IsFile, + /// `DirEntry.is_junction()` method. + IsJunction, + /// `unicodedata.is_normalized()` function. + #[strum(serialize = "is_normalized")] + IsNormalized, + /// `Path.is_symlink()` method — yields a host call. + IsSymlink, + /// `os.path.isabs()` function. + Isabs, + /// `isalnum()` method, shared by `str` and `bytes`. + Isalnum, + /// `isalpha()` method, shared by `str` and `bytes`. + Isalpha, + /// `isascii()` method, shared by `str` and `bytes`. + Isascii, + /// `math.isclose()` function. + Isclose, + /// `str.isdecimal()` method. + Isdecimal, + /// `os.path.isdevdrive()` function. + Isdevdrive, + /// `isdigit()` method, shared by `str` and `bytes`. + Isdigit, + /// `os.path.isdir()` function. + Isdir, + /// `set.isdisjoint()` method. + Isdisjoint, + /// `os.path.isfile()` function. + Isfile, + /// `math.isfinite()` function. + Isfinite, + /// `str.isidentifier()` method. + Isidentifier, + /// `math.isinf()` function. + Isinf, + /// `os.path.isjunction()` function. + Isjunction, + /// `itertools.islice()` function. + Islice, + /// `os.path.islink()` function. + Islink, + /// `islower()` method, shared by `str` and `bytes`. + Islower, + /// `os.path.ismount()` function. + Ismount, + /// `math.isnan()` function. + Isnan, + /// `str.isnumeric()` method. + Isnumeric, + /// `date.isoformat()` / `datetime.isoformat()` method. + Isoformat, + /// `sys.flags.isolated` field. + Isolated, + /// `date.isoweekday()` / `datetime.isoweekday()` method. + Isoweekday, + /// `str.isprintable()` method. + Isprintable, + /// `math.isqrt()` function. + Isqrt, + /// `isspace()` method, shared by `str` and `bytes`. + Isspace, + /// `set.issubset()` method. + Issubset, + /// `set.issuperset()` method. + Issuperset, + /// `istext` parameter of `binascii.b2a_qp()`. + #[strum(serialize = "istext")] + Istext, + /// `istitle()` method, shared by `str` and `bytes`. + Istitle, + /// `isupper()` method, shared by `str` and `bytes`. + Isupper, + /// `dict.items()` method. + Items, + /// `typing.Iterable` marker. + #[strum(serialize = "Iterable")] + Iterable, + /// `deque(iterable=...)` — the constructor's first parameter, which CPython + /// also accepts by keyword. Distinct from [`Self::Iterable`], which is the + /// capitalized `typing.Iterable`. + #[strum(serialize = "iterable")] + IterableArg, + /// `iterations` parameter of `hashlib.pbkdf2_hmac()`. + Iterations, + /// `typing.Iterator` marker. + #[strum(serialize = "Iterator")] + IteratorType, + /// `Path.iterdir()` method — yields a host call. + Iterdir, + /// Module name for `import itertools`. + Itertools, + /// `join()` method, shared by `str` and `bytes`. + Join, + /// `Path.joinpath()` method, answered without host I/O. + Joinpath, + /// Module name for `import json`. + Json, + /// `json.JSONDecodeError` exception. + #[strum(serialize = "JSONDecodeError")] + JsonDecodeError, + /// `kappa` parameter of `random.vonmisesvariate()`. + Kappa, + /// Kwarg name `keepends` — `str.splitlines(keepends=...)`. + Keepends, + /// Kwarg name `key` — `sorted(key=...)`, `min(key=...)`, etc. + Key, + /// `dict.keys()` method. + Keys, + /// `partial.keywords` attribute. + Keywords, + /// `@dataclass(kw_only=...)`. + KwOnly, + /// `lambd` parameter of `random.expovariate()`. + Lambd, + /// `last_node` parameter of `hashlib.blake2b()`. + LastNode, + /// `math.lcm()` function. + Lcm, + /// `math.ldexp()` function. + Ldexp, + /// `leaf_size` parameter of `hashlib.blake2b()`. + LeafSize, + /// `length` parameter of a SHAKE `digest()`. + Length, + /// `os.path.lexists()` function. + Lexists, + /// `math.lgamma()` function. + Lgamma, + /// The value of `sys.platlibdir`. + Lib, + /// `line_num` attribute of the `csv` readers. + LineNum, + /// `os.linesep` constant name. + Linesep, + /// `lineterminator` dialect attribute and `csv` format parameter. + Lineterminator, + /// `csv.list_dialects()` function. + ListDialects, + /// `typing.List` marker. + #[strum(serialize = "List")] + ListType, + /// `os.listdir()` function. + Listdir, + /// `typing.Literal` marker. + #[strum(serialize = "Literal")] + Literal, + /// The value of `sys.byteorder` on every target Monty builds for. + Little, + /// `ljust()` method, shared by `str` and `bytes`. + Ljust, + /// `lo` in the bisect module. + Lo, + /// `json.load()` and `tomllib.load()` functions. + Load, + /// `json.loads()` and `tomllib.loads()` functions. + Loads, + /// `decimal.localcontext()` function. + Localcontext, + /// `locals` parameter of eval/exec. + Locals, + /// `time.localtime()` function. + Localtime, + /// `math.log()` function. + Log, + /// `math.log10()` function. + Log10, + /// `math.log1p()` function. + Log1p, + /// `math.log2()` function. + Log2, + /// `random.lognormvariate()` function. + Lognormvariate, + /// `unicodedata.lookup()` function. + Lookup, + /// `low` parameter of `random.triangular()`. + Low, + /// `lower()` method, shared by `str` and `bytes`. + Lower, + /// `functools.lru_cache()` function. + LruCache, + /// `lstrip()` method, shared by `str` and `bytes`. + Lstrip, + /// `sys.version_info.major` field. + Major, + /// `os.makedirs()` function. + Makedirs, + /// `sys.float_info.mant_dig` field. + MantDig, + /// `map01` parameter of `base64.b32decode()`. + #[strum(serialize = "map01")] + Map01, + /// `typing.Mapping` marker. + #[strum(serialize = "Mapping")] + Mapping, + /// `re.match()` / `pattern.match()` method + Match, + /// `@dataclass(match_args=...)`. + MatchArgs, + /// The `__match_args__` class attribute class patterns read and `@dataclass` writes. + #[strum(serialize = "__match_args__")] + MatchArgsDunder, + /// `re.Match` + #[strum(serialize = "Match")] + MatchClass, + /// Module name for `import math`. + Math, + /// `math.inf` constant + #[strum(serialize = "inf")] + MathInf, + /// `math.nan` constant + #[strum(serialize = "nan")] + MathNan, + /// `sys.float_info.max` field; also the `max` class constant of the `datetime` classes. + Max, + /// `sys.float_info.max_10_exp` field. + #[strum(serialize = "max_10_exp")] + Max10Exp, + /// `base64.MAXBINSIZE` module constant. + #[strum(serialize = "MAXBINSIZE")] + MaxBinSize, + /// `blake2b.MAX_DIGEST_SIZE` class constant. + #[strum(serialize = "MAX_DIGEST_SIZE")] + MaxDigestSize, + /// `decimal.MAX_EMAX` constant. + #[strum(serialize = "MAX_EMAX")] + MaxEmax, + /// `sys.float_info.max_exp` field. + MaxExp, + /// `blake2b.MAX_KEY_SIZE` class constant. + #[strum(serialize = "MAX_KEY_SIZE")] + MaxKeySize, + /// `base64.MAXLINESIZE` module constant. + #[strum(serialize = "MAXLINESIZE")] + MaxLineSize, + /// `decimal.MAX_PREC` constant. + #[strum(serialize = "MAX_PREC")] + MaxPrec, + /// `deque.maxlen` attribute (also a constructor keyword argument). + Maxlen, + /// `sys.maxsize` attribute. + Maxsize, + /// Kwarg name `maxsplit` — `str.split(maxsplit=...)`, `re.split(maxsplit=...)`. + Maxsplit, + /// `sys.maxunicode` attribute. + Maxunicode, + /// `hashlib.md5()` function and hash name. + Md5, + /// `memo` parameter of `copy.deepcopy()`. + Memo, + /// `field(metadata=...)`. + Metadata, + /// `sys.version_info.micro` field. + Micro, + /// `datetime` / `time` `microsecond` attribute and constructor kwarg. + Microsecond, + /// `timedelta.microseconds` attribute and constructor kwarg. + Microseconds, + /// `timedelta(milliseconds=...)` constructor kwarg. + Milliseconds, + /// `sys.float_info.min` field; also the `min` class constant of the `datetime` classes. + Min, + /// `sys.float_info.min_10_exp` field. + #[strum(serialize = "min_10_exp")] + Min10Exp, + /// `decimal.MIN_EMIN` constant. + #[strum(serialize = "MIN_EMIN")] + MinEmin, + /// `decimal.MIN_ETINY` constant. + #[strum(serialize = "MIN_ETINY")] + MinEtiny, + /// `sys.float_info.min_exp` field. + MinExp, + /// `sys.version_info.minor` field. + Minor, + /// `datetime` / `time` `minute` attribute and constructor kwarg. + Minute, + /// `timedelta(minutes=...)` constructor kwarg. + Minutes, + /// `CacheInfo.misses` field. + Misses, + /// `dataclasses.MISSING` — the sentinel for an argument not given, since + /// `None` is a legitimate default. + #[strum(serialize = "MISSING")] + Missing, + /// Path.unlink missing-file option. + MissingOk, + /// `Path.mkdir()` and `os.mkdir()` — yields a host call. + Mkdir, + /// `time.mktime()` function. + Mktime, + /// `file.mode` attribute and the `open(mode=...)` kwarg. + Mode, + /// `math.modf()` function. + Modf, + /// ``, the traceback frame name for top-level code. + #[strum(serialize = "")] + Module, + /// `namedtuple(..., module=...)` keyword argument. + #[strum(serialize = "module")] + ModuleKwarg, + /// Kwarg name `modulo` — `Context.power()`. + Modulo, + /// `time.monotonic()` function. + Monotonic, + /// `time.monotonic_ns()` function. + MonotonicNs, + /// `date` / `datetime` `month` attribute and constructor kwarg. + Month, + /// Value of `sys.platform`. + Monty, + /// The value of `sys.copyright`. + #[strum(serialize = "Copyright (c) Pydantic Services Inc. 2026 to present")] + MontyCopyright, + /// Value of `sys.version`. + #[strum(serialize = "3.14.0 (Monty)")] + MontyVersionString, + /// `Counter.most_common()` method. + #[strum(serialize = "most_common")] + MostCommon, + /// `mu` parameter of `random.gauss()` and the other normal variates. + Mu, + /// `re.MULTILINE` flag + #[strum(serialize = "MULTILINE")] + MultilineFlag, + /// `Path.name` property; also `file.name`, `os.name` and `unicodedata.name()`. + Name, + /// The `collections.namedtuple` factory function. + Namedtuple, + /// Kwarg name `ndigits` — `round(ndigits=...)`. + Ndigits, + /// `typing.Never` marker. + #[strum(serialize = "Never")] + Never, + /// Kwarg name `new` — `str.replace(new=...)`, `bytes.replace(new=...)`. + New, + /// `new_limit` parameter of `csv.field_size_limit()`. + NewLimit, + /// Kwarg name `newline` — `open(newline=...)`. + Newline, + /// `math.nextafter()` function. + Nextafter, + /// `_nil` parameter of `copy.deepcopy()`, CPython's private sentinel. + #[strum(serialize = "_nil")] + NilSentinel, + /// `re.NOFLAG` flag + #[strum(serialize = "NOFLAG")] + NoFlag, + /// `typing.NoReturn` marker. + #[strum(serialize = "NoReturn")] + NoReturn, + /// `sys.flags.no_site` field. + NoSite, + /// `sys.flags.no_user_site` field. + NoUserSite, + /// `node_depth` parameter of `hashlib.blake2b()`. + NodeDepth, + /// `node_offset` parameter of `hashlib.blake2b()`. + NodeOffset, + /// `repr()`/`str()` text of `None`, interned so rendering allocates nothing. + #[strum(serialize = "None")] + NoneRepr, + /// `unicodedata.normalize()` function. + Normalize, + /// `random.normalvariate()` function. + Normalvariate, + /// `os.path.normcase()` function. + Normcase, + /// `os.path.normpath()` function. + Normpath, + /// Python's `NotImplemented` singleton representation. + #[strum(serialize = "NotImplemented")] + NotImplementedRepr, + /// `datetime.now()` classmethod. + Now, + /// Kwarg name `num` — `Context.create_decimal()`. + Num, + /// Kwarg name `number` — `round(number=...)`. + Number, + /// Kwarg name `obj` — `json.dumps(obj=...)`. + Obj, + /// Kwarg name `object` — `str(object=...)`, `itertools.repeat(object=...)`. + Object, + /// `timezone(offset=...)` constructor kwarg. + Offset, + /// Kwarg name `old` — `str.replace(old=...)`, `bytes.replace(old=...)`. + Old, + /// Kwarg name `on_error` — `Path.walk(on_error=...)`. + OnError, + /// Kwarg name `onerror` — `os.walk(onerror=...)`. + Onerror, + /// `Path.open()` and the `open()` builtin, which share the `OsFunctionCall::Open` + /// round-trip. `Path::py_call_attr` delegates to `builtin_open` for mode/kwarg + /// validation rather than taking the generic `is_path_os_method` pre-flight. + Open, + /// Kwarg name `opener` — `open(opener=...)`. + Opener, + /// `sys.flags.optimize` field. + Optimize, + /// `typing.Optional` marker. + #[strum(serialize = "Optional")] + Optional, + /// `@dataclass(order=...)`. + Order, + /// Module name for `import os`. + Os, + /// `os.fspath()` function — distinct from `Fspath` (`__fspath__`). + #[strum(serialize = "fspath")] + OsFspath, + /// Module name for `import os.path`. + #[strum(serialize = "os.path")] + OsPath, + /// Named-tuple type name of the `os.stat()` result. + #[strum(serialize = "StatResult")] + OsStatResult, + /// Kwarg name `other` — the binary `Decimal` methods. + Other, + /// `decimal.Overflow` signal. + #[strum(serialize = "Overflow")] + Overflow, + /// Kwarg name `override` — `Decimal.__format__()`. + Override, + /// `pad` parameter of `base64.b85encode()`. + #[strum(serialize = "pad")] + Pad, + /// `itertools.pairwise()` function. + Pairwise, + /// `os.pardir` constant name. + Pardir, + /// `Path.parent` property. + Parent, + /// Value of `os.pardir`. + #[strum(serialize = "..")] + ParentDirString, + /// Kwarg name `parents` — `Path.mkdir(parents=...)`. + Parents, + /// `random.paretovariate()` function. + Paretovariate, + /// Kwarg name `parse_float` — `json.loads()`. + ParseFloat, + /// Kwarg name `parse_int` — `json.loads()`. + ParseInt, + /// `functools.partial` type. + Partial, + /// `partition()` method, shared by `str` and `bytes`. + Partition, + /// `Path.parts` property. + Parts, + /// `password` parameter of `hashlib.pbkdf2_hmac()`. + Password, + /// Kwarg name `path` — `os.listdir(path=...)`, `os.stat(path=...)`, etc. + Path, + /// The `pathlib.Path` type. + #[strum(serialize = "Path")] + PathClass, + /// Module name for `import pathlib`. + Pathlib, + /// Kwarg name `paths` — `os.path.commonpath(paths=...)`. + Paths, + /// `os.pathsep` / `os.path.pathsep` constant name. + Pathsep, + /// `pattern.pattern` + #[strum(serialize = "pattern")] + PatternAttr, + /// `re.Pattern` + #[strum(serialize = "Pattern")] + PatternClass, + /// `re.PatternError` exception + #[strum(serialize = "PatternError")] + PatternError, + /// `hashlib.pbkdf2_hmac()` function. + Pbkdf2Hmac, + /// `time.perf_counter()` function. + PerfCounter, + /// `time.perf_counter_ns()` function. + PerfCounterNs, + /// `math.perm()` function. + Perm, + /// `itertools.permutations()` function. + Permutations, + /// `person` parameter of `hashlib.blake2b()`. + Person, + /// `blake2b.PERSON_SIZE` class constant. + #[strum(serialize = "PERSON_SIZE")] + PersonSize, + /// `math.pi` constant + Pi, + /// `sys.platform` attribute. + Platform, + /// `sys.platlibdir` attribute. + Platlibdir, + /// `pop()` method, shared by `list`, `dict`, `set` and `deque`. + Pop, + /// `dict.popitem()` method. + Popitem, + /// `deque.popleft()` method. + Popleft, + /// `population` parameter of `random.choices()` and `random.sample()`. + Population, + /// Value of `os.name`. + Posix, + /// Module name for `import posixpath`, and the name `os.path` reports. + Posixpath, + /// `__post_init__` — the hook the generated `__init__` calls last. + #[strum(serialize = "__post_init__")] + PostInit, + /// `math.pow()` function. + Pow, + /// Kwarg name `prec` — `decimal.Context()`. + Prec, + /// `sys.prefix` attribute. + Prefix, + /// `time.process_time()` function. + ProcessTime, + /// `time.process_time_ns()` function. + ProcessTimeNs, + /// `math.prod()` function. + Prod, + /// `itertools.product()` function. + Product, + /// `typing.Protocol` marker. + #[strum(serialize = "Protocol")] + Protocol, + /// `sys.pycache_prefix` attribute. + PycachePrefix, + /// `sys.flags.quiet` field. + Quiet, + /// `csv.QUOTE_ALL` constant. + #[strum(serialize = "QUOTE_ALL")] + QuoteAll, + /// `csv.QUOTE_MINIMAL` constant. + #[strum(serialize = "QUOTE_MINIMAL")] + QuoteMinimal, + /// `csv.QUOTE_NONE` constant. + #[strum(serialize = "QUOTE_NONE")] + QuoteNone, + /// `csv.QUOTE_NONNUMERIC` constant. + #[strum(serialize = "QUOTE_NONNUMERIC")] + QuoteNonnumeric, + /// `csv.QUOTE_NOTNULL` constant. + #[strum(serialize = "QUOTE_NOTNULL")] + QuoteNotnull, + /// `csv.QUOTE_STRINGS` constant. + #[strum(serialize = "QUOTE_STRINGS")] + QuoteStrings, + /// `quotechar` dialect attribute and `csv` format parameter. + Quotechar, + /// `quotetabs` parameter of `binascii.b2a_qp()`. + #[strum(serialize = "quotetabs")] + Quotetabs, + /// `quoting` dialect attribute and `csv` format parameter. + Quoting, + /// `math.radians()` function. + Radians, + /// `sys.float_info.radix` field. + Radix, + /// `extrasaction='raise'`, the `csv.DictWriter` default. + Raise, + /// `random.randbytes()` function. + Randbytes, + /// `random.randint()` function. + Randint, + /// Module name for `import random`, and the `random.random()` function. + Random, + /// The `random.Random` class. + #[strum(serialize = "Random")] + RandomClass, + /// `Random.VERSION`, the `getstate()` format number. + #[strum(serialize = "VERSION")] + RandomVersion, + /// `random.randrange()` function. + Randrange, + /// Module name for `import re`. + Re, + /// `file.read()` method. + Read, + /// `Path.read_bytes()` method — yields a host call. + ReadBytes, + /// `Path.read_text()` method — yields a host call. + ReadText, + /// `file.readable()` method. + Readable, + /// `csv.reader()` function and `csv.DictReader.reader` attribute. + Reader, + /// `file.readline()` method. + Readline, + /// `file.readlines()` method. + Readlines, + /// `complex.real` attribute. + Real, + /// `os.path.realpath()` function. + Realpath, + /// Kwarg name `recurse_symlinks` — `Path.glob(recurse_symlinks=...)`. + RecurseSymlinks, + /// `functools.reduce()` function. + Reduce, + /// Kwarg name `rel_tol` — `math.isclose(rel_tol=...)`. + RelTol, + /// `sys.version_info.releaselevel` field. + Releaselevel, + /// `os.path.relpath()` function. + Relpath, + /// `math.remainder()` function. + Remainder, + /// `remove()` method, shared by `set`, `list` and `deque`. + Remove, + /// `removeprefix()` method, shared by `str` and `bytes`. + Removeprefix, + /// `removesuffix()` method, shared by `str` and `bytes`. + Removesuffix, + /// `Path.rename()` and `os.rename()` — yields a host call. + Rename, + /// `itertools.repeat()` function. + Repeat, + /// Kwarg name `repl` — `re.sub(repl=...)`. + Repl, + /// `replace()` method, shared by `str` and `bytes`. + Replace, + /// `@dataclass(repr=...)`. + Repr, + /// `resolution` class constant of the `datetime` classes. + Resolution, + /// `Path.resolve()` method — yields a host call. + Resolve, + /// `restkey` parameter and attribute of `csv.DictReader`. + Restkey, + /// `restval` parameter and attribute of `csv.DictReader` / `csv.DictWriter`. + Restval, + /// `result` parameter of `asyncio.sleep()`. + #[strum(serialize = "result")] + ResultArg, + /// Kwarg name `return_exceptions` — `asyncio.gather(return_exceptions=...)`. + ReturnExceptions, + /// `list.reverse()` method. + Reverse, + /// `rfind()` method, shared by `str` and `bytes`. + Rfind, + /// `Path.rglob()` method — yields a host scan. + Rglob, + /// `rindex()` method, shared by `str` and `bytes`. + Rindex, + /// `rjust()` method, shared by `str` and `bytes`. + Rjust, + /// `Path.rmdir()` and `os.rmdir()` — yields a host call. + Rmdir, + /// `deque.rotate()` method. + Rotate, + /// `decimal.ROUND_05UP` rounding mode. + #[strum(serialize = "ROUND_05UP")] + Round05up, + /// `decimal.ROUND_CEILING` rounding mode. + #[strum(serialize = "ROUND_CEILING")] + RoundCeiling, + /// `decimal.ROUND_DOWN` rounding mode. + #[strum(serialize = "ROUND_DOWN")] + RoundDown, + /// `decimal.ROUND_FLOOR` rounding mode. + #[strum(serialize = "ROUND_FLOOR")] + RoundFloor, + /// `decimal.ROUND_HALF_DOWN` rounding mode. + #[strum(serialize = "ROUND_HALF_DOWN")] + RoundHalfDown, + /// `decimal.ROUND_HALF_EVEN` rounding mode. + #[strum(serialize = "ROUND_HALF_EVEN")] + RoundHalfEven, + /// `decimal.ROUND_HALF_UP` rounding mode. + #[strum(serialize = "ROUND_HALF_UP")] + RoundHalfUp, + /// `decimal.ROUND_UP` rounding mode. + #[strum(serialize = "ROUND_UP")] + RoundUp, + /// `decimal.Rounded` signal. + #[strum(serialize = "Rounded")] + Rounded, + /// Kwarg name `rounding` — `Decimal.quantize()` and friends. + Rounding, + /// `sys.float_info.rounds` field. + Rounds, + /// `rpartition()` method, shared by `str` and `bytes`. + Rpartition, + /// `rsplit()` method, shared by `str` and `bytes`. + Rsplit, + /// `rstrip()` method, shared by `str` and `bytes`. + Rstrip, + /// `asyncio.run()` function. + Run, + /// Kwarg name `s1` — `os.path.samestat(s1=...)`. + S1, + /// Kwarg name `s2` — `os.path.samestat(s2=...)`. + S2, + /// `sys.flags.safe_path` field. + SafePath, + /// `salt` parameter of `hashlib.blake2b()` and `pbkdf2_hmac()`. + Salt, + /// `blake2b.SALT_SIZE` class constant. + #[strum(serialize = "SALT_SIZE")] + SaltSize, + /// `os.path.samefile()` function. + Samefile, + /// `os.path.samestat()` function. + Samestat, + /// `random.sample()` function. + Sample, + /// `os.scandir()` function — yields a host scan. + Scandir, + /// `re.search()` / `pattern.search()` method + Search, + /// `datetime` / `time` `second` attribute and constructor kwarg. + Second, + /// `timedelta.seconds` attribute and constructor kwarg. + Seconds, + /// `random.seed()` function. + Seed, + /// `file.seek()` method. + Seek, + /// `file.seekable()` method. + Seekable, + /// `selectors` keyword argument of `itertools.compress()`. + Selectors, + /// `typing.Self` marker. + #[strum(serialize = "Self")] + SelfType, + /// Kwarg name `sep` — `str.split(sep=...)`, `print(sep=...)`, etc. + Sep, + /// `json.dumps(separators=...)` keyword. + Separators, + /// `seq` parameter of `random.choice()`. + Seq, + /// `typing.Sequence` marker. + #[strum(serialize = "Sequence")] + Sequence, + /// `sys.version_info.serial` field. + Serial, + /// `typing.Set` marker. + #[strum(serialize = "Set")] + SetType, + /// `decimal.setcontext()` function. + Setcontext, + /// `dict.setdefault()` method. + Setdefault, + /// `sys.setrecursionlimit()` function (only callable under `test-hooks`). + Setrecursionlimit, + /// `random.setstate()` function. + Setstate, + /// `hashlib.sha1()` function and hash name. + Sha1, + /// `hashlib.sha224()` function and hash name. + Sha224, + /// `hashlib.sha256()` function and hash name. + Sha256, + /// `hashlib.sha384()` function and hash name. + Sha384, + /// `hashlib.sha3_224()` function and hash name. + #[strum(serialize = "sha3_224")] + Sha3_224, + /// `hashlib.sha3_256()` function and hash name. + #[strum(serialize = "sha3_256")] + Sha3_256, + /// `hashlib.sha3_384()` function and hash name. + #[strum(serialize = "sha3_384")] + Sha3_384, + /// `hashlib.sha3_512()` function and hash name. + #[strum(serialize = "sha3_512")] + Sha3_512, + /// `hashlib.sha512()` function and hash name. + Sha512, + /// `hashlib.shake_128()` function and hash name. + #[strum(serialize = "shake_128")] + Shake128, + /// `hashlib.shake_256()` function and hash name. + #[strum(serialize = "shake_256")] + Shake256, + /// The value of `sys.float_repr_style`. + Short, + /// `random.shuffle()` function. + Shuffle, + /// `sigma` parameter of `random.gauss()` and the other normal variates. + Sigma, + /// `DecimalTuple.sign` field. + Sign, + /// `math.sin()` function. + Sin, + /// `math.sinh()` function. + Sinh, + /// `size` parameter of `os.urandom()`. + Size, + /// `skipinitialspace` dialect attribute and `csv` format parameter. + Skipinitialspace, + /// `json.dumps(skipkeys=...)` keyword. + Skipkeys, + /// `time.sleep()` and `asyncio.sleep()`. + Sleep, + /// `@dataclass(slots=...)`. + Slots, + /// `list.sort()` method. + Sort, + /// `json.dumps(sort_keys=...)` keyword. + #[strum(serialize = "sort_keys")] + SortKeys, + /// Kwarg name `source` — `bytes(source=...)`, `bytearray(source=...)`. + Source, + /// `match.span()` method + Span, + /// `split()` method, shared by `str` and `bytes`; also `re.split()`. + Split, + /// `os.path.splitdrive()` function. + Splitdrive, + /// `os.path.splitext()` function. + Splitext, + /// `splitlines()` method, shared by `str` and `bytes`. + Splitlines, + /// `os.path.splitroot()` function. + Splitroot, + /// `math.sqrt()` function. + Sqrt, + /// Kwarg name `src` — `os.rename(src=...)`, `os.replace(src=...)`. + Src, + /// Kwarg name `src_dir_fd` — `os.rename(src_dir_fd=...)`. + SrcDirFd, + /// `os.stat_result.st_atime` field. + StAtime, + /// `os.stat_result.st_ctime` field. + StCtime, + /// `os.stat_result.st_dev` field. + StDev, + /// `os.stat_result.st_gid` field. + StGid, + /// `os.stat_result.st_ino` field. + StIno, + /// `os.stat_result.st_mode` field. + StMode, + /// `os.stat_result.st_mtime` field. + StMtime, + /// `os.stat_result.st_nlink` field. + StNlink, + /// `os.stat_result.st_size` field. + StSize, + /// `os.stat_result.st_uid` field. + StUid, + /// `base64.standard_b64decode()` function. + #[strum(serialize = "standard_b64decode")] + StandardB64Decode, + /// `base64.standard_b64encode()` function. + #[strum(serialize = "standard_b64encode")] + StandardB64Encode, + /// `itertools.starmap()` function. + Starmap, + /// `slice.start` attribute; also the `start` kwarg of `itertools.count()`. + Start, + /// `startswith()` method, shared by `str` and `bytes`. + Startswith, + /// `Path.stat()` and `os.stat()` — yields a host call. + #[strum(serialize = "stat")] + StatMethod, + /// `state` parameter of `Random.setstate()`. + State, + /// `sys.stderr` attribute and the marker it holds. + Stderr, + /// `sys.stdout` attribute and the marker it holds. + Stdout, + /// `Path.stem` property. + Stem, + /// `slice.step` attribute; also the `step` kwarg of `itertools.count()`. + Step, + /// `slice.stop` attribute. + Stop, + /// Private cache insertion primitive. + Store, + /// `date.strftime()` / `datetime.strftime()` method. + Strftime, + /// Kwarg name `strict` — `zip(strict=...)`. + Strict, + /// `strict_mode` parameter of `binascii.a2b_base64()`. + #[strum(serialize = "strict_mode")] + StrictMode, + /// `match.string` + #[strum(serialize = "string")] + StringAttr, + /// `strip()` method, shared by `str` and `bytes`. + Strip, + /// `datetime.strptime()` classmethod. + Strptime, + /// Named-tuple type name of a `time` module `struct_time`. + #[strum(serialize = "time.struct_time")] + StructTime, + /// `re.sub()` / `pattern.sub()` method + Sub, + /// `decimal.Subnormal` signal. + #[strum(serialize = "Subnormal")] + Subnormal, + /// `Counter.subtract()` method. + Subtract, + /// `Path.suffix` property. + Suffix, + /// `Path.suffixes` property. + Suffixes, + /// `math.sumprod()` function. + Sumprod, + /// `os.path.supports_unicode_filenames` constant name. + SupportsUnicodeFilenames, + /// `swapcase()` method, shared by `str` and `bytes`. + Swapcase, + /// `set.symmetric_difference()` method. + SymmetricDifference, + /// Module name for `import sys`. + Sys, + /// Named-tuple type name of `sys.flags`. + #[strum(serialize = "sys.flags")] + SysFlags, + /// Named-tuple type name of `sys.float_info`. + #[strum(serialize = "sys.float_info")] + SysFloatInfo, + /// Named-tuple type name of `sys.version_info`. + #[strum(serialize = "sys.version_info")] + SysVersionInfo, + /// Kwarg name `tabsize` — `str.expandtabs(tabsize=...)`. + Tabsize, + /// `itertools.takewhile()` function. + Takewhile, + /// `math.tan()` function. + Tan, + /// `math.tanh()` function. + Tanh, + /// Destination keyword for Path.rename and Path.replace. + Target, + /// `math.tau` constant + Tau, + /// `itertools.tee()` function. + Tee, + /// `itertools._tee_dataobject`, the buffer those iterators share. + #[strum(serialize = "_tee_dataobject")] + TeeDataObject, + /// `itertools._tee`, the iterator `tee()` hands out. + #[strum(serialize = "_tee")] + TeeType, + /// `file.tell()` method. + Tell, + /// Kwarg name `third` — `Decimal.fma()`. + Third, + /// `time.thread_time()` function. + ThreadTime, + /// `time.thread_time_ns()` function. + ThreadTimeNs, + /// `datetime.time` class name. + Time, + /// `time.time_ns()` function. + TimeNs, + /// The `datetime.timedelta` type. + Timedelta, + /// `times` keyword argument of `itertools.repeat()`. + Times, + /// `timespec` keyword of `time.isoformat()` and `datetime.isoformat()`. + Timespec, + /// `datetime.timestamp()` method. + Timestamp, + /// `datetime.timetz` method name. + Timetz, + /// The `datetime.timezone` type. + Timezone, + /// `title()` method, shared by `str` and `bytes`. + Title, + /// `struct_time.tm_gmtoff` field. + TmGmtoff, + /// `struct_time.tm_hour` field. + TmHour, + /// `struct_time.tm_isdst` field. + TmIsdst, + /// `struct_time.tm_mday` field. + TmMday, + /// `struct_time.tm_min` field. + TmMin, + /// `struct_time.tm_mon` field. + TmMon, + /// `struct_time.tm_sec` field. + TmSec, + /// `struct_time.tm_wday` field. + TmWday, + /// `struct_time.tm_yday` field. + TmYday, + /// `struct_time.tm_year` field. + TmYear, + /// `struct_time.tm_zone` field. + TmZone, + /// `date.today()` / `datetime.today()` classmethod. + Today, + /// `tomllib.TOMLDecodeError` exception. + #[strum(serialize = "TOMLDecodeError")] + TomlDecodeError, + /// Module name for `import tomllib`. + Tomllib, + /// Kwarg name `top` — `os.walk(top=...)`. + Top, + /// Kwarg name `top_down` — `Path.walk(top_down=...)`. + TopDown, + /// Kwarg name `topdown` — `os.walk(topdown=...)`. + Topdown, + /// `Counter.total()` method. + Total, + /// `timedelta.total_seconds()` method. + TotalSeconds, + /// Kwarg name `traps` — `decimal.Context()`. + Traps, + /// `random.triangular()` function. + Triangular, + /// `repr()`/`str()` text of `True`, interned so rendering allocates nothing. + #[strum(serialize = "True")] + TrueRepr, + /// `math.trunc()` function. + Trunc, + /// `typing.Tuple` marker. + #[strum(serialize = "Tuple")] + TupleType, + /// `typing.Type` marker. + #[strum(serialize = "Type")] + Type, + /// `typing.TYPE_CHECKING` constant. + #[strum(serialize = "TYPE_CHECKING")] + TypeChecking, + /// `typing.TypeVar` marker. + #[strum(serialize = "TypeVar")] + TypeVar, + /// Whether argument types distinguish cache keys. + Typed, + /// `namedtuple(typename=...)` keyword argument. + Typename, + /// Module name for `import typing`. + Typing, + /// `datetime.now(tz=...)` kwarg. + Tz, + /// `datetime.tzinfo` attribute and constructor kwarg. + Tzinfo, + /// `tzname()` method of `time`, `datetime` and `timezone`. (`dst()` reuses + /// the `Dst` variant already interned for the `os` kwarg of the same name.) + Tzname, + /// `math.ulp()` function. + Ulp, + /// `NamedTuple._asdict()` method. + #[strum(serialize = "_asdict")] + UnderAsdict, + /// `NamedTuple._field_defaults` — dict of defaulted field names to values. + #[strum(serialize = "_field_defaults")] + UnderFieldDefaults, + /// `NamedTuple._fields` — tuple of field names. + #[strum(serialize = "_fields")] + UnderFields, + /// `NamedTuple._make(iterable)` classmethod. + #[strum(serialize = "_make")] + UnderMake, + /// `NamedTuple._replace(**kwargs)` method. + #[strum(serialize = "_replace")] + UnderReplace, + /// `decimal.Underflow` signal. + #[strum(serialize = "Underflow")] + Underflow, + /// `binascii.unhexlify()` function. + #[strum(serialize = "unhexlify")] + Unhexlify, + /// Module name for `import unicodedata`. + Unicodedata, + /// `unicodedata.unidata_version` constant. + #[strum(serialize = "unidata_version")] + UnidataVersion, + /// `random.uniform()` function. + Uniform, + /// `set.union()` method. + Union, + /// `typing.Union` marker. + #[strum(serialize = "Union")] + UnionType, + /// `csv.unix_dialect` dialect. + UnixDialect, + /// `Path.unlink()` and `os.unlink()` — yields a host call. + Unlink, + /// `@dataclass(unsafe_hash=...)`. + UnsafeHash, + /// `update()` method, shared by `set` and `dict`. + Update, + /// `upper()` method, shared by `str` and `bytes`. + Upper, + /// `os.urandom()` function. + Urandom, + /// `base64.urlsafe_b64decode()` function. + #[strum(serialize = "urlsafe_b64decode")] + UrlsafeB64Decode, + /// `base64.urlsafe_b64encode()` function. + #[strum(serialize = "urlsafe_b64encode")] + UrlsafeB64Encode, + /// `usedforsecurity` keyword of the `hashlib` constructors. + Usedforsecurity, + /// Callable accepted by caching decorators. + UserFunction, + /// `timezone.utc` class constant. + Utc, + /// `utcoffset()` method of `time`, `datetime` and `timezone`. + Utcoffset, + /// `sys.flags.utf8_mode` field. + #[strum(serialize = "utf8_mode")] + Utf8Mode, + /// `validate` parameter of `base64.b64decode()`. + #[strum(serialize = "validate")] + Validate, + /// Kwarg name `value` — `decimal.Decimal()`. + Value, + /// `dict.values()` method. + Values, + /// `sys.flags.verbose` field. + Verbose, + /// `sys.version` attribute. + Version, + /// `sys.version_info` attribute. + VersionInfo, + /// `random.vonmisesvariate()` function. + Vonmisesvariate, + /// `os.walk()` / `Path.walk()` — yields a host scan. + Walk, + /// `sys.flags.warn_default_encoding` field. + WarnDefaultEncoding, + /// `@dataclass(weakref_slot=...)`. + WeakrefSlot, + /// `date.weekday()` / `datetime.weekday()` method. + Weekday, + /// `timedelta(weeks=...)` constructor kwarg. + Weeks, + /// `random.weibullvariate()` function. + Weibullvariate, + /// `weights` parameter of `random.choices()`. + Weights, + /// `Path.with_name()` method, answered without host I/O. + WithName, + /// `Path.with_stem()` method, answered without host I/O. + WithStem, + /// `Path.with_suffix()` method, answered without host I/O. + WithSuffix, + /// `wrapcol` parameter of `base64.a85encode()`. + #[strum(serialize = "wrapcol")] + Wrapcol, + /// `file.writable()` method. + Writable, + /// `file.write()` method. + Write, + /// `Path.write_bytes()` method — yields a host call. + WriteBytes, + /// `Path.write_text()` method — yields a host call. + WriteText, + /// `csv.DictWriter.writeheader()` method. + Writeheader, + /// `csv.writer()` function and `csv.DictWriter.writer` attribute. + Writer, + /// `writerow()` method of the `csv` writers. + Writerow, + /// `writerows()` method of the `csv` writers. + Writerows, + /// `date` / `datetime` `year` attribute and constructor kwarg. + Year, + /// `base64.z85decode()` function. + #[strum(serialize = "z85decode")] + Z85Decode, + /// `base64.z85encode()` function. + #[strum(serialize = "z85encode")] + Z85Encode, + /// `zfill()` method, shared by `str` and `bytes`. + Zfill, + /// `itertools.zip_longest()` function. + ZipLongest, +} + +/// One immutable interned string with directly accessible dispatch metadata. +/// Snapshots store only text; loading reconstructs the tag and cached hash. +#[derive(Debug, Clone)] +struct InternedString { + /// Runtime classification, independent of the string's executor-local ID. + static_tag: Option, + /// Text and its eagerly computed Python hash. + text: WithHash, +} + +/// Ownership of interned text, independent of its dispatch metadata. +#[derive(Debug, Clone)] +enum InternedText { + /// Text recognized by this build, requiring no owned allocation. + Static(&'static str), + /// Source or snapshot text unknown to the static registry. + Owned(Box), +} + +impl AsRef for InternedText { + fn as_ref(&self) -> &str { + match self { + Self::Static(text) => text, + Self::Owned(text) => text, + } + } +} + +impl InternedString { + /// Creates an entry for compile-time-known text. + fn static_string(value: StaticStrings) -> Self { + Self { + static_tag: Some(value), + text: WithHash::for_str(InternedText::Static(value.into())), + } + } + + /// Creates an entry owning text not present in the static registry. + fn owned(value: String) -> Self { + Self { + static_tag: None, + text: WithHash::for_str(InternedText::Owned(value.into_boxed_str())), + } + } + + /// Returns the interned text. + fn as_str(&self) -> &str { + self.text.value().as_ref() + } + + /// Returns the cached Python hash. + fn hash(&self) -> HashValue { + self.text.hash() + } + + /// Returns the static tag when this build recognizes the text. + fn static_value(&self) -> Option { + self.static_tag + } +} + +impl serde::Serialize for InternedString { + fn serialize(&self, serializer: S) -> Result { + serde::Serialize::serialize(self.as_str(), serializer) + } +} + +impl<'de> serde::Deserialize<'de> for InternedString { + fn deserialize>(deserializer: D) -> Result { + let value = ::deserialize(deserializer)?; + Ok(match StaticStrings::from_str(&value) { + Ok(static_string) => Self::static_string(static_string), + Err(_) => Self::owned(value), + }) + } +} + +/// Index into the bytes interner's storage. +/// +/// Separate from `StringId` to distinguish string vs bytes literals at the type level. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct BytesId(u32); + +impl BytesId { + /// Returns the raw index value. + #[inline] + pub fn index(self) -> usize { + self.0 as usize + } +} + +/// Index into the long integer interner's storage. +/// +/// Used for integer literals that exceed i64 range. The actual `BigInt` values +/// are stored in the `Interns` table and looked up by index at runtime. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct LongIntId(u32); + +impl LongIntId { + /// Returns the raw index value. + #[inline] + pub fn index(self) -> usize { + self.0 as usize + } +} + +/// Unique identifier for functions +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +pub struct FunctionId(u32); + +impl FunctionId { + /// Creates a FunctionId from a raw index value. + /// + /// Used by the bytecode VM to reconstruct FunctionIds from operands stored + /// in bytecode. The caller is responsible for ensuring the index is valid. + #[inline] + pub fn from_index(index: u16) -> Self { + Self(u32::from(index)) + } + + /// Returns the raw index value. + #[inline] + pub fn index(self) -> usize { + self.0 as usize + } +} + +/// Prehashed core strings reused when constructing independent interners. +static CORE_ENTRIES: LazyLock> = LazyLock::new(|| { + CORE_STATIC_STRINGS + .iter() + .copied() + .map(InternedString::static_string) + .collect() +}); + +/// Interns a static tag into an append-only executor-local table. +fn intern_static( + static_string_ids: &RefCell>, + strings: &Entries, + value: StaticStrings, +) -> StringId { + let text: &'static str = value.into(); + if text.is_empty() { + StringId::EMPTY + } else if text.len() == 1 { + StringId::from_ascii(text.as_bytes()[0]) + } else { + let existing = static_string_ids.borrow().get(&value).copied(); + if let Some(id) = existing { + id + } else { + let id = next_string_id(strings.len()); + strings.push(InternedString::static_string(value)); + static_string_ids.borrow_mut().insert(value, id); + id + } + } +} + +/// Returns the next dense executor-local string ID. +fn next_string_id(strings_len: usize) -> StringId { + let index = strings_len + INTERN_STRING_ID_OFFSET; + assert!(index < SOURCE_ID_BASE, "StringId overflow"); + StringId(index.try_into().expect("StringId overflow")) +} + +/// Reverse of [`get_str`]: the `StringId` for `s`, or `None` if never interned. +fn get_string_id_by_name( + string_map: &AHashMap, + static_string_ids: &RefCell>, + s: &str, +) -> Option { + if s.is_empty() { + Some(StringId::EMPTY) + } else if s.len() == 1 { + Some(StringId::from_ascii(s.as_bytes()[0])) + } else if let Ok(value) = StaticStrings::from_str(s) { + static_string_ids.borrow().get(&value).copied() + } else { + string_map.get(s).copied() + } +} + +/// Looks up a string by its `StringId`. +/// +/// # Panics +/// +/// Panics if the ID is neither reserved nor a slot in this interner. +fn get_str(strings: &Entries, id: StringId) -> &str { + if let Some(text) = RESERVED_STRS.get(id.index()) { + text + } else { + strings[id.index() - INTERN_STRING_ID_OFFSET].as_str() + } +} + +/// Returns the static tag stored at `id`, if any. +#[inline] +fn get_static_string(strings: &Entries, id: StringId) -> Option { + if id == StringId::EMPTY { + Some(StaticStrings::EmptyString) + } else if id.index() < INTERN_STRING_ID_OFFSET { + StaticStrings::from_repr(u16::try_from(id.index()).expect("ASCII ID fits u16")) + } else { + strings[id.index() - INTERN_STRING_ID_OFFSET].static_tag + } +} + +/// Committed strings, literals, functions and snippet sources. +/// Entries never move or disappear; existing sessions publish private compilation overlays on success. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(try_from = "InternsWire")] +pub(crate) struct Interns { + strings: Entries, + bytes: Entries>>, + long_ints: Entries>, + /// Boxes keep a mostly empty storage page from reserving hundreds of function bodies. + functions: Entries>, + /// Installed internal implementations by identity, ordered for stable dump bytes. + frozen_functions: RefCell>, + eval_sources: Entries>, + #[serde(skip)] + string_id_by_name: RefCell>, + #[serde(skip)] + static_string_ids: RefCell>, + /// Prevents runtime insertion or a second compiler from consuming provisional IDs. + #[serde(skip)] + compiling: Cell, +} + +impl Default for Interns { + fn default() -> Self { + Self::new("") + } +} + +/// Serialized tables without the derived lookup maps or compilation lock. +#[derive(serde::Deserialize)] +struct InternsWire { + strings: Entries, + bytes: Entries>>, + long_ints: Entries>, + functions: Entries>, + #[serde(default)] + frozen_functions: RefCell>, + eval_sources: Entries>, +} + +impl TryFrom for Interns { + type Error = String; + + fn try_from(wire: InternsWire) -> Result { + let mut string_id_by_name = AHashMap::new(); + let mut static_string_ids = AHashMap::new(); + let mut seen = AHashSet::new(); + for (index, entry) in wire.strings.iter().enumerate() { + let text = entry.as_str(); + if text.is_empty() || text.len() == 1 || !seen.insert(text) { + return Err(format!("duplicate or reserved interned string {text:?}")); + } + let id = next_string_id(index); + if let Some(value) = entry.static_value() { + static_string_ids.insert(value, id); + } else { + string_id_by_name.insert(text.to_owned(), id); + } + } + Ok(Self { + strings: wire.strings, + bytes: wire.bytes, + long_ints: wire.long_ints, + functions: wire.functions, + frozen_functions: wire.frozen_functions, + eval_sources: wire.eval_sources, + string_id_by_name: RefCell::new(string_id_by_name), + static_string_ids: RefCell::new(static_string_ids), + compiling: Cell::new(false), + }) + } +} + +/// Filename-only IDs are separate from canonical Python strings. +/// Each snippet has distinct source identity but the same displayed filename. +const SOURCE_ID_BASE: usize = 1 << 31; + +impl Interns { + /// Moves session ownership without initializing another interner. + pub(crate) fn take(&mut self) -> Self { + mem::replace(self, Self::placeholder()) + } + + /// Empty replacement used while the executor owns the session's tables. + fn placeholder() -> Self { + Self { + strings: Entries::default(), + bytes: Entries::default(), + long_ints: Entries::default(), + functions: Entries::default(), + frozen_functions: RefCell::default(), + eval_sources: Entries::default(), + string_id_by_name: RefCell::default(), + static_string_ids: RefCell::default(), + compiling: Cell::new(false), + } + } + + /// Initializes the core static strings; other entries are appended on demand. + pub fn new(code: &str) -> Self { + let capacity = code.bytes().filter(|&b| b == b'"' || b == b'\'').count() >> 1; + let interns = Self { + strings: Entries::with_capacity(capacity + CORE_STATIC_STRINGS.len()), + bytes: Entries::default(), + long_ints: Entries::default(), + functions: Entries::default(), + frozen_functions: RefCell::default(), + eval_sources: Entries::default(), + string_id_by_name: RefCell::new(AHashMap::with_capacity(capacity)), + static_string_ids: RefCell::new(AHashMap::with_capacity(CORE_STATIC_STRINGS.len())), + compiling: Cell::new(false), + }; + for entry in CORE_ENTRIES.iter() { + let value = entry.static_value().expect("core entries are static"); + let id = next_string_id(interns.strings.len()); + interns.strings.push(entry.clone()); + interns.static_string_ids.borrow_mut().insert(value, id); + } + interns + } + + /// Interns runtime static text without invalidating existing string borrows. + pub(crate) fn intern_static(&self, value: StaticStrings) -> StringId { + assert!(!self.compiling.get(), "runtime interning during compilation"); + intern_static(&self.static_string_ids, &self.strings, value) + } + + /// Looks up a Python string; filename identities use `get_filename` instead. + #[inline] + pub fn get_str(&self, id: StringId) -> &str { + get_str(&self.strings, id) + } + + /// Resolves a traceback filename, displaying each snippet's source identity as ``. + pub(crate) fn get_filename(&self, id: StringId) -> &str { + if id.index() >= SOURCE_ID_BASE { + assert!( + id.index() - SOURCE_ID_BASE < self.eval_sources.len(), + "invalid snippet source ID" + ); + "" + } else { + get_str(&self.strings, id) + } + } + + /// Returns dispatch metadata independent of the executor-local ID. + pub(crate) fn static_string(&self, id: StringId) -> Option { + get_static_string(&self.strings, id) + } + + /// Borrows a committed bytes literal. + #[inline] + pub fn get_bytes(&self, id: BytesId) -> &[u8] { + self.bytes[id.index()].value() + } + + /// Borrows a committed integer literal. + #[inline] + pub fn get_long_int(&self, id: LongIntId) -> &BigInt { + self.long_ints[id.index()].value() + } + + /// Borrows a function; later compilation cannot invalidate this reference. + #[inline] + pub fn get_function(&self, id: FunctionId) -> &Function { + &self.functions[id.index()] + } + + /// Looks up source by its filename-only ID, never by the displayed text. + pub(crate) fn eval_source(&self, filename: StringId) -> Option<&str> { + filename + .index() + .checked_sub(SOURCE_ID_BASE) + .and_then(|index| self.eval_sources.get(index)) + .map(AsRef::as_ref) + } + + /// Returns the same hash as an equal heap string. + #[inline] + pub fn str_hash(&self, id: StringId) -> HashValue { + if id.index() < RESERVED_STRS.len() { + RESERVED_STRING_HASHES.get_or_compute(id.index(), || hash_python_str(RESERVED_STRS[id.index()])) + } else { + self.strings[id.index() - INTERN_STRING_ID_OFFSET].hash() + } + } + + /// Returns the cached Python hash of a bytes literal. + #[inline] + pub fn bytes_hash(&self, id: BytesId) -> HashValue { + self.bytes[id.index()].hash() + } + + /// Returns the cached Python hash of an integer literal. + #[inline] + pub fn long_int_hash(&self, id: LongIntId) -> HashValue { + self.long_ints[id.index()].hash() + } + + /// Returns the captured implementation if this session has already compiled it. + pub(crate) fn frozen_function(&self, function: FrozenFunction) -> Option { + self.frozen_functions.borrow().get(&function).copied() + } + + /// Records an admitted implementation after its compilation overlay is committed. + pub(crate) fn set_frozen_function(&self, function: FrozenFunction, id: FunctionId) { + self.frozen_functions.borrow_mut().insert(function, id); + } + + /// Identifies implementation frames hidden from tracebacks and namespace introspection. + pub(crate) fn is_internal_function(&self, id: FunctionId) -> bool { + self.frozen_functions.borrow().values().any(|&function| function == id) + } + + /// Finds canonical text already interned, excluding snippet filename IDs. + pub fn get_string_id_by_name(&self, s: &str) -> Option { + get_string_id_by_name(&self.string_id_by_name.borrow(), &self.static_string_ids, s) + } +} diff --git a/crates/bashkit-monty/src/intern/compile.rs b/crates/bashkit-monty/src/intern/compile.rs new file mode 100644 index 000000000..a33e65977 --- /dev/null +++ b/crates/bashkit-monty/src/intern/compile.rs @@ -0,0 +1,262 @@ +//! Compiler access to session tables, with private overlays for recoverable compilation. + +use std::sync::Arc; + +use ahash::AHashMap; +use num_bigint::BigInt; + +use super::{BytesId, InternedString, Interns, LongIntId, SOURCE_ID_BASE, StaticStrings, StringId, next_string_id}; +use crate::{function::Function, hash::WithHash}; + +/// Compilation tables with final IDs assigned before execution. +/// Existing sessions use a private overlay so rejection retains no products. +/// Fresh programs may insert directly: the caller discards their tables on failure. +#[derive(Debug)] +pub(crate) struct CompileInterns<'i> { + base: &'i Interns, + pending: Option, +} + +/// An unpublished suffix of a session's tables, discarded unless compilation commits. +#[derive(Debug, Default)] +struct PendingInterns { + strings: Vec, + string_ids: AHashMap, + static_string_ids: AHashMap, + bytes: Vec>>, + long_ints: Vec>, + functions: Vec, + sources: Vec>, +} + +impl<'i> CompileInterns<'i> { + /// Reserves the next IDs without modifying the committed tables. + pub(crate) fn new(base: &'i Interns) -> Self { + assert!(!base.compiling.replace(true), "overlapping compilations"); + Self { + base, + pending: Some(PendingInterns::default()), + } + } + + /// Compiles directly into exclusively borrowed tables that the caller discards on failure. + /// Unlike `new`, this does not roll back; it is only for a fresh program, not a REPL feed. + pub(crate) fn direct(base: &'i mut Interns) -> Self { + assert!(!base.compiling.replace(true), "overlapping compilations"); + Self { base, pending: None } + } + + /// Publishes an overlay in provisional-ID order; direct compilation is already published. + pub(crate) fn commit(mut self) { + if let Some(pending) = &mut self.pending { + for entry in pending.strings.drain(..) { + self.base.strings.push(entry); + } + self.base + .string_id_by_name + .borrow_mut() + .extend(pending.string_ids.drain()); + self.base + .static_string_ids + .borrow_mut() + .extend(pending.static_string_ids.drain()); + for entry in pending.bytes.drain(..) { + self.base.bytes.push(entry); + } + for entry in pending.long_ints.drain(..) { + self.base.long_ints.push(entry); + } + for entry in pending.functions.drain(..) { + self.base.functions.push(Box::new(entry)); + } + for source in pending.sources.drain(..) { + self.base.eval_sources.push(source); + } + } + } + + /// Deduplicates against pending and committed text before assigning an ID. + pub(crate) fn intern(&mut self, text: &str) -> StringId { + if text.is_empty() { + StringId::EMPTY + } else if text.len() == 1 { + StringId::from_ascii(text.as_bytes()[0]) + } else if let Some(id) = self.pending.as_ref().and_then(|pending| pending.string_ids.get(text)) { + *id + } else if let Ok(tag) = text.parse::() { + self.intern_static(tag) + } else { + let existing = self.base.string_id_by_name.borrow().get(text).copied(); + if let Some(id) = existing { + id + } else { + self.push_string(InternedString::owned(text.to_owned())) + } + } + } + + /// Interns a compiler-generated name without parsing its known static tag again. + pub(crate) fn intern_static(&mut self, value: StaticStrings) -> StringId { + let text: &'static str = value.into(); + if text.is_empty() { + StringId::EMPTY + } else if text.len() == 1 { + StringId::from_ascii(text.as_bytes()[0]) + } else { + let existing = self.get_static_id(value); + if let Some(id) = existing { + id + } else { + self.push_string(InternedString::static_string(value)) + } + } + } + + /// Appends a bytes literal; these are not deduplicated. + pub(crate) fn intern_bytes(&mut self, bytes: &[u8]) -> BytesId { + let pending_len = self.pending.as_ref().map_or(0, |pending| pending.bytes.len()); + let id = BytesId( + (self.base.bytes.len() + pending_len) + .try_into() + .expect("BytesId overflow"), + ); + let entry = WithHash::for_bytes(bytes.to_vec()); + if let Some(pending) = &mut self.pending { + pending.bytes.push(entry); + } else { + self.base.bytes.push(entry); + } + id + } + + /// Appends an integer literal too large for an immediate value. + pub(crate) fn intern_long_int(&mut self, value: BigInt) -> LongIntId { + let pending_len = self.pending.as_ref().map_or(0, |pending| pending.long_ints.len()); + let id = LongIntId( + (self.base.long_ints.len() + pending_len) + .try_into() + .expect("LongIntId overflow"), + ); + let entry = WithHash::for_long_int(value); + if let Some(pending) = &mut self.pending { + pending.long_ints.push(entry); + } else { + self.base.long_ints.push(entry); + } + id + } + + /// Borrows either committed or pending text for preparation and diagnostics. + pub(crate) fn get_str(&self, id: StringId) -> &str { + let base = next_string_id(self.base.strings.len()).index(); + if let Some(pending) = &self.pending + && id.index() >= base + { + pending.strings[id.index() - base].as_str() + } else { + self.base.get_str(id) + } + } + + /// Borrows a committed or pending bytes literal for diagnostics. + pub(crate) fn get_bytes(&self, id: BytesId) -> &[u8] { + let base = self.base.bytes.len(); + match &self.pending { + Some(pending) if id.index() >= base => pending.bytes[id.index() - base].value(), + _ => self.base.get_bytes(id), + } + } + + /// Borrows a committed or pending big integer literal for diagnostics. + pub(crate) fn get_long_int(&self, id: LongIntId) -> &BigInt { + let base = self.base.long_ints.len(); + match &self.pending { + Some(pending) if id.index() >= base => pending.long_ints[id.index() - base].value(), + _ => self.base.get_long_int(id), + } + } + + /// Finds a name already present in either table. + pub(crate) fn get_string_id_by_name(&self, text: &str) -> Option { + if text.is_empty() { + Some(StringId::EMPTY) + } else if text.len() == 1 { + Some(StringId::from_ascii(text.as_bytes()[0])) + } else if let Some(id) = self.pending.as_ref().and_then(|pending| pending.string_ids.get(text)) { + Some(*id) + } else if let Ok(tag) = text.parse::() { + self.get_static_id(tag) + } else { + self.base.string_id_by_name.borrow().get(text).copied() + } + } + + /// Records source separately from canonical strings, preserving equal-string ID equality. + pub(crate) fn add_eval_source(&mut self, source: Arc) -> StringId { + let pending_len = self.pending.as_ref().map_or(0, |pending| pending.sources.len()); + let index = SOURCE_ID_BASE + self.base.eval_sources.len() + pending_len; + let id = StringId(index.try_into().expect("source ID overflow")); + if let Some(pending) = &mut self.pending { + pending.sources.push(source); + } else { + self.base.eval_sources.push(source); + } + id + } + + /// Appends a compiled function under its final session ID. + pub(crate) fn push_function(&mut self, function: Function) -> usize { + let index = self.functions_len(); + if let Some(pending) = &mut self.pending { + pending.functions.push(function); + } else { + self.base.functions.push(Box::new(function)); + } + index + } + + /// Returns the next function ID, including unpublished functions. + pub(crate) fn functions_len(&self) -> usize { + self.base.functions.len() + self.pending.as_ref().map_or(0, |pending| pending.functions.len()) + } + + /// Finds a known static tag without converting it back to text. + fn get_static_id(&self, value: StaticStrings) -> Option { + self.pending + .as_ref() + .and_then(|pending| pending.static_string_ids.get(&value).copied()) + .or_else(|| self.base.static_string_ids.borrow().get(&value).copied()) + } + + /// Assigns an ID to new text and records its reverse lookup in the same compilation mode. + fn push_string(&mut self, entry: InternedString) -> StringId { + if let Some(pending) = &mut self.pending { + let id = next_string_id(self.base.strings.len() + pending.strings.len()); + if let Some(tag) = entry.static_value() { + pending.static_string_ids.insert(tag, id); + } else { + pending.string_ids.insert(entry.as_str().to_owned(), id); + } + pending.strings.push(entry); + id + } else { + let id = next_string_id(self.base.strings.len()); + if let Some(tag) = entry.static_value() { + self.base.static_string_ids.borrow_mut().insert(tag, id); + } else { + self.base + .string_id_by_name + .borrow_mut() + .insert(entry.as_str().to_owned(), id); + } + self.base.strings.push(entry); + id + } + } +} + +impl Drop for CompileInterns<'_> { + fn drop(&mut self) { + self.base.compiling.set(false); + } +} diff --git a/crates/bashkit-monty/src/intern/storage.rs b/crates/bashkit-monty/src/intern/storage.rs new file mode 100644 index 000000000..2dab4d47b --- /dev/null +++ b/crates/bashkit-monty/src/intern/storage.rs @@ -0,0 +1,79 @@ +//! Stable, append-only storage for committed compiler tables. + +use std::ops::Index; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use crate::heap::{HeapId, StableHeap}; + +/// Keeps committed entries borrowed across subsequent compilation and insertion. +/// Removal is deliberately unavailable: rejected compilations own separate vectors. +#[derive(Debug)] +pub(super) struct Entries(StableHeap); + +impl Entries { + /// Reserves slots without constructing entries. + pub(super) fn with_capacity(capacity: usize) -> Self { + Self(StableHeap::with_capacity(capacity)) + } + + /// Returns the next entry's dense index. + pub(super) fn len(&self) -> usize { + self.0.len() + } + + /// Appends an entry without invalidating references to earlier entries. + pub(super) fn push(&self, entry: T) { + self.0.allocate(entry); + } + + /// Looks up an assigned index. + pub(super) fn get(&self, index: usize) -> Option<&T> { + (index < self.len()).then(|| self.0.get(HeapId::from_index(index))) + } + + /// Visits committed entries in ID order. + pub(super) fn iter(&self) -> impl Iterator { + (0..self.len()).map(|index| &self[index]) + } +} + +impl Default for Entries { + fn default() -> Self { + Self::with_capacity(0) + } +} + +impl Index for Entries { + type Output = T; + fn index(&self, index: usize) -> &T { + self.get(index).expect("invalid intern slot") + } +} + +impl Clone for Entries { + fn clone(&self) -> Self { + let entries = Self::with_capacity(self.len()); + for entry in self.iter() { + entries.push(entry.clone()); + } + entries + } +} + +impl Serialize for Entries { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq(self.iter()) + } +} + +impl<'de, T: Deserialize<'de>> Deserialize<'de> for Entries { + fn deserialize>(deserializer: D) -> Result { + let values = Vec::::deserialize(deserializer)?; + let entries = Self::with_capacity(values.len()); + for value in values { + entries.push(value); + } + Ok(entries) + } +} diff --git a/crates/bashkit-monty/src/lib.rs b/crates/bashkit-monty/src/lib.rs new file mode 100644 index 000000000..e0f2c4f20 --- /dev/null +++ b/crates/bashkit-monty/src/lib.rs @@ -0,0 +1,71 @@ +#![doc = include_str!("../README.md")] +// bashkit fork: upstream source is kept unchanged, so its lints are not +// bashkit's. Source attributes override `cargo clippy -- -D warnings`. +#![allow(warnings, clippy::all, clippy::pedantic)] +// these files first because they include macros for the rest of the crate to use +mod boundary_uuid; +mod heap; +mod heap_traits; + +mod args; +mod asyncio; +mod builtins; +mod bytecode; +mod codecs; +mod dump_format; +mod dump_upgrade; +mod exception_private; +mod expressions; +mod frozen; +mod fstring; +mod function; +mod hash; +mod heap_data; +mod identity; +mod intern; +mod modules; +mod name_map; +mod namespace; +mod object_bridge; +mod os_dispatch; +mod parse; +mod percent_format; +mod predicate; +mod prepare; +mod py_value; +mod repl; +mod resource_checks; +mod run; +mod run_progress; +mod sorting; +mod source_map; +mod source_nesting; +mod str_format; +mod string_builder; +mod stringize; +mod types; +mod value; +mod virtual_path; + +#[cfg(feature = "ref-count-return")] +pub use crate::run::RefCountOutput; +/// The import names of every module the sandbox provides itself; see `SANDBOX_MODULE_NAMES` in `monty_types`. +#[must_use] +pub fn builtin_module_names() -> Vec<&'static str> { + modules::StandardLib::names().collect() +} + +pub use crate::{ + dump_format::{ + DUMP_VERSION, Dump, DumpDecodeError, DumpEncodeError, DumpError, MIN_SUPPORTED_DUMP_VERSION, Session, + SessionRef, dump, + }, + parse::type_check_nesting_exception, + repl::{ + CheckedSource, MontyRepl, ReplContinuationMode, ReplFunctionCall, ReplNameLookup, ReplOsCall, ReplProgress, + ReplResolveFutures, ReplStartError, detect_repl_continuation_mode, + }, + run::MontyRun, + run_progress::{FunctionCall, NameLookup, OsCall, ResolveFutures, RunProgress}, + source_nesting::source_within_nesting_bound, +}; diff --git a/crates/bashkit-monty/src/modules/CLAUDE.md b/crates/bashkit-monty/src/modules/CLAUDE.md new file mode 100644 index 000000000..cd976d848 --- /dev/null +++ b/crates/bashkit-monty/src/modules/CLAUDE.md @@ -0,0 +1,132 @@ +# Adding / extending stdlib modules + +Guidance for the Python stdlib modules implemented in this directory +(`re`, `json`, `math`, `datetime`, `unicodedata`, …). The overriding goal is +**CPython parity**: signatures, error messages, and error *ordering* must +match CPython 3.14 byte-for-byte. Verify every message against CPython with +the `/python-playground` skill before pinning it in a test. + +## Always use `#[derive(FromArgs)]` for function parameters + +Any function beyond the trivial 0/1/2-positional shapes (covered by +`ArgValues::check_zero_args` / `get_one_arg` / `get_two_args` / +`get_zero_one_arg` / `into_pos_only`) MUST define its parameters with a +`#[derive(FromArgs)]` struct. Never hand-roll `args.into_parts()` loops — +they leak refcounts and diverge from CPython's wording. The derive emits a +static param spec driven by the runtime binder +(`crate::args::bind_native`), which handles dispatch, arity errors, kwarg +matching, duplicate/conflict detection, and refcount cleanup mechanically. + +Full attribute reference: `crates/monty-macros/README.md` (including the +CPython-family table and the `at_most_total` litmus test). + +### 1. Pick the `style` by how CPython implements the function + +| CPython implementation | `style` | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | +| pure-Python `def` (the `re` functions, `json.dumps`) | `style = def` | +| Argument Clinic, positional-only (`sorted`, `math.pow`) | default — omit `style` | +| Argument Clinic with keyword-capable params (`accumulate`, `os.stat`) | `style = c_named` — it shares `_PyArg_UnpackKeywords` wording | +| `PyArg_ParseTupleAndKeywords`, anonymous `function` errors | `style = c` | +| same, with the name embedded (`timezone() missing …`) | `style = c_named` | +| `PyArg_UnpackTuple` (positional-only, `min..max` arity, kwargs rejected wholesale with `takes no keyword arguments`) | `style = unpack` | +| `tp_vectorcall` fast path in front of a clinic parser (`int`, `str`: kwarg-free overflow says `int expected at most 2 arguments, got 3`, with kwargs `int() takes at most 2 arguments (3 given)`) | default style + `at_most_total, vectorcall` | + +The style controls wording *and* ordering (e.g. C families report leftover +kwargs last; clinic/def bind fully before any conversion). When unsure, probe +CPython: call the function with a bad type + a bogus kwarg, too many args, +etc., and match the observed messages. + +### 2. Typical shapes (real examples from this directory) + +A pure-Python `def` — fields stay raw `Value` because CPython `def` binding +never type-checks; coerce in the body (`re.rs`): + +```rust +#[derive(FromArgs)] +#[from_args(name = "search", style = def)] +struct ReSearchArgs { + #[from_args(static_string = "PatternAttr")] + pattern: Value, + #[from_args(static_string = "StringAttr")] + string: Value, + #[from_args(default = Value::Int(0))] + flags: Value, +} +``` + +A clinic function with keyword-capable positionals and a keyword-only tail +(`itertools.rs`) — `c_named` per the table, so overflow reports `accumulate() takes at most 2 positional arguments (3 given)`: + +```rust +#[derive(FromArgs)] +#[from_args(name = "accumulate", style = c_named)] +struct AccumulateArgs { + #[from_args(static_string = "IterableArg")] + iterable: Value, + #[from_args(default = Value::None)] + func: Value, + #[from_args(kw_only, default = Value::None)] + initial: Value, +} +``` + +A positional-only C function with typed extraction (`unicodedata.rs`) — +`StrArg` borrows the text zero-copy. Note the form *name* is validated in the +body (`NormForm::parse`), not during extraction: CPython type-checks every +argument before the body rejects a bad value, so value checks must not run +inside `FromValue`: + +```rust +#[derive(FromArgs)] +#[from_args(name = "normalize", style = unpack, bad_arg)] +struct NormalizeArgs { + #[from_args(pos_only)] + form: StrArg, + #[from_args(pos_only)] + unistr: StrArg, +} +``` + +Calling and consuming — sketch; see `unicodedata.rs` for the real body (note +`defer_drop!` for fields that hold heap refs): + +```rust +fn call_normalize(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let NormalizeArgs { form, unistr } = NormalizeArgs::from_args(args, vm)?; + defer_drop!(unistr, vm); + let normalized = form.apply(unistr.as_str(vm)); // sketch — do the work here + // ... allocate and return the result; the guard releases `unistr` +} +``` + +### 3. Field rules + +- Declaration order = Python signature order: + `[pos_only…] [pos_or_keyword…] [varargs] [kw_only…] [varkwargs]`, required + fields before defaulted ones in the positional region. +- **Typed fields** (`i64`, `i32`, `bool`, `StrArg`, `Option`, custom + `FromValue` impls) are only for functions implemented in C in CPython — + pair with `bad_arg` / `bad_arg_named` when CPython uses + `_PyArg_BadArgument` wording (`f() argument 1 must be str, not int`). +- **`style = def` fields must be raw `Value`** (coerce in the body so the + error message matches what CPython's function body raises). +- Prefer `StrArg` over `String` for str params the function only reads — it + validates without copying and lends `&str` via `.as_str(vm)`. +- Field names that aren't single ASCII chars need a `StaticStrings` variant + (in `crate::intern`) for kwarg matching — add one, or point + `static_string = "ExistingVariant"` at an existing one. +- `Value` / `StrArg` / `Option` fields hold heap references: bind + them with `defer_drop!` in the body, or otherwise guarantee + `drop_with` on every path. +- `varargs` fields must be `Vec`; convert elements in the body. + +### 4. Tests and docs + +- Add behaviour tests to `crates/monty/test_cases/` (dual-run against + CPython — asserts must pass on both engines; exact `==` messages, never + `in`). Signature-error orderings belong in `args__macro_errors.py`. +- Document every remaining CPython divergence in `./limitations/.md` + — including "obvious" ones. +- Run `make test-cases`, `make format-rs`, `make lint-rs` (and + `make lint-py` for test changes) before finishing. diff --git a/crates/bashkit-monty/src/modules/asyncio.rs b/crates/bashkit-monty/src/modules/asyncio.rs new file mode 100644 index 000000000..a4d33c142 --- /dev/null +++ b/crates/bashkit-monty/src/modules/asyncio.rs @@ -0,0 +1,211 @@ +//! Implementation of the `asyncio` module. +//! +//! Provides a minimal implementation of Python's `asyncio` module with: +//! - `run(coro)`: Runs a coroutine to completion, equivalent to `await coro` +//! - `gather(*awaitables)`: Collects coroutines for concurrent execution +//! - `sleep(delay, result=None)`: An awaitable governed by the session's `SleepMode` +//! +//! Other asyncio functions (`create_task`, `wait`, etc.) are not implemented. +//! The host acts as the event loop - Monty yields control when tasks are blocked. + +use monty_types::{OsFunctionCall, sleep_duration_saturating}; +use num_traits::ToPrimitive; + +use crate::{ + args::{ArgValues, FromArgs}, + asyncio::GatherFuture, + bytecode::{CallResult, VM}, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{Heap, HeapData, HeapId}, + heap_traits::DropGuard, + intern::StaticStrings, + modules::{ + ModuleFunctions, + time::{HostSleep, host_sleep}, + }, + os_dispatch::PostConversionEffect, + types::Module, + value::Value, +}; + +/// Async Functions. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "lowercase")] +pub(crate) enum AsyncioFunctions { + Gather, + Run, + Sleep, +} + +/// Creates the `asyncio` module and allocates it on the heap. +/// +/// The module contains only the `run`, `gather` and `sleep` functions. Other asyncio +/// functions are not implemented as they would require additional VM/scheduler features. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Asyncio, vm.interns); + + module.set_attr( + StaticStrings::Gather, + Value::ModuleFunction(ModuleFunctions::Asyncio(AsyncioFunctions::Gather)), + vm, + ); + module.set_attr( + StaticStrings::Run, + Value::ModuleFunction(ModuleFunctions::Asyncio(AsyncioFunctions::Run)), + vm, + ); + module.set_attr( + StaticStrings::Sleep, + Value::ModuleFunction(ModuleFunctions::Asyncio(AsyncioFunctions::Sleep)), + vm, + ); + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} +pub(super) fn call(vm: &mut VM<'_>, functions: AsyncioFunctions, args: ArgValues) -> RunResult { + match functions { + AsyncioFunctions::Gather => gather(vm, args).map(CallResult::Value), + AsyncioFunctions::Run => run(vm.heap, args), + AsyncioFunctions::Sleep => sleep(vm, args), + } +} + +/// Returns an awaitable producing `result`, retained by [`PostConversionEffect::SleepResult`]. +/// Unlike CPython, waiting starts at the call. The host answers with a future +/// or inline; [`host_sleep`] determines the destination and delay. +/// `Zero` and zero-length system sleeps settle immediately. See `limitations/asyncio.md`. +fn sleep(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let SleepArgs { delay, result } = SleepArgs::from_args(args, vm)?; + // `result` outlives `delay`: it moves into the awaitable once the delay is valid. + let mut result_guard = DropGuard::new(result, vm); + let delay = { + let (_, vm) = result_guard.as_parts_mut(); + defer_drop!(delay, vm); + let seconds = delay_seconds(delay, vm)?; + // NaN is the one delay CPython refuses; the rest clamp. + let delay = sleep_duration_saturating(seconds) + .map_err(|_| ExcType::value_error("Invalid delay: NaN (not a number)"))?; + host_sleep(vm, delay) + }; + let (result, vm) = result_guard.into_parts(); + let call = match delay { + Some(HostSleep::CallHost(delay)) => OsFunctionCall::AsyncSleep(delay), + // Avoid a host round trip for a zero-length system sleep. + Some(HostSleep::System(delay)) if !delay.is_zero() => OsFunctionCall::AsyncSystemSleep(delay), + _ => return Ok(CallResult::Value(vm.settled_awaitable(result))), + }; + Ok(CallResult::OsCallWithEffect { + call, + effect: PostConversionEffect::SleepResult { result }.into(), + }) +} + +/// `asyncio.sleep(delay, result=None)` — a pure-Python `def` in CPython, so +/// both parameters bind by keyword and neither is type-checked while binding. +#[derive(FromArgs)] +#[from_args(name = "sleep", style = def)] +struct SleepArgs { + #[from_args(static_string = "Delay")] + delay: Value, + #[from_args(static_string = "ResultArg", default = Value::None)] + result: Value, +} + +/// Reads `delay` as float seconds. +/// +/// CPython never converts it: it compares `delay <= 0` and hands whatever is +/// left to the loop, so only real numbers work — an `__index__`-able class is +/// rejected here although `time.sleep()` accepts it — and a non-number fails as +/// an unsupported comparison rather than as a bad argument. +fn delay_seconds(delay: &Value, vm: &VM<'_>) -> RunResult { + match delay { + Value::Float(f) => Ok(*f), + Value::Int(n) => Ok(*n as f64), + Value::Bool(b) => Ok(f64::from(*b)), + _ => match delay.as_long_int(vm) { + Some(n) => Ok(n.to_f64().unwrap_or(f64::INFINITY)), + None => Err(ExcType::type_error_ordering("<=", &delay.py_type_name(vm), "int")), + }, + } +} + +/// Implementation of `asyncio.run(coro)`. +/// +/// Runs a single coroutine to completion, equivalent to `await coro` at the top level. +/// Accepts exactly one positional argument (the coroutine) and no keyword arguments. +/// +/// Returns `CallResult::AwaitValue` so the VM executes `exec_get_awaitable` on +/// the value, which handles validation that it's actually a coroutine/awaitable. +fn run(heap: &mut Heap, args: ArgValues) -> RunResult { + let coroutine = args.get_one_arg("asyncio.run", heap)?; + Ok(CallResult::AwaitValue(coroutine)) +} + +/// Implementation of `asyncio.gather(*awaitables)`. +/// +/// Collects coroutines and external futures for concurrent execution. Does NOT +/// spawn tasks immediately - just validates and stores the references. Tasks are +/// spawned when the returned `GatherFuture` is awaited (in the `Await` opcode handler). +/// +/// # Behavior when awaited +/// +/// 1. Each coroutine is spawned as a separate Task +/// 2. External futures are tracked for resolution by the host +/// 3. The current task blocks until all items complete +/// 4. Results are collected in order and returned as a list +/// 5. On any task failure, sibling tasks are cancelled and the exception propagates +/// +/// # Arguments +/// * `heap` - The heap for allocating the GatherFuture +/// * `args` - Variadic awaitable arguments (coroutines or external futures) +/// +/// # Errors +/// Returns `TypeError` if any argument is not awaitable. +pub(crate) fn gather(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + // TODO: support keyword arguments (e.g. return_exceptions); for now any + // kwarg is rejected up front by the macro's `kwargs_not_supported_yet` + // flag with a `NotImplementedError: gather() does not yet support keyword + // arguments` (CPython would have given a TypeError naming the bad kwarg). + let GatherArgs { awaitables } = GatherArgs::from_args(args, vm)?; + defer_drop_mut!(awaitables, vm); + + // Validate every argument before transferring any references to the gather, + // so an invalid later argument needs no raw-HeapId rollback. + for arg in awaitables.iter() { + if !matches!( + arg, + Value::Ref(id) + if matches!( + vm.heap.get(*id), + HeapData::Coroutine(_) | HeapData::ExternalFuture(_) | HeapData::GatherFuture(_) + ) + ) { + return Err(ExcType::type_error( + "An asyncio.Future, a coroutine or an awaitable is required", + )); + } + } + + let items = awaitables + .drain(..) + .map(|arg| arg.into_ref_id().expect("validated gather awaitable is heap-backed")) + .collect(); + let gather_future = GatherFuture::new(items); + let id = vm.heap.allocate(HeapData::GatherFuture(Box::new(gather_future))); + Ok(Value::Ref(id)) +} + +/// `asyncio.gather(*awaitables)` — variadic positional, no kwargs accepted. +/// +/// `kwargs_not_supported_yet` rejects any kwarg with the macro's +/// "not yet implemented" `NotImplementedError`, replacing the previous +/// `TypeError: gather() takes no keyword arguments` from `into_pos_only`. +/// When CPython's `return_exceptions=False` is wired up this becomes a +/// regular `kw_only` slot and the flag goes away. +#[derive(FromArgs)] +#[from_args(name = "gather", kwargs_not_supported_yet)] +struct GatherArgs { + #[from_args(varargs)] + awaitables: Vec, +} diff --git a/crates/bashkit-monty/src/modules/base64.rs b/crates/bashkit-monty/src/modules/base64.rs new file mode 100644 index 000000000..748385bbb --- /dev/null +++ b/crates/bashkit-monty/src/modules/base64.rs @@ -0,0 +1,1355 @@ +//! Implementation of Python's `base64` module. +//! +//! Covers the base64/base32/base16/base85 codecs, the ascii85 pair and the +//! MIME helpers `encodebytes`/`decodebytes`; the file-object `encode`/`decode` +//! pair is not — see `limitations/base64.md`. +//! +//! CPython's `base64` is pure Python delegating to `binascii`, so every +//! function here uses `#[from_args(style = def)]` and coerces in the body, +//! reproducing both CPython's signature errors and the order its bodies reject +//! bad values in. Decode failures raise [`ExcType::BinasciiError`] +//! (`binascii.Error`, a `ValueError` subclass) with `binascii`'s wording. +//! +//! Encoders take bytes only; decoders also take ASCII `str` (CPython's +//! `_bytes_from_decode_data`). + +use std::{borrow::Cow, cmp::Ordering}; + +use monty_types::ResourceTracker; + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{Heap, HeapData, HeapId}, + intern::StaticStrings, + modules::ModuleFunctions, + resource_checks::check_estimated_size, + types::{CmpOrder, Module, PyTrait, bytes::bytes_repr}, + value::Value, +}; + +/// Standard base64 alphabet (RFC 4648 §4). +const B64_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +/// Standard base32 alphabet (RFC 4648 §6). +const B32_ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; +/// Base85 alphabet used by `b85encode` (RFC 1924 order, as CPython spells it). +const B85_ALPHABET: &[u8; 85] = + b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"; +/// Z85 alphabet (ZeroMQ RFC 32), the same scheme over a shell-safe character set. +const Z85_ALPHABET: &[u8; 85] = + b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#"; + +/// Lowest Ascii85 digit: value `v` encodes as `A85_FIRST_DIGIT + v`, so the +/// alphabet is the 85 characters `!` through `u`. +const A85_FIRST_DIGIT: u8 = b'!'; +/// Highest Ascii85 digit, and the character CPython pads a trailing partial +/// group with. +const A85_LAST_DIGIT: u8 = b'u'; +/// Opening marker of the Adobe framing, optional on decode. +const A85_ADOBE_START: &[u8; 2] = b"<~"; +/// Closing marker of the Adobe framing, required on decode when `adobe` is set. +const A85_ADOBE_END: &[u8; 2] = b"~>"; + +/// Extended-hex base32 alphabet (RFC 4648 §7), used by `b32hexencode`. +const B32HEX_ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHIJKLMNOPQRSTUV"; + +/// Bytes per `encodebytes` output line: 57 input bytes encode to 76 base64 +/// characters, CPython's `MAXBINSIZE`. +const MAX_BIN_SIZE: u8 = 57; +/// Characters per `encodebytes` output line, CPython's `MAXLINESIZE`. Both are +/// exposed as module attributes, as CPython does. +const MAX_LINE_SIZE: u8 = 76; + +/// `base64` module functions, one variant per Python-visible function. +/// +/// Serialized into dumps by variant name, so renaming one needs `#[serde(alias)]`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +pub(crate) enum Base64Functions { + #[strum(serialize = "b64encode")] + B64Encode, + #[strum(serialize = "b64decode")] + B64Decode, + #[strum(serialize = "standard_b64encode")] + StandardB64Encode, + #[strum(serialize = "standard_b64decode")] + StandardB64Decode, + #[strum(serialize = "urlsafe_b64encode")] + UrlsafeB64Encode, + #[strum(serialize = "urlsafe_b64decode")] + UrlsafeB64Decode, + #[strum(serialize = "b32encode")] + B32Encode, + #[strum(serialize = "b32decode")] + B32Decode, + #[strum(serialize = "b32hexencode")] + B32HexEncode, + #[strum(serialize = "b32hexdecode")] + B32HexDecode, + #[strum(serialize = "b16encode")] + B16Encode, + #[strum(serialize = "b16decode")] + B16Decode, + #[strum(serialize = "encodebytes")] + Encodebytes, + #[strum(serialize = "decodebytes")] + Decodebytes, + #[strum(serialize = "b85encode")] + B85Encode, + #[strum(serialize = "b85decode")] + B85Decode, + #[strum(serialize = "z85encode")] + Z85Encode, + #[strum(serialize = "z85decode")] + Z85Decode, + #[strum(serialize = "a85encode")] + A85Encode, + #[strum(serialize = "a85decode")] + A85Decode, +} + +/// Static mapping of attribute names to functions for module creation. +const BASE64_FUNCTIONS: &[(StaticStrings, Base64Functions)] = &[ + (StaticStrings::B64Encode, Base64Functions::B64Encode), + (StaticStrings::B64Decode, Base64Functions::B64Decode), + (StaticStrings::StandardB64Encode, Base64Functions::StandardB64Encode), + (StaticStrings::StandardB64Decode, Base64Functions::StandardB64Decode), + (StaticStrings::UrlsafeB64Encode, Base64Functions::UrlsafeB64Encode), + (StaticStrings::UrlsafeB64Decode, Base64Functions::UrlsafeB64Decode), + (StaticStrings::B32Encode, Base64Functions::B32Encode), + (StaticStrings::B32Decode, Base64Functions::B32Decode), + (StaticStrings::B32HexEncode, Base64Functions::B32HexEncode), + (StaticStrings::B32HexDecode, Base64Functions::B32HexDecode), + (StaticStrings::B16Encode, Base64Functions::B16Encode), + (StaticStrings::B16Decode, Base64Functions::B16Decode), + (StaticStrings::Encodebytes, Base64Functions::Encodebytes), + (StaticStrings::Decodebytes, Base64Functions::Decodebytes), + (StaticStrings::B85Encode, Base64Functions::B85Encode), + (StaticStrings::B85Decode, Base64Functions::B85Decode), + (StaticStrings::Z85Encode, Base64Functions::Z85Encode), + (StaticStrings::Z85Decode, Base64Functions::Z85Decode), + (StaticStrings::A85Encode, Base64Functions::A85Encode), + (StaticStrings::A85Decode, Base64Functions::A85Decode), +]; + +/// Creates the `base64` module on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Base64, vm.interns); + + for (name, func) in BASE64_FUNCTIONS { + module.set_attr(*name, Value::ModuleFunction(ModuleFunctions::Base64(*func)), vm); + } + + module.set_attr(StaticStrings::MaxBinSize, Value::Int(i64::from(MAX_BIN_SIZE)), vm); + module.set_attr(StaticStrings::MaxLineSize, Value::Int(i64::from(MAX_LINE_SIZE)), vm); + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a call to a `base64` module function. +/// +/// All functions are pure computations and return `Value` directly. +pub(super) fn call(vm: &mut VM<'_>, function: Base64Functions, args: ArgValues) -> RunResult { + match function { + Base64Functions::B64Encode => call_b64encode(vm, args), + Base64Functions::B64Decode => call_b64decode(vm, args), + Base64Functions::StandardB64Encode => call_standard_b64encode(vm, args), + Base64Functions::StandardB64Decode => call_standard_b64decode(vm, args), + Base64Functions::UrlsafeB64Encode => call_urlsafe_b64encode(vm, args), + Base64Functions::UrlsafeB64Decode => call_urlsafe_b64decode(vm, args), + Base64Functions::B32Encode => call_b32encode(vm, args), + Base64Functions::B32Decode => call_b32decode(vm, args), + Base64Functions::B32HexEncode => call_b32hexencode(vm, args), + Base64Functions::B32HexDecode => call_b32hexdecode(vm, args), + Base64Functions::B16Encode => call_b16encode(vm, args), + Base64Functions::B16Decode => call_b16decode(vm, args), + Base64Functions::Encodebytes => call_encodebytes(vm, args), + Base64Functions::Decodebytes => call_decodebytes(vm, args), + Base64Functions::B85Encode => call_b85encode(vm, args), + Base64Functions::B85Decode => call_b85decode(vm, args), + Base64Functions::Z85Encode => call_z85encode(vm, args), + Base64Functions::Z85Decode => call_z85decode(vm, args), + Base64Functions::A85Encode => call_a85encode(vm, args), + Base64Functions::A85Decode => call_a85decode(vm, args), + } +} + +/// `base64.b64encode(s, altchars=None)` — standard base64 with optional +/// substitutes for the `+` and `/` characters. +fn call_b64encode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B64EncodeArgs { s, altchars } = B64EncodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + defer_drop!(altchars, vm); + + let mut encoded = b64_encode(encode_input(s, vm)?.as_ref(), &vm.heap.tracker)?; + if !matches!(altchars, Value::None) { + // CPython asserts on the raw object's length before `bytes.maketrans` + // type-checks it, so a 1-byte `str` is an AssertionError, not a TypeError. + assert_len(altchars, 2, vm)?; + let alt = encode_input(altchars, vm)?.into_owned(); + translate(&mut encoded, b"+/", &alt); + } + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `base64.b64decode(s, altchars=None, validate=False)`. +/// +/// With `validate=False` (the default) anything outside the alphabet is +/// discarded before the quads are assembled; `validate=True` rejects it. +fn call_b64decode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B64DecodeArgs { s, altchars, validate } = B64DecodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + defer_drop!(altchars, vm); + defer_drop!(validate, vm); + + let mut data = decode_input(s, vm)?.into_owned(); + if !matches!(altchars, Value::None) { + // Unlike the encode path, CPython coerces before asserting the length. + let alt = decode_input(altchars, vm)?.into_owned(); + assert_len_bytes(&alt, 2)?; + translate(&mut data, &alt, b"+/"); + } + let strict = validate.py_bool(vm)?; + let decoded = b64_decode(&data, strict)?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `base64.standard_b64encode(s)` — `b64encode` without `altchars`. +fn call_standard_b64encode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let StandardB64EncodeArgs { s } = StandardB64EncodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + let encoded = b64_encode(encode_input(s, vm)?.as_ref(), &vm.heap.tracker)?; + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `base64.standard_b64decode(s)` — `b64decode` without `altchars`. +fn call_standard_b64decode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let StandardB64DecodeArgs { s } = StandardB64DecodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + let decoded = b64_decode(decode_input(s, vm)?.as_ref(), false)?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `base64.urlsafe_b64encode(s)` — standard base64 with `-` and `_` in place +/// of `+` and `/`. +fn call_urlsafe_b64encode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let UrlsafeB64EncodeArgs { s } = UrlsafeB64EncodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + let mut encoded = b64_encode(encode_input(s, vm)?.as_ref(), &vm.heap.tracker)?; + translate(&mut encoded, b"+/", b"-_"); + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `base64.urlsafe_b64decode(s)` — the inverse of [`call_urlsafe_b64encode`]. +fn call_urlsafe_b64decode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let UrlsafeB64DecodeArgs { s } = UrlsafeB64DecodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + let mut data = decode_input(s, vm)?.into_owned(); + translate(&mut data, b"-_", b"+/"); + let decoded = b64_decode(&data, false)?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `base64.b32encode(s)` — RFC 4648 base32. +fn call_b32encode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B32EncodeArgs { s } = B32EncodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + let encoded = b32_encode(memoryview_input(s, vm)?.as_ref(), B32_ALPHABET, &vm.heap.tracker)?; + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `base64.b32decode(s, casefold=False, map01=None)`. +/// +/// `map01` names the letter that the digit `1` maps to; `0` always maps to +/// `O`. Both translations happen before the optional case folding. +fn call_b32decode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B32DecodeArgs { s, casefold, map01 } = B32DecodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + defer_drop!(casefold, vm); + defer_drop!(map01, vm); + + let mut data = decode_input(s, vm)?.into_owned(); + if !data.len().is_multiple_of(8) { + return Err(incorrect_padding()); + } + if !matches!(map01, Value::None) { + let map = decode_input(map01, vm)?.into_owned(); + assert_len_bytes(&map, 1)?; + translate(&mut data, b"01", &[b'O', map[0]]); + } + let decoded = b32_decode(&data, B32_ALPHABET, casefold.py_bool(vm)?)?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `base64.b32hexencode(s)` — base32 over the extended-hex alphabet. +fn call_b32hexencode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B32HexEncodeArgs { s } = B32HexEncodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + let encoded = b32_encode(memoryview_input(s, vm)?.as_ref(), B32HEX_ALPHABET, &vm.heap.tracker)?; + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `base64.b32hexdecode(s, casefold=False)` — no `map01`, since `0` and `1` +/// are themselves digits in the extended-hex alphabet. +fn call_b32hexdecode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B32HexDecodeArgs { s, casefold } = B32HexDecodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + defer_drop!(casefold, vm); + + let data = decode_input(s, vm)?.into_owned(); + if !data.len().is_multiple_of(8) { + return Err(incorrect_padding()); + } + let decoded = b32_decode(&data, B32HEX_ALPHABET, casefold.py_bool(vm)?)?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `base64.b16encode(s)` — uppercase hex. +fn call_b16encode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B16EncodeArgs { s } = B16EncodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + let encoded = b16_encode(encode_input(s, vm)?.as_ref(), &vm.heap.tracker)?; + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `base64.b16decode(s, casefold=False)` — rejects lowercase hex unless +/// `casefold` is set, as CPython does. +fn call_b16decode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B16DecodeArgs { s, casefold } = B16DecodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + defer_drop!(casefold, vm); + + let data = decode_input(s, vm)?.into_owned(); + let decoded = b16_decode(&data, casefold.py_bool(vm)?)?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `base64.encodebytes(s)` — base64 split into 76-character lines, each +/// terminated by a newline (the MIME convention). +fn call_encodebytes(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let EncodebytesArgs { s } = EncodebytesArgs::from_args(args, vm)?; + defer_drop!(s, vm); + + let data = input_type_check(s, vm)?; + // Each `MAX_BIN_SIZE` chunk becomes `MAX_LINE_SIZE` characters plus a + // newline. The per-chunk encode only ever sees 57 bytes, so the whole + // output has to be preflighted here. + let capacity = data + .len() + .div_ceil(usize::from(MAX_BIN_SIZE)) + .saturating_mul(usize::from(MAX_LINE_SIZE) + 1); + check_estimated_size(capacity, &vm.heap.tracker)?; + let mut encoded = Vec::with_capacity(capacity); + for chunk in data.chunks(usize::from(MAX_BIN_SIZE)) { + encoded.extend_from_slice(&b64_encode(chunk, &vm.heap.tracker)?); + encoded.push(b'\n'); + } + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `base64.decodebytes(s)` — the inverse of [`call_encodebytes`]. Unlike +/// `b64decode` it takes bytes only, never a `str`. +fn call_decodebytes(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let DecodebytesArgs { s } = DecodebytesArgs::from_args(args, vm)?; + defer_drop!(s, vm); + let decoded = b64_decode(input_type_check(s, vm)?.as_ref(), false)?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `base64.b85encode(b, pad=False)` — RFC 1924 base85. +/// +/// `pad` keeps the characters that encode the zero-padding of a final short +/// group, so the output length is always a multiple of five. +fn call_b85encode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B85EncodeArgs { b, pad } = B85EncodeArgs::from_args(args, vm)?; + defer_drop!(b, vm); + defer_drop!(pad, vm); + + let pad = pad.py_bool(vm)?; + let encoded = b85_encode(memoryview_input(b, vm)?.as_ref(), B85_ALPHABET, pad, &vm.heap.tracker)?; + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `base64.b85decode(b)` — the inverse of [`call_b85encode`]. +fn call_b85decode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B85DecodeArgs { b } = B85DecodeArgs::from_args(args, vm)?; + defer_drop!(b, vm); + + let decoded = b85_decode(decode_input(b, vm)?.as_ref(), B85_ALPHABET, "base85")?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `base64.z85encode(s)` — base85 over the shell-safe Z85 alphabet. +fn call_z85encode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let Z85EncodeArgs { s } = Z85EncodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + + let encoded = b85_encode(memoryview_input(s, vm)?.as_ref(), Z85_ALPHABET, false, &vm.heap.tracker)?; + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `base64.z85decode(s)` — the inverse of [`call_z85encode`]. +fn call_z85decode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let Z85DecodeArgs { s } = Z85DecodeArgs::from_args(args, vm)?; + defer_drop!(s, vm); + + let decoded = b85_decode(decode_input(s, vm)?.as_ref(), Z85_ALPHABET, "z85")?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `base64.a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)` +/// — Ascii85, the btoa/PostScript dialect of base85. +/// +/// Zero folding to `z` is always on and `foldspaces` adds `y` for four spaces; +/// `adobe` frames the result in `<~`/`~>`, and `wrapcol` breaks it into lines. +fn call_a85encode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let A85EncodeArgs { + b, + foldspaces, + wrapcol, + pad, + adobe, + } = A85EncodeArgs::from_args(args, vm)?; + defer_drop!(b, vm); + defer_drop!(foldspaces, vm); + defer_drop!(wrapcol, vm); + defer_drop!(pad, vm); + defer_drop!(adobe, vm); + + // CPython coerces the input before any flag and reaches `pad` only when the + // length needs padding. Which flag raises first is unobservable while + // `__bool__` goes undispatched (`limitations/classes.md`), but this order + // holds once it lands. Owned as `tobytes()` is: a dispatched `__bool__` + // re-enters the interpreter and could mutate a `bytearray`. + let data = memoryview_input(b, vm)?.into_owned(); + let fold = foldspaces.py_bool(vm)?; + let keep_padding = data.len() % 4 != 0 && pad.py_bool(vm)?; + let adobe = adobe.py_bool(vm)?; + let framing = if adobe { + A85_ADOBE_START.len() + A85_ADOBE_END.len() + } else { + 0 + }; + let mut encoded = a85_encode(&data, keep_padding, fold, framing, &vm.heap.tracker)?; + + if adobe { + encoded.splice(0..0, *A85_ADOBE_START); + } + // CPython only consults the width when it is truthy, and wraps the framed + // result — so the opening marker counts towards the first line. + if wrapcol.py_bool(vm)? { + let width = a85_wrapcol(wrapcol, if adobe { 2 } else { 1 }, vm)?; + encoded = a85_wrap(&encoded, width, adobe, &vm.heap.tracker)?; + } + if adobe { + encoded.extend_from_slice(A85_ADOBE_END); + } + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `base64.a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v')` +/// — the inverse of [`call_a85encode`]. +/// +/// `foldspaces` must be set to the same value the encoder used, since `y` is +/// otherwise not a digit at all. +fn call_a85decode(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let A85DecodeArgs { + b, + foldspaces, + adobe, + ignorechars, + } = A85DecodeArgs::from_args(args, vm)?; + defer_drop!(b, vm); + defer_drop!(foldspaces, vm); + defer_drop!(adobe, vm); + defer_drop!(ignorechars, vm); + + // Owned so the decode loop can re-enter the interpreter for a caller-given + // `ignorechars`, which the borrowed input would rule out. + let data = decode_input(b, vm)?.into_owned(); + let framed = a85_strip_adobe(&data, adobe.py_bool(vm)?)?; + let fold = foldspaces.py_bool(vm)?; + let ignore = match ignorechars.as_ref() { + Some(value) => IgnoreChars::Given(value), + None => IgnoreChars::Default, + }; + + let decoded = a85_decode(framed, fold, &ignore, vm)?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// Argument shape for `b64encode(s, altchars=None)`. +/// +/// Fields stay raw `Value` throughout this module: CPython's `def` binding +/// never type-checks, so the body's coercion order is what produces the +/// observable errors. +#[derive(FromArgs)] +#[from_args(name = "b64encode", style = def)] +struct B64EncodeArgs { + s: Value, + #[from_args(default = Value::None)] + altchars: Value, +} + +/// Argument shape for `b64decode(s, altchars=None, validate=False)`. +/// +/// `validate` is a raw `Value` truth-tested in the body — CPython forwards it +/// to `binascii.a2b_base64(strict_mode=...)`, which accepts any object. +#[derive(FromArgs)] +#[from_args(name = "b64decode", style = def)] +struct B64DecodeArgs { + s: Value, + #[from_args(default = Value::None)] + altchars: Value, + #[from_args(default = Value::Bool(false))] + validate: Value, +} + +/// Argument shape for `b32decode(s, casefold=False, map01=None)` — see +/// [`B64DecodeArgs`] for why the flags are raw `Value`s. +#[derive(FromArgs)] +#[from_args(name = "b32decode", style = def)] +struct B32DecodeArgs { + s: Value, + #[from_args(default = Value::Bool(false))] + casefold: Value, + #[from_args(default = Value::None)] + map01: Value, +} + +/// Argument shape for `b32hexdecode(s, casefold=False)`. +#[derive(FromArgs)] +#[from_args(name = "b32hexdecode", style = def)] +struct B32HexDecodeArgs { + s: Value, + #[from_args(default = Value::Bool(false))] + casefold: Value, +} + +/// Argument shape for `b16decode(s, casefold=False)`. +#[derive(FromArgs)] +#[from_args(name = "b16decode", style = def)] +struct B16DecodeArgs { + s: Value, + #[from_args(default = Value::Bool(false))] + casefold: Value, +} + +/// Argument shape for `b85encode(b, pad=False)` — note the parameter is `b`, +/// not the `s` the rest of the module uses, which signature errors report. +#[derive(FromArgs)] +#[from_args(name = "b85encode", style = def)] +struct B85EncodeArgs { + b: Value, + #[from_args(default = Value::Bool(false))] + pad: Value, +} + +/// Argument shape for `b85decode(b)`. +#[derive(FromArgs)] +#[from_args(name = "b85decode", style = def)] +struct B85DecodeArgs { + b: Value, +} + +/// Argument shape for +/// `a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)`. +#[derive(FromArgs)] +#[from_args(name = "a85encode", style = def)] +struct A85EncodeArgs { + b: Value, + #[from_args(kw_only, default = Value::Bool(false))] + foldspaces: Value, + #[from_args(kw_only, default = Value::Int(0))] + wrapcol: Value, + #[from_args(kw_only, default = Value::Bool(false))] + pad: Value, + #[from_args(kw_only, default = Value::Bool(false))] + adobe: Value, +} + +/// Argument shape for +/// `a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v')`. +/// +/// `ignorechars` is absent rather than defaulted: CPython tests membership in +/// whatever object was passed, so an explicit argument takes a different path +/// from the built-in set — see [`IgnoreChars`]. +#[derive(FromArgs)] +#[from_args(name = "a85decode", style = def)] +struct A85DecodeArgs { + b: Value, + #[from_args(kw_only, default = Value::Bool(false))] + foldspaces: Value, + #[from_args(kw_only, default = Value::Bool(false))] + adobe: Value, + #[from_args(kw_only, default)] + ignorechars: Option, +} + +/// Declares the argument struct for one of the module's `f(s)` functions. +/// +/// These differ only in the name reported by signature errors +/// (`b32encode() missing 1 required positional argument: 's'`), which the +/// derive bakes in, so a shared struct cannot serve them. +macro_rules! single_arg_struct { + ($struct_name:ident, $py_name:literal) => { + #[derive(FromArgs)] + #[from_args(name = $py_name, style = def)] + struct $struct_name { + s: Value, + } + }; +} + +single_arg_struct!(StandardB64EncodeArgs, "standard_b64encode"); +single_arg_struct!(StandardB64DecodeArgs, "standard_b64decode"); +single_arg_struct!(UrlsafeB64EncodeArgs, "urlsafe_b64encode"); +single_arg_struct!(UrlsafeB64DecodeArgs, "urlsafe_b64decode"); +single_arg_struct!(B32EncodeArgs, "b32encode"); +single_arg_struct!(B32HexEncodeArgs, "b32hexencode"); +single_arg_struct!(B16EncodeArgs, "b16encode"); +single_arg_struct!(EncodebytesArgs, "encodebytes"); +single_arg_struct!(DecodebytesArgs, "decodebytes"); +single_arg_struct!(Z85EncodeArgs, "z85encode"); +single_arg_struct!(Z85DecodeArgs, "z85decode"); + +/// Encodes bytes as standard base64 with `=` padding. +pub(super) fn b64_encode(data: &[u8], tracker: &ResourceTracker) -> RunResult> { + b64_encode_reserving(data, 0, tracker) +} + +/// [`b64_encode`], leaving room for `extra` bytes the caller will append. +/// +/// The encoder fills its buffer exactly, so appending even one byte — +/// `b2a_base64`'s trailing newline — grows it, and a `Vec` grows by doubling: +/// a second copy of the output, charged as a burst the preflight never saw. +pub(super) fn b64_encode_reserving(data: &[u8], extra: usize, tracker: &ResourceTracker) -> RunResult> { + let capacity = data.len().div_ceil(3) * 4 + extra; + check_estimated_size(capacity, tracker)?; + let mut out = Vec::with_capacity(capacity); + for chunk in data.chunks(3) { + let b0 = usize::from(chunk[0]); + let b1 = chunk.get(1).map_or(0, |b| usize::from(*b)); + let b2 = chunk.get(2).map_or(0, |b| usize::from(*b)); + out.push(B64_ALPHABET[b0 >> 2]); + out.push(B64_ALPHABET[((b0 & 0x03) << 4) | (b1 >> 4)]); + out.push(if chunk.len() > 1 { + B64_ALPHABET[((b1 & 0x0f) << 2) | (b2 >> 6)] + } else { + b'=' + }); + out.push(if chunk.len() > 2 { B64_ALPHABET[b2 & 0x3f] } else { b'=' }); + } + Ok(out) +} + +/// Decodes base64, mirroring `binascii.a2b_base64`'s two modes. +/// +/// Non-strict decoding skips bytes outside the alphabet, and padding only +/// *permits* a quad to end rather than stopping the scan, so +/// `b64decode(b'YQ==YQ==')` is three bytes, not two `a`s. The state machine +/// transcribes CPython's, since which error an input produces depends on +/// exactly where CPython gives up. +pub(super) fn b64_decode(data: &[u8], strict: bool) -> RunResult> { + if strict && data.first() == Some(&b'=') { + return Err(binascii_error("Leading padding not allowed")); + } + + let mut out: Vec = Vec::with_capacity(data.len().div_ceil(4) * 3); + let mut quad_pos = 0u8; + let mut leftchar = 0u8; + let mut pads = 0u8; + let mut padding_started = false; + // Whether padding has closed the quad currently in progress, which makes a + // non-zero `quad_pos` legal at end of input. + let mut quad_closed = false; + + for byte in data { + if *byte == b'=' { + if strict { + // A pad is only ever legal two or three characters into an + // open quad. One character in, CPython reports the same + // "1 more than a multiple of 4" error it would at end of input. + if quad_closed || quad_pos == 0 { + return Err(binascii_error("Excess padding not allowed")); + } else if quad_pos == 1 { + return Err(invalid_data_characters(out.len())); + } + } + padding_started = true; + // Only count pads while the quad is open: once closed, further `=` + // bytes are inert, and counting them would overflow these `u8`s. + if quad_pos >= 2 && !quad_closed { + pads += 1; + if quad_pos + pads >= 4 { + quad_closed = true; + } + } + continue; + } + + let Some(sextet) = b64_value(*byte) else { + if strict { + return Err(binascii_error("Only base64 data is allowed")); + } + continue; + }; + if strict { + if quad_closed { + return Err(binascii_error("Excess data after padding")); + } else if padding_started { + return Err(binascii_error("Discontinuous padding not allowed")); + } + } + pads = 0; + quad_closed = false; + + match quad_pos { + 0 => { + quad_pos = 1; + leftchar = sextet; + } + 1 => { + quad_pos = 2; + out.push((leftchar << 2) | (sextet >> 4)); + leftchar = sextet & 0x0f; + } + 2 => { + quad_pos = 3; + out.push((leftchar << 4) | (sextet >> 2)); + leftchar = sextet & 0x03; + } + _ => { + quad_pos = 0; + out.push((leftchar << 6) | sextet); + leftchar = 0; + } + } + } + + if quad_pos == 0 || quad_closed { + Ok(out) + } else if quad_pos == 1 { + Err(invalid_data_characters(out.len())) + } else { + Err(incorrect_padding()) + } +} + +/// The error for a quad holding a single character, which no encoder can +/// produce. The count is of decoded characters, derived from the output so far, +/// not of input bytes — junk and padding never reach it. +fn invalid_data_characters(decoded_len: usize) -> RunError { + let data_chars = decoded_len / 3 * 4 + 1; + binascii_error(format!( + "Invalid base64-encoded string: number of data characters ({data_chars}) cannot be 1 more than a multiple of 4" + )) +} + +/// Maps a base64 character to its 6-bit value. +fn b64_value(byte: u8) -> Option { + match byte { + b'A'..=b'Z' => Some(byte - b'A'), + b'a'..=b'z' => Some(byte - b'a' + 26), + b'0'..=b'9' => Some(byte - b'0' + 52), + b'+' => Some(62), + b'/' => Some(63), + _ => None, + } +} + +/// Encodes bytes as base32 over `alphabet`, padding the final group to eight +/// characters with `=`. +fn b32_encode(data: &[u8], alphabet: &[u8; 32], tracker: &ResourceTracker) -> RunResult> { + let capacity = data.len().div_ceil(5) * 8; + check_estimated_size(capacity, tracker)?; + let mut out = Vec::with_capacity(capacity); + for chunk in data.chunks(5) { + let mut acc: u64 = 0; + for i in 0..5 { + acc = (acc << 8) | u64::from(chunk.get(i).copied().unwrap_or(0)); + } + // Characters carrying data; the remaining 8 - encoded_len are pads. + let encoded_len = match chunk.len() { + 1 => 2, + 2 => 4, + 3 => 5, + 4 => 7, + _ => 8, + }; + for i in 0..8 { + out.push(if i < encoded_len { + let shift = 35 - i * 5; + alphabet[usize::try_from((acc >> shift) & 0x1f).expect("5 bits fit usize")] + } else { + b'=' + }); + } + } + Ok(out) +} + +/// Decodes base32 over `alphabet`. +/// +/// Assumes the caller has already checked that the length is a multiple of +/// eight and applied any `map01` translation — CPython performs both before +/// this point and the resulting error ordering is observable. +fn b32_decode(data: &[u8], alphabet: &[u8; 32], casefold: bool) -> RunResult> { + let folded: Cow<'_, [u8]> = if casefold { + Cow::Owned(data.to_ascii_uppercase()) + } else { + Cow::Borrowed(data) + }; + let stripped = { + let mut end = folded.len(); + while end > 0 && folded[end - 1] == b'=' { + end -= 1; + } + &folded[..end] + }; + let pad_chars = folded.len() - stripped.len(); + + let mut out = Vec::with_capacity(stripped.len() / 8 * 5 + 5); + let mut last_acc: u64 = 0; + for group in stripped.chunks(8) { + let mut acc: u64 = 0; + for byte in group { + let Some(value) = alphabet.iter().position(|c| c == byte) else { + return Err(binascii_error("Non-base32 digit found")); + }; + acc = (acc << 5) | u64::try_from(value).expect("alphabet index fits u64"); + } + last_acc = acc; + // A short final group is still written as five bytes here and trimmed + // below, exactly as CPython's `decoded[-5:] = last[:leftover]` does. + out.extend_from_slice(&acc.to_be_bytes()[3..]); + } + + // 0, 1, 3, 4 and 6 are the pad counts a base32 encoder can emit. + if !matches!(pad_chars, 0 | 1 | 3 | 4 | 6) { + return Err(incorrect_padding()); + } + if pad_chars > 0 && !out.is_empty() { + let shifted = last_acc << (5 * pad_chars); + let leftover = (43 - 5 * pad_chars) / 8; + let tail = shifted.to_be_bytes(); + out.truncate(out.len() - 5); + out.extend_from_slice(&tail[3..3 + leftover]); + } + Ok(out) +} + +/// Encodes bytes as uppercase hex (`b16encode`). +fn b16_encode(data: &[u8], tracker: &ResourceTracker) -> RunResult> { + const HEX: &[u8; 16] = b"0123456789ABCDEF"; + let capacity = data.len() * 2; + check_estimated_size(capacity, tracker)?; + let mut out = Vec::with_capacity(capacity); + for byte in data { + out.push(HEX[usize::from(byte >> 4)]); + out.push(HEX[usize::from(byte & 0x0f)]); + } + Ok(out) +} + +/// Decodes uppercase hex, folding case first when asked. +/// +/// CPython screens the whole input for non-`[0-9A-F]` bytes before +/// `binascii.unhexlify` sees it, so a bad digit outranks an odd length. +fn b16_decode(data: &[u8], casefold: bool) -> RunResult> { + let folded: Cow<'_, [u8]> = if casefold { + Cow::Owned(data.to_ascii_uppercase()) + } else { + Cow::Borrowed(data) + }; + if folded.iter().any(|b| !matches!(b, b'0'..=b'9' | b'A'..=b'F')) { + return Err(binascii_error("Non-base16 digit found")); + } + if !folded.len().is_multiple_of(2) { + return Err(binascii_error("Odd-length string")); + } + Ok(folded + .chunks(2) + .map(|pair| (hex_value(pair[0]) << 4) | hex_value(pair[1])) + .collect()) +} + +/// Maps a validated uppercase hex digit to its value. +fn hex_value(byte: u8) -> u8 { + if byte.is_ascii_digit() { + byte - b'0' + } else { + byte - b'A' + 10 + } +} + +/// Encodes bytes as base85 over `alphabet`, five characters per four bytes. +/// +/// A short final group is zero-padded to four bytes; unless `pad` is set, the +/// characters those padding bytes produced are dropped again, so the output +/// length tracks the input's. +fn b85_encode(data: &[u8], alphabet: &[u8; 85], pad: bool, tracker: &ResourceTracker) -> RunResult> { + let padding = (4 - data.len() % 4) % 4; + let capacity = data.len().div_ceil(4) * 5; + check_estimated_size(capacity, tracker)?; + let mut out = Vec::with_capacity(capacity); + + for chunk in data.chunks(4) { + let mut word: u32 = 0; + for i in 0..4 { + word = (word << 8) | u32::from(chunk.get(i).copied().unwrap_or(0)); + } + // Five base-85 digits, most significant first. + let mut digits = [0u8; 5]; + for slot in digits.iter_mut().rev() { + *slot = alphabet[usize::try_from(word % 85).expect("remainder below 85")]; + word /= 85; + } + out.extend_from_slice(&digits); + } + + if !pad { + out.truncate(out.len() - padding); + } + Ok(out) +} + +/// Decodes base85 over `alphabet`, with `codec` naming the scheme in errors. +/// +/// A trailing partial group is completed with the alphabet's highest character +/// and the extra bytes trimmed off, so any input length decodes. Unlike the +/// other decoders here, failures are plain `ValueError`s, as CPython's are. +fn b85_decode(data: &[u8], alphabet: &[u8; 85], codec: &str) -> RunResult> { + let table = base85_table(alphabet); + let padding = (5 - data.len() % 5) % 5; + let mut out = Vec::with_capacity(data.len().div_ceil(5) * 4); + + for (chunk_index, chunk) in data.chunks(5).enumerate() { + let start = chunk_index * 5; + let mut acc: u64 = 0; + for offset in 0..5 { + // Positions past the end are the virtual padding: the top digit. + let value = match chunk.get(offset) { + Some(byte) => table[usize::from(*byte)].ok_or_else(|| { + codec_value_error(format!("bad {codec} character at position {}", start + offset)) + })?, + None => 84, + }; + acc = acc * 85 + u64::from(value); + } + let word = u32::try_from(acc) + .map_err(|_| codec_value_error(format!("{codec} overflow in hunk starting at byte {start}")))?; + out.extend_from_slice(&word.to_be_bytes()); + } + + out.truncate(out.len() - padding); + Ok(out) +} + +/// Reverse lookup for a base85 alphabet: index by byte, `None` outside it. +fn base85_table(alphabet: &[u8; 85]) -> [Option; 256] { + let mut table = [None; 256]; + for (value, byte) in alphabet.iter().enumerate() { + table[usize::from(*byte)] = Some(u8::try_from(value).expect("index bounded by alphabet length")); + } + table +} + +/// Encodes bytes as Ascii85, five digits per four-byte word. +/// +/// An all-zero word folds to `z` and, with `foldspaces`, four spaces fold to +/// `y`. A short final group is zero-padded to a full word and the digits that +/// padding produced are dropped again unless `pad` is set. +/// +/// `extra` reserves the Adobe framing the caller splices onto both ends, which +/// would otherwise double a buffer this fills to the byte. +fn a85_encode(data: &[u8], pad: bool, foldspaces: bool, extra: usize, tracker: &ResourceTracker) -> RunResult> { + let padding = (4 - data.len() % 4) % 4; + let capacity = data.len().div_ceil(4) * 5 + extra; + check_estimated_size(capacity, tracker)?; + let mut out: Vec = Vec::with_capacity(capacity); + // Where the final word's digits start, so the padding trim below can + // rewrite them the way CPython rewrites `chunks[-1]`. + let mut last_start = 0; + + for chunk in data.chunks(4) { + last_start = out.len(); + let mut word: u32 = 0; + for i in 0..4 { + word = (word << 8) | u32::from(chunk.get(i).copied().unwrap_or(0)); + } + if word == 0 { + out.push(b'z'); + } else if foldspaces && word == 0x2020_2020 { + out.push(b'y'); + } else { + // Five base-85 digits, most significant first. + let mut digits = [0u8; 5]; + for slot in digits.iter_mut().rev() { + *slot = A85_FIRST_DIGIT + u8::try_from(word % 85).expect("remainder below 85"); + word /= 85; + } + out.extend_from_slice(&digits); + } + } + + if padding != 0 && !pad { + // Padding cannot make a word four spaces, but it can make one zero — + // and a folded `z` has no digits to trim, so it is expanded first. + if out[last_start..] == *b"z" { + out.truncate(last_start); + out.extend_from_slice(&[A85_FIRST_DIGIT; 5]); + } + out.truncate(out.len() - padding); + } + Ok(out) +} + +/// Breaks encoded output into lines of at most `width` characters. +/// +/// With the Adobe framing an extra newline is added when `~>` would not fit on +/// the last line, so no line ever exceeds `width`. +fn a85_wrap(result: &[u8], width: usize, adobe: bool, tracker: &ResourceTracker) -> RunResult> { + // The closing marker is appended to what this returns, so it is reserved + // here alongside the newlines rather than growing the buffer afterwards. + let closing = if adobe { A85_ADOBE_END.len() } else { 0 }; + let capacity = result.len() + result.len() / width + 1 + closing; + check_estimated_size(capacity, tracker)?; + let mut out = Vec::with_capacity(capacity); + let mut last_len = 0; + for (index, line) in result.chunks(width).enumerate() { + if index > 0 { + out.push(b'\n'); + } + out.extend_from_slice(line); + last_len = line.len(); + } + if adobe && last_len + A85_ADOBE_END.len() > width { + out.push(b'\n'); + } + Ok(out) +} + +/// Resolves `max(2 if adobe else 1, wrapcol)` and the index `range` then needs. +/// +/// Both of CPython's failure modes live here: a `wrapcol` that cannot be +/// ordered against an `int` fails in `max`, and one that wins the comparison +/// but is no index — a `float` of one or more — fails in `range`. +fn a85_wrapcol(wrapcol: &Value, floor: u8, vm: &mut VM<'_>) -> RunResult { + let wider = match wrapcol.py_cmp(&Value::Int(i64::from(floor)), vm)? { + CmpOrder::Ordered(Ordering::Greater) => true, + // `NaN` is neither larger nor smaller, so the floor stands, as in `max`. + CmpOrder::Ordered(_) | CmpOrder::Unordered => false, + CmpOrder::Incomparable => { + return Err(ExcType::type_error_ordering(">", &wrapcol.py_type_name(vm), "int")); + } + }; + if wider { + a85_width(wrapcol, vm) + } else { + Ok(usize::from(floor)) + } +} + +/// Converts a `wrapcol` that won the `max` into a line length. +/// +/// CPython feeds it to `range`, which takes an arbitrary `int`, so a width +/// past the address space is not an error — everything lands on one line. +/// Having beaten a floor of 1, such a width can only be large and positive. +fn a85_width(wrapcol: &Value, vm: &mut VM<'_>) -> RunResult { + let long = match wrapcol { + Value::InternLongInt(_) => true, + Value::Ref(heap_id) => matches!(vm.heap.get(*heap_id), HeapData::LongInt(_)), + _ => false, + }; + if long { + Ok(usize::MAX) + } else { + Ok(usize::try_from(wrapcol.as_int(vm)?).unwrap_or(usize::MAX)) + } +} + +/// Strips the `<~` / `~>` framing when `adobe` is set, leaving the digits. +/// +/// Only the terminator is required — PDF streams carry it without the opening +/// marker — and the two overlap in `b'<~>'`, where Python's slicing yields an +/// empty body rather than failing. +fn a85_strip_adobe(data: &[u8], adobe: bool) -> RunResult<&[u8]> { + if !adobe { + Ok(data) + } else if data.ends_with(A85_ADOBE_END) { + let end = data.len() - A85_ADOBE_END.len(); + let start = if data.starts_with(A85_ADOBE_START) { + A85_ADOBE_START.len() + } else { + 0 + }; + Ok(data.get(start..end).unwrap_or_default()) + } else { + Err(codec_value_error("Ascii85 encoded byte sequences must end with b'~>'")) + } +} + +/// Decodes Ascii85, transcribing CPython's byte-at-a-time loop. +/// +/// The four `u`s appended to the input flush a trailing partial group, exactly +/// as CPython's `b + b'u' * 4` does; the bytes they contributed are trimmed +/// off again at the end, so a group left one digit short decodes to nothing. +/// +/// Alone among the decoders this can outgrow its input, so its buffer is sized +/// by [`a85_decoded_size`] rather than from the input's length. +fn a85_decode(data: &[u8], foldspaces: bool, ignore: &IgnoreChars<'_>, vm: &mut VM<'_>) -> RunResult> { + let capacity = a85_decoded_size(data, foldspaces); + check_estimated_size(capacity, &vm.heap.tracker)?; + let mut out: Vec = Vec::with_capacity(capacity); + let mut acc: u64 = 0; + let mut digits = 0u8; + // Counts only the bytes reaching `skips`, the one arm whose cost grows with + // a caller's `ignorechars`. Indexing by position instead would let input + // that lands those bytes off the poll's stride skip the clock entirely. + let mut ignored = 0usize; + + for byte in data.iter().copied().chain([A85_LAST_DIGIT; 4]) { + if (A85_FIRST_DIGIT..=A85_LAST_DIGIT).contains(&byte) { + acc = acc * 85 + u64::from(byte - A85_FIRST_DIGIT); + digits += 1; + if digits == 5 { + // Five digits reach 85**5 - 1, half again as much as a word holds. + let word = u32::try_from(acc).map_err(|_| codec_value_error("Ascii85 overflow"))?; + out.extend_from_slice(&word.to_be_bytes()); + acc = 0; + digits = 0; + } + } else if byte == b'z' { + // The short forms stand for a whole word, so they cannot appear + // part-way through one. + if digits != 0 { + return Err(codec_value_error("z inside Ascii85 5-tuple")); + } + out.extend_from_slice(&[0; 4]); + } else if foldspaces && byte == b'y' { + if digits != 0 { + return Err(codec_value_error("y inside Ascii85 5-tuple")); + } + out.extend_from_slice(b" "); + } else { + // `ignorechars` is a Python container, so this is a `py_contains` + // per byte — linear for `bytes`. Nothing here returns to the VM's + // dispatch checkpoint, so the loop polls the clock itself. + vm.heap.tracker.check_time_every(ignored)?; + ignored += 1; + if !ignore.skips(byte, vm)? { + return Err(codec_value_error(format!( + "Non-Ascii85 digit found: {}", + char::from(byte) + ))); + } + } + } + + // Each digit still held stood for a byte the input never carried. The flush + // guarantees a whole word was written, so there is always that much to trim. + out.truncate(out.len() - usize::from(4 - digits)); + Ok(out) +} + +/// How many bytes [`a85_decode`] writes before its trailing trim. +/// +/// The input's length is no guide: five ordinary digits decode to four bytes, +/// but `z` (and `y` when folding) stands for a whole four-byte word, so a +/// buffer of them quadruples. Exact for an input that decodes, and an upper +/// bound for one that fails part-way. +fn a85_decoded_size(data: &[u8], foldspaces: bool) -> usize { + // Two plain counts rather than one if/else chain, so each vectorises. + let digits = data + .iter() + .filter(|byte| (A85_FIRST_DIGIT..=A85_LAST_DIGIT).contains(*byte)) + .count(); + let words = data + .iter() + .filter(|byte| **byte == b'z' || (foldspaces && **byte == b'y')) + .count(); + // The decode appends four digits of its own, so a partial group is flushed + // as a whole one. Saturating so a 32-bit target reports a rejectable size. + digits.div_ceil(5).saturating_add(words).saturating_mul(4) +} + +/// Which bytes `a85decode` skips rather than decoding. +/// +/// Splitting the default out keeps the common case a byte comparison: an +/// explicit argument is tested with Python's `in`, which re-enters the +/// interpreter and is where a `str` argument raises the way CPython's does. +enum IgnoreChars<'a> { + /// `ignorechars` left at its `b' \t\n\r\v'` default. + Default, + /// The object the caller passed, whatever its type. + Given(&'a Value), +} + +impl IgnoreChars<'_> { + /// Answers CPython's `x in ignorechars` for a byte no digit rule matched. + fn skips(&self, byte: u8, vm: &mut VM<'_>) -> RunResult { + match self { + Self::Default => Ok(matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | 0x0b)), + Self::Given(value) => value.py_contains(&Value::Int(i64::from(byte)), vm), + } + } +} + +/// Builds the plain `ValueError` the ascii85 and base85 codecs raise — not +/// `binascii.Error`, since none of them reaches `binascii`. +fn codec_value_error(message: impl Into) -> RunError { + SimpleException::new_msg(ExcType::ValueError, message.into()).into() +} + +/// Rewrites `data` in place, mapping each byte of `from` to the byte at the +/// same index of `to` — CPython's `bytes.translate(bytes.maketrans(...))`. +/// +/// Later entries win, matching `maketrans` when `from` repeats a byte. +fn translate(data: &mut [u8], from: &[u8], to: &[u8]) { + let mut table: [u8; 256] = [0; 256]; + for (i, slot) in table.iter_mut().enumerate() { + *slot = u8::try_from(i).expect("index bounded by table length"); + } + for (src, dst) in from.iter().zip(to) { + table[usize::from(*src)] = *dst; + } + for byte in data { + *byte = table[usize::from(*byte)]; + } +} + +/// Borrows the bytes of an encoder input. +/// +/// Encoders reach `binascii` without a coercion step, so a `str` fails the +/// buffer protocol with CPython's `a bytes-like object is required` wording. +pub(super) fn encode_input<'a>(value: &'a Value, vm: &'a VM<'_>) -> RunResult> { + encode_input_prefixed(value, vm, "") +} + +/// Borrows the bytes of an encoder that coerces with `memoryview(s).tobytes()` +/// first — the base32 and base85 pair — whose `TypeError` is prefixed as a +/// result. The base64 and base16 encoders reach `binascii` directly instead. +fn memoryview_input<'a>(value: &'a Value, vm: &'a VM<'_>) -> RunResult> { + encode_input_prefixed(value, vm, "memoryview: ") +} + +/// Shared body of the encoder coercions, where `prefix` selects the wording. +fn encode_input_prefixed<'a>(value: &'a Value, vm: &'a VM<'_>, prefix: &str) -> RunResult> { + value_as_bytes(value, vm).ok_or_else(|| { + ExcType::type_error(format!( + "{prefix}a bytes-like object is required, not '{}'", + value.py_type_name(vm) + )) + }) +} + +/// Borrows the bytes of a decoder input — CPython's `_bytes_from_decode_data`. +/// +/// Decoders additionally accept `str`, provided it is pure ASCII. +pub(super) fn decode_input<'a>(value: &'a Value, vm: &'a VM<'_>) -> RunResult> { + decode_input_described(value, vm, "a bytes-like object or ASCII string") +} + +/// The same coercion with `expected` naming the accepted types, which +/// `binascii`'s own functions word differently from `base64`'s. +pub(super) fn decode_input_described<'a>(value: &'a Value, vm: &'a VM<'_>, expected: &str) -> RunResult> { + if value.is_str(vm.heap) { + let text = value.to_str(vm)?; + if text.is_ascii() { + Ok(Cow::Borrowed(text.as_bytes())) + } else { + Err(SimpleException::new_msg( + ExcType::ValueError, + "string argument should contain only ASCII characters", + ) + .into()) + } + } else { + value_as_bytes(value, vm).ok_or_else(|| { + ExcType::type_error(format!( + "argument should be {expected}, not '{}'", + value.py_type_name(vm) + )) + }) + } +} + +/// Borrows the bytes of an `encodebytes` / `decodebytes` argument. +/// +/// These two go through `base64._input_type_check`, whose message differs from +/// both other paths. +fn input_type_check<'a>(value: &'a Value, vm: &'a VM<'_>) -> RunResult> { + value_as_bytes(value, vm) + .ok_or_else(|| ExcType::type_error(format!("expected bytes-like object, not {}", value.py_type_name(vm)))) +} + +/// Borrows the bytes behind a `bytes` value, interned or heap-allocated. +/// +/// `None` for anything else — each caller supplies its own error message. +fn value_as_bytes<'a>(value: &'a Value, vm: &'a VM<'_>) -> Option> { + match value { + Value::InternBytes(bytes_id) => Some(Cow::Borrowed(vm.interns.get_bytes(*bytes_id))), + Value::Ref(heap_id) => match vm.heap.get(*heap_id) { + HeapData::Bytes(bytes) => Some(Cow::Borrowed(bytes.as_slice())), + _ => None, + }, + _ => None, + } +} + +/// Reproduces `assert len(value) == expected, repr(value)` on a raw argument. +fn assert_len(value: &Value, expected: usize, vm: &mut VM<'_>) -> RunResult<()> { + let Some(len) = value.py_len(vm) else { + return Err(ExcType::type_error(format!( + "object of type '{}' has no len()", + value.py_type_name(vm) + ))); + }; + if len == expected { + Ok(()) + } else { + Err(assertion_error(value, vm)?) + } +} + +/// The same assertion, but against already-coerced bytes. +/// +/// The decoders coerce before asserting, so both the length and the `repr` in +/// the message come from the bytes — `b64decode(s, altchars='-')` reports +/// `b'-'`, not the `str` the caller passed. +fn assert_len_bytes(bytes: &[u8], expected: usize) -> RunResult<()> { + if bytes.len() == expected { + Ok(()) + } else { + Err(SimpleException::new_msg(ExcType::AssertionError, bytes_repr(bytes)).into()) + } +} + +/// Builds the `AssertionError` whose message is `repr(value)`. +fn assertion_error(value: &Value, vm: &mut VM<'_>) -> RunResult { + let repr = value.py_repr(vm)?; + defer_drop!(repr, vm); + let message = repr.to_str(vm)?.to_owned(); + Ok(SimpleException::new_msg(ExcType::AssertionError, message).into()) +} + +/// Allocates a decoded/encoded byte string on the heap. +/// +/// No resource preflight: every result here is bounded by a small constant +/// multiple of an input that the heap already accounts for. +pub(super) fn allocate_bytes(data: Vec, heap: &Heap) -> Value { + Value::Ref(heap.allocate(HeapData::Bytes(data.into()))) +} + +/// `binascii.Error("Incorrect padding")` — shared by the base64 and base32 +/// padding checks. +fn incorrect_padding() -> RunError { + binascii_error("Incorrect padding") +} + +/// Builds a `binascii.Error`, the `ValueError` subclass every codec failure uses. +pub(super) fn binascii_error(message: impl Into) -> RunError { + SimpleException::new_msg(ExcType::BinasciiError, message.into()).into() +} diff --git a/crates/bashkit-monty/src/modules/binascii.rs b/crates/bashkit-monty/src/modules/binascii.rs new file mode 100644 index 000000000..121d1b643 --- /dev/null +++ b/crates/bashkit-monty/src/modules/binascii.rs @@ -0,0 +1,871 @@ +//! Implementation of Python's `binascii` module. +//! +//! Every name CPython's `binascii` exposes: the `Error` and `Incomplete` +//! classes, the hex pair (`hexlify`/`unhexlify` and their `b2a_hex`/`a2b_hex` +//! aliases), the base64 pair (`b2a_base64`/`a2b_base64`), the uuencode pair +//! (`b2a_uu`/`a2b_uu`), the quoted-printable pair (`b2a_qp`/`a2b_qp`) and the +//! two checksums `crc32` and `crc_hqx`. +//! +//! These are C functions in CPython, not the pure Python of [`super::base64`], +//! so each argument struct names the parser family CPython's own definition +//! uses: `hexlify` is `PyArg_ParseTupleAndKeywords`, the base64 and uuencode +//! pairs are Argument Clinic with keyword-only flags, `crc32` and `crc_hqx` +//! are `PyArg_UnpackTuple`, and `unhexlify` and `a2b_uu` are `METH_O`, which +//! [`ArgValues::get_one_arg`] already words correctly. +//! +//! The byte-level codecs live in [`super::base64`], where they were written +//! first; `binascii` re-exposes them under the names CPython puts them at. + +use monty_types::ResourceTracker; + +use crate::{ + args::{ArgValues, FromArgs}, + builtins::Builtins, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{DropWithContext, HeapData, HeapId}, + intern::StaticStrings, + modules::{ + ModuleFunctions, + base64::{ + allocate_bytes, b64_decode, b64_encode_reserving, binascii_error, decode_input_described, encode_input, + }, + }, + py_value::PyValue, + resource_checks::check_estimated_size, + types::{Module, PyTrait}, + value::Value, +}; + +/// Lowercase hex digits, `hexlify`'s output alphabet. +const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef"; + +/// `binascii` module functions, one variant per Python-visible function. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +pub(crate) enum BinasciiFunctions { + #[strum(serialize = "hexlify")] + Hexlify, + #[strum(serialize = "unhexlify")] + Unhexlify, + #[strum(serialize = "b2a_hex")] + B2aHex, + #[strum(serialize = "a2b_hex")] + A2bHex, + #[strum(serialize = "b2a_base64")] + B2aBase64, + #[strum(serialize = "a2b_base64")] + A2bBase64, + #[strum(serialize = "crc32")] + Crc32, + #[strum(serialize = "crc_hqx")] + CrcHqx, + #[strum(serialize = "b2a_uu")] + B2aUu, + #[strum(serialize = "a2b_uu")] + A2bUu, + #[strum(serialize = "b2a_qp")] + B2aQp, + #[strum(serialize = "a2b_qp")] + A2bQp, +} + +/// Static mapping of attribute names to functions for module creation. +const BINASCII_FUNCTIONS: &[(StaticStrings, BinasciiFunctions)] = &[ + (StaticStrings::Hexlify, BinasciiFunctions::Hexlify), + (StaticStrings::Unhexlify, BinasciiFunctions::Unhexlify), + (StaticStrings::B2aHex, BinasciiFunctions::B2aHex), + (StaticStrings::A2bHex, BinasciiFunctions::A2bHex), + (StaticStrings::B2aBase64, BinasciiFunctions::B2aBase64), + (StaticStrings::A2bBase64, BinasciiFunctions::A2bBase64), + (StaticStrings::Crc32, BinasciiFunctions::Crc32), + (StaticStrings::CrcHqx, BinasciiFunctions::CrcHqx), + (StaticStrings::B2aUu, BinasciiFunctions::B2aUu), + (StaticStrings::A2bUu, BinasciiFunctions::A2bUu), + (StaticStrings::B2aQp, BinasciiFunctions::B2aQp), + (StaticStrings::A2bQp, BinasciiFunctions::A2bQp), +]; + +/// Creates the `binascii` module on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Binascii, vm.interns); + + module.set_attr( + StaticStrings::ErrorClass, + Value::Builtin(Builtins::ExcType(ExcType::BinasciiError)), + vm, + ); + module.set_attr( + StaticStrings::IncompleteClass, + Value::Builtin(Builtins::ExcType(ExcType::BinasciiIncomplete)), + vm, + ); + for (name, func) in BINASCII_FUNCTIONS { + module.set_attr(*name, Value::ModuleFunction(ModuleFunctions::Binascii(*func)), vm); + } + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a call to a `binascii` module function. +/// +/// All functions are pure computations and return `Value` directly. +pub(super) fn call(vm: &mut VM<'_>, function: BinasciiFunctions, args: ArgValues) -> RunResult { + match function { + BinasciiFunctions::Hexlify => call_hexlify(vm, args, "hexlify"), + BinasciiFunctions::B2aHex => call_hexlify(vm, args, "b2a_hex"), + BinasciiFunctions::Unhexlify => call_unhexlify(vm, args, "binascii.unhexlify"), + BinasciiFunctions::A2bHex => call_unhexlify(vm, args, "binascii.a2b_hex"), + BinasciiFunctions::B2aBase64 => call_b2a_base64(vm, args), + BinasciiFunctions::A2bBase64 => call_a2b_base64(vm, args), + BinasciiFunctions::Crc32 => call_crc32(vm, args), + BinasciiFunctions::CrcHqx => call_crc_hqx(vm, args), + BinasciiFunctions::B2aUu => call_b2a_uu(vm, args), + BinasciiFunctions::A2bUu => call_a2b_uu(vm, args), + BinasciiFunctions::B2aQp => call_b2a_qp(vm, args), + BinasciiFunctions::A2bQp => call_a2b_qp(vm, args), + } +} + +/// `binascii.hexlify(data, sep, bytes_per_sep=1)` and its `b2a_hex` alias, +/// which differ only in the name their signature errors carry. +fn call_hexlify(vm: &mut VM<'_>, args: ArgValues, name: &str) -> RunResult { + let (data, sep, bytes_per_sep) = if name == "hexlify" { + let HexlifyArgs { + data, + sep, + bytes_per_sep, + } = HexlifyArgs::from_args(args, vm)?; + (data, sep, bytes_per_sep) + } else { + let B2aHexArgs { + data, + sep, + bytes_per_sep, + } = B2aHexArgs::from_args(args, vm)?; + (data, sep, bytes_per_sep) + }; + defer_drop!(data, vm); + defer_drop!(sep, vm); + + let separator = hex_separator(sep.as_ref(), vm)?; + let encoded = hex_encode( + encode_input(data, vm)?.as_ref(), + separator, + bytes_per_sep, + &vm.heap.tracker, + )?; + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `binascii.unhexlify(hexstr)` and its `a2b_hex` alias — `METH_O`, so +/// keywords are rejected wholesale before the arity is even counted, both +/// under the module-qualified `name`. +fn call_unhexlify(vm: &mut VM<'_>, args: ArgValues, name: &str) -> RunResult { + let mut positional = args.into_pos_only(name, vm.heap)?; + let count = positional.len(); + let Some(hexstr) = positional.next().filter(|_| count == 1) else { + positional.drop_with(vm.heap); + return Err(ExcType::type_error_arg_count(name, 1, count)); + }; + defer_drop!(hexstr, vm); + + let decoded = hex_decode(decode_input_described(hexstr, vm, "bytes, buffer or ASCII string")?.as_ref())?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `binascii.b2a_base64(data, *, newline=True)` — base64 with the trailing +/// newline `encodebytes` relies on. +fn call_b2a_base64(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B2aBase64Args { data, newline } = B2aBase64Args::from_args(args, vm)?; + defer_drop!(data, vm); + defer_drop!(newline, vm); + + // Resolved before encoding so the newline is reserved with the rest, which + // is also where CPython's Argument Clinic `p` converter reads it. + let newline = newline.py_bool(vm)?; + let mut encoded = b64_encode_reserving(encode_input(data, vm)?.as_ref(), usize::from(newline), &vm.heap.tracker)?; + if newline { + encoded.push(b'\n'); + } + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `binascii.a2b_base64(data, *, strict_mode=False)` — the decoder every +/// `base64` decode path funnels into. +fn call_a2b_base64(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let A2bBase64Args { data, strict_mode } = A2bBase64Args::from_args(args, vm)?; + defer_drop!(data, vm); + defer_drop!(strict_mode, vm); + + let strict = strict_mode.py_bool(vm)?; + let decoded = b64_decode( + decode_input_described(data, vm, "bytes, buffer or ASCII string")?.as_ref(), + strict, + )?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `binascii.crc32(data, crc=0)` — CRC-32 as used by zip and png, resumable +/// by feeding the previous result back in as `crc`. +fn call_crc32(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let Crc32Args { data, crc } = Crc32Args::from_args(args, vm)?; + defer_drop!(data, vm); + defer_drop!(crc, vm); + + // CPython converts `crc` with the `I` format, which takes any int modulo + // 2**32 rather than rejecting one out of range. + let seed = match crc { + None => 0, + Some(value) => wrapping_u32(value, vm)?, + }; + let checksum = crc32(encode_input(data, vm)?.as_ref(), seed); + Ok(Value::Int(i64::from(checksum))) +} + +/// `binascii.crc_hqx(data, crc)` — the CRC-16 the classic BinHex format used, +/// resumable through `crc` exactly as `crc32` is. +fn call_crc_hqx(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let CrcHqxArgs { data, crc } = CrcHqxArgs::from_args(args, vm)?; + defer_drop!(data, vm); + defer_drop!(crc, vm); + + // The `I` format takes the seed modulo 2**32, then the body narrows it to + // the 16 bits the register holds — so `-1` and `0xffff` seed alike. + let seed = u16::try_from(wrapping_u32(crc, vm)? & 0xffff).expect("masked below 2**16"); + let checksum = crc_hqx(encode_input(data, vm)?.as_ref(), seed); + Ok(Value::Int(i64::from(checksum))) +} + +/// `binascii.b2a_uu(data, *, backtick=False)` — one uuencoded line, newline +/// included, for at most the 45 bytes the line-length byte can describe. +fn call_b2a_uu(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B2aUuArgs { data, backtick } = B2aUuArgs::from_args(args, vm)?; + defer_drop!(data, vm); + defer_drop!(backtick, vm); + + let backtick = backtick.py_bool(vm)?; + let encoded = uu_encode(encode_input(data, vm)?.as_ref(), backtick)?; + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `binascii.a2b_uu(data)` — the inverse, tolerant of either padding +/// convention and of a line truncated before its length byte promised. +fn call_a2b_uu(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let mut positional = args.into_pos_only("binascii.a2b_uu", vm.heap)?; + let count = positional.len(); + let Some(data) = positional.next().filter(|_| count == 1) else { + positional.drop_with(vm.heap); + return Err(ExcType::type_error_arg_count("binascii.a2b_uu", 1, count)); + }; + defer_drop!(data, vm); + + let decoded = uu_decode(decode_input_described(data, vm, "bytes, buffer or ASCII string")?.as_ref())?; + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// `binascii.b2a_qp(data, quotetabs=False, istext=True, header=False)` — +/// quoted-printable encoding, soft-wrapped to 76 columns. +fn call_b2a_qp(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let B2aQpArgs { + data, + quotetabs, + istext, + header, + } = B2aQpArgs::from_args(args, vm)?; + defer_drop!(data, vm); + defer_drop!(quotetabs, vm); + defer_drop!(istext, vm); + defer_drop!(header, vm); + + let options = QpOptions { + quotetabs: quotetabs.py_bool(vm)?, + istext: istext.py_bool(vm)?, + header: header.py_bool(vm)?, + }; + let encoded = qp_encode(encode_input(data, vm)?.as_ref(), options, &vm.heap.tracker)?; + Ok(allocate_bytes(encoded, vm.heap)) +} + +/// `binascii.a2b_qp(data, header=False)` — quoted-printable decoding, which +/// never fails: anything malformed is copied through verbatim. +fn call_a2b_qp(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let A2bQpArgs { data, header } = A2bQpArgs::from_args(args, vm)?; + defer_drop!(data, vm); + defer_drop!(header, vm); + + let header = header.py_bool(vm)?; + let decoded = qp_decode( + decode_input_described(data, vm, "bytes, buffer or ASCII string")?.as_ref(), + header, + ); + Ok(allocate_bytes(decoded, vm.heap)) +} + +/// Argument shape for `hexlify(data, sep, bytes_per_sep=1)`. +/// +/// `PyArg_ParseTupleAndKeywords` with a `:name`, plus the up-front count that +/// reports `takes at most 3 arguments` rather than an unexpected keyword. +#[derive(FromArgs)] +#[from_args(name = "hexlify", style = c_named, at_most_total)] +struct HexlifyArgs { + data: Value, + #[from_args(default)] + sep: Option, + #[from_args(default = 1)] + bytes_per_sep: i32, +} + +/// The same shape under the `b2a_hex` name, which its signature errors report. +#[derive(FromArgs)] +#[from_args(name = "b2a_hex", style = c_named, at_most_total)] +struct B2aHexArgs { + data: Value, + #[from_args(default)] + sep: Option, + #[from_args(default = 1)] + bytes_per_sep: i32, +} + +/// Argument shape for `b2a_base64(data, *, newline=True)`. +#[derive(FromArgs)] +#[from_args(name = "b2a_base64", style = c_named)] +struct B2aBase64Args { + #[from_args(pos_only)] + data: Value, + #[from_args(kw_only, default = Value::Bool(true))] + newline: Value, +} + +/// Argument shape for `a2b_base64(data, *, strict_mode=False)`. +#[derive(FromArgs)] +#[from_args(name = "a2b_base64", style = c_named)] +struct A2bBase64Args { + #[from_args(pos_only)] + data: Value, + #[from_args(kw_only, default = Value::Bool(false))] + strict_mode: Value, +} + +/// Argument shape for `crc32(data, crc=0)` — positional-only, so keywords are +/// rejected outright with the module-qualified name. +#[derive(FromArgs)] +#[from_args(name = "crc32", style = unpack, kwarg_error_name = "binascii.crc32")] +struct Crc32Args { + #[from_args(pos_only)] + data: Value, + // Absent rather than `None`: CPython's `crc` defaults to unset, so an + // explicit `None` reaches the integer conversion and is rejected there. + #[from_args(pos_only, default)] + crc: Option, +} + +/// Argument shape for `crc_hqx(data, crc)` — like `crc32`, but with `crc` +/// required rather than defaulted. +#[derive(FromArgs)] +#[from_args(name = "crc_hqx", style = unpack, kwarg_error_name = "binascii.crc_hqx")] +struct CrcHqxArgs { + #[from_args(pos_only)] + data: Value, + #[from_args(pos_only)] + crc: Value, +} + +/// Argument shape for `b2a_uu(data, *, backtick=False)`. +#[derive(FromArgs)] +#[from_args(name = "b2a_uu", style = c_named)] +struct B2aUuArgs { + #[from_args(pos_only)] + data: Value, + #[from_args(kw_only, default = Value::Bool(false))] + backtick: Value, +} + +/// Argument shape for `b2a_qp(data, quotetabs=False, istext=True, header=False)`, +/// whose three flags are all positional-or-keyword. +#[derive(FromArgs)] +#[from_args(name = "b2a_qp", style = c_named, at_most_total)] +struct B2aQpArgs { + data: Value, + #[from_args(default = Value::Bool(false))] + quotetabs: Value, + #[from_args(default = Value::Bool(true))] + istext: Value, + #[from_args(default = Value::Bool(false))] + header: Value, +} + +/// Argument shape for `a2b_qp(data, header=False)`. +#[derive(FromArgs)] +#[from_args(name = "a2b_qp", style = c_named, at_most_total)] +struct A2bQpArgs { + data: Value, + #[from_args(default = Value::Bool(false))] + header: Value, +} + +/// Reduces an `int` to the `unsigned int` CPython's `I` format takes, which +/// wraps modulo 2**32 rather than rejecting a value out of range — so a +/// negative or huge `crc` seed is accepted, as CPython accepts it. +fn wrapping_u32(value: &Value, vm: &VM<'_>) -> RunResult { + match value.py_value(vm) { + PyValue::Int(integer) => Ok(integer.wrapping_u32(vm)), + PyValue::Bool(value) => Ok(u32::from(value)), + _ => Err(ExcType::type_error_not_integer(&value.py_type_name(vm))), + } +} + +/// Encodes bytes as lowercase hex, inserting `sep` every `bytes_per_sep` bytes. +/// +/// A positive `bytes_per_sep` groups from the right, so any short group leads; +/// a negative one groups from the left. Zero, or no separator, means none. +fn hex_encode(data: &[u8], sep: Option, bytes_per_sep: i32, tracker: &ResourceTracker) -> RunResult> { + let group = match sep { + Some(_) if bytes_per_sep != 0 && !data.is_empty() => usize::try_from(bytes_per_sep.unsigned_abs()) + .expect("u32 fits usize on supported targets") + .min(data.len()), + // Without a separator, or with an empty input, emit one flat run. + _ => data.len().max(1), + }; + // Groups are measured from the right when positive, so the leading group + // absorbs the remainder. + let lead = if bytes_per_sep > 0 { + match data.len() % group { + 0 => group, + remainder => remainder, + } + } else { + group + }; + + let capacity = data.len() * 2 + data.len() / group; + check_estimated_size(capacity, tracker)?; + let mut out = Vec::with_capacity(capacity); + for (index, byte) in data.iter().enumerate() { + if let Some(sep) = sep + && (index == lead || (index > lead && (index - lead) % group == 0)) + { + out.push(sep); + } + out.push(HEX_DIGITS[usize::from(byte >> 4)]); + out.push(HEX_DIGITS[usize::from(byte & 0x0f)]); + } + Ok(out) +} + +/// Decodes hex of either case, CPython's `unhexlify`. +/// +/// Written as a loop rather than a `collect`: collecting into a `Result` +/// erases the iterator's lower size hint, so the output would grow by +/// doubling instead of being reserved once. +fn hex_decode(data: &[u8]) -> RunResult> { + if data.len().is_multiple_of(2) { + let mut out = Vec::with_capacity(data.len() / 2); + for pair in data.as_chunks::<2>().0 { + match (hex_digit(pair[0]), hex_digit(pair[1])) { + (Some(hi), Some(lo)) => out.push((hi << 4) | lo), + _ => return Err(binascii_error("Non-hexadecimal digit found")), + } + } + Ok(out) + } else { + Err(binascii_error("Odd-length string")) + } +} + +/// Maps a hex digit of either case to its value, `None` for anything else. +fn hex_digit(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +/// Extracts `hexlify`'s separator: one byte, from a `bytes` or a `str` whose +/// single character is Latin-1, which is what CPython's `sep` accepts. +/// +/// CPython measures the length before it looks at the type, so an unsized +/// separator reports "has no len()" and a sized one of the wrong length is a +/// `ValueError` — "sep must be str or bytes." only applies to a sized object +/// of length one. `None` is not "no separator": omitting `sep` leaves it +/// unset, so an explicit `None` fails the length check as any other object. +fn hex_separator(sep: Option<&Value>, vm: &VM<'_>) -> RunResult> { + let Some(sep) = sep else { + return Ok(None); + }; + let length = sep + .py_len(vm) + .ok_or_else(|| ExcType::type_error(format!("object of type '{}' has no len()", sep.py_type_name(vm))))?; + + if length != 1 { + Err(value_error("sep must be length 1.")) + } else if sep.is_str(vm.heap) { + // Latin-1, not ASCII: `hexlify` returns bytes, so CPython only rejects + // a character that does not fit a byte, under an "ASCII" message. + u8::try_from(u32::from(sep.to_str(vm)?.chars().next().expect("one character"))) + .map(Some) + .map_err(|_| value_error("sep must be ASCII.")) + } else if is_bytes(sep, vm) { + Ok(Some(encode_input(sep, vm)?[0])) + } else { + Err(ExcType::type_error("sep must be str or bytes.")) + } +} + +/// Whether a value is `bytes`, which is all `hexlify` accepts as a separator +/// besides `str` — a buffer that `encode_input` would take is still rejected. +fn is_bytes(value: &Value, vm: &VM<'_>) -> bool { + match value { + Value::InternBytes(_) => true, + Value::Ref(heap_id) => matches!(vm.heap.get(*heap_id), HeapData::Bytes(_)), + _ => false, + } +} + +/// The `ValueError`s `hexlify` raises for a malformed separator, whose +/// messages end in a full stop as CPython's do. +fn value_error(message: &'static str) -> RunError { + SimpleException::new_msg(ExcType::ValueError, message).into() +} + +/// Computes the CRC-32 of `data`, continuing from `seed`. +/// +/// The standard reflected polynomial (`0xedb88320`), computed a nibble at a +/// time so the table stays 16 entries rather than 256. +fn crc32(data: &[u8], seed: u32) -> u32 { + const NIBBLE_TABLE: [u32; 16] = [ + 0x0000_0000, + 0x1db7_1064, + 0x3b6e_20c8, + 0x26d9_30ac, + 0x76dc_4190, + 0x6b6b_51f4, + 0x4db2_6158, + 0x5005_713c, + 0xedb8_8320, + 0xf00f_9344, + 0xd6d6_a3e8, + 0xcb61_b38c, + 0x9b64_c2b0, + 0x86d3_d2d4, + 0xa00a_e278, + 0xbdbd_f21c, + ]; + + let mut crc = !seed; + for byte in data { + crc ^= u32::from(*byte); + crc = (crc >> 4) ^ NIBBLE_TABLE[usize::try_from(crc & 0x0f).expect("nibble fits usize")]; + crc = (crc >> 4) ^ NIBBLE_TABLE[usize::try_from(crc & 0x0f).expect("nibble fits usize")]; + } + !crc +} + +/// Computes the CRC-16 of `data`, continuing from `seed`. +/// +/// CRC-16/XMODEM: polynomial `0x1021`, unreflected, no final xor — the +/// checksum BinHex 4.0 carried, which `crc_hqx` outlived. +fn crc_hqx(data: &[u8], seed: u16) -> u16 { + let mut crc = seed; + for byte in data { + crc ^= u16::from(*byte) << 8; + for _ in 0..8 { + crc = if crc & 0x8000 == 0 { + crc << 1 + } else { + (crc << 1) ^ 0x1021 + }; + } + } + crc +} + +/// The most bytes one uuencoded line can hold, since the leading length byte +/// only spans the 6 bits `' '..='`'` encodes. +const UU_MAX_LINE: usize = 45; + +/// Encodes one uuencoded line: a length byte, the data in 6-bit groups, and a +/// trailing newline. +/// +/// `backtick` picks which of the two conventions spells a zero group — the +/// historic space, or the backtick that survives a mail gateway trimming +/// trailing whitespace. +fn uu_encode(data: &[u8], backtick: bool) -> RunResult> { + if data.len() > UU_MAX_LINE { + return Err(binascii_error("At most 45 bytes at once")); + } + // The length byte is a group like any other, so `backtick` reaches it too: + // an empty input encodes as a lone backtick rather than a lone space. + let sextet = |value: u8| match (value & 0x3f, backtick) { + (0, true) => b'`', + (value, _) => value + b' ', + }; + + let mut out = Vec::with_capacity(1 + data.len().div_ceil(3) * 4 + 1); + out.push(sextet(u8::try_from(data.len()).expect("at most 45"))); + for chunk in data.chunks(3) { + // Short chunks pad with zero bytes, which the length byte tells the + // decoder to discard. + let word = u32::from_be_bytes([0, chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)]); + for shift in [18, 12, 6, 0] { + out.push(sextet(u8::try_from((word >> shift) & 0x3f).expect("six bits"))); + } + } + out.push(b'\n'); + Ok(out) +} + +/// Decodes one uuencoded line. +/// +/// A line shorter than its length byte claims is zero-padded rather than +/// rejected, matching CPython — only a character outside the alphabet, or +/// non-whitespace left over once the promised bytes are decoded, is an error. +fn uu_decode(data: &[u8]) -> RunResult> { + let Some((length_byte, mut rest)) = data.split_first() else { + return Err(binascii_error("Missing length byte")); + }; + let remaining = usize::from(length_byte.wrapping_sub(b' ') & 0x3f); + + let mut out = Vec::with_capacity(remaining); + let mut leftover: u32 = 0; + let mut bits = 0_u32; + while out.len() < remaining { + let sextet = match rest.split_first() { + // A newline stands for spaces an encoder ate off the end of the + // line, so it decodes as a zero group like a space would — and is + // consumed, leaving anything after it to be decoded in turn. + Some((b'\n' | b'\r', tail)) => { + rest = tail; + 0 + } + // Past the end of the line the padding costs no input. + None => 0, + Some((byte, tail)) => { + rest = tail; + match byte { + b' ' | b'`' => 0, + b'!'..=b'_' => byte - b' ', + _ => return Err(binascii_error("Illegal char")), + } + } + }; + leftover = (leftover << 6) | u32::from(sextet); + bits += 6; + if bits >= 8 { + bits -= 8; + out.push(u8::try_from((leftover >> bits) & 0xff).expect("one byte")); + leftover &= (1 << bits) - 1; + } + } + + if rest.iter().all(|byte| matches!(byte, b' ' | b'`' | b'\n' | b'\r')) { + Ok(out) + } else { + Err(binascii_error("Trailing garbage")) + } +} + +/// The column at which `b2a_qp` soft-wraps, CPython's `MAXLINESIZE`. +const QP_MAX_LINE: usize = 76; + +/// The three flags `b2a_qp` reads, grouped so the encoder's helpers can take +/// them as one argument. +#[derive(Clone, Copy)] +struct QpOptions { + /// Quote tabs and spaces wherever they appear, not just at end of line. + quotetabs: bool, + /// Treat the input as text, so newlines stay literal line breaks. + istext: bool, + /// RFC 2047 header mode: a space becomes `_`, and `_` is itself quoted. + header: bool, +} + +/// Encodes bytes as quoted-printable. +/// +/// Soft line breaks (`=` then the newline) keep every line under +/// [`QP_MAX_LINE`]; which newline they use is decided once, up front, by +/// whether the input's first line ends `\r\n` — so mixed endings are +/// normalised to whichever came first, as CPython's own does. +fn qp_encode(data: &[u8], options: QpOptions, tracker: &ResourceTracker) -> RunResult> { + // Independent of `istext`, as CPython's own `memchr` for it is. + let crlf = data + .iter() + .position(|byte| *byte == b'\n') + .is_some_and(|index| index > 0 && data[index - 1] == b'\r'); + let capacity = qp_encoded_size(data, options, crlf); + check_estimated_size(capacity, tracker)?; + + let mut out = Vec::with_capacity(capacity); + let mut linelen = 0; + let mut index = 0; + while index < data.len() { + let byte = data[index]; + if qp_needs_quoting(data, index, linelen, options) { + // The escape is three columns wide and may not be split, so it + // moves to the next line whole. + if linelen + 3 >= QP_MAX_LINE { + qp_soft_break(&mut out, crlf); + linelen = 0; + } + out.push(b'='); + out.extend_from_slice(&qp_hex(byte)); + linelen += 3; + index += 1; + } else if options.istext && (byte == b'\n' || (byte == b'\r' && data.get(index + 1) == Some(&b'\n'))) { + // A literal line break, but trailing whitespace before it would be + // eaten in transit, so the last byte written is quoted after all. + if let Some(last @ (b' ' | b'\t')) = out.last().copied() { + out.pop(); + out.push(b'='); + out.extend_from_slice(&qp_hex(last)); + } + if crlf { + out.push(b'\r'); + } + out.push(b'\n'); + linelen = 0; + index += if byte == b'\r' { 2 } else { 1 }; + } else { + // A break right before a newline would be wasted, so it is skipped. + if index + 1 != data.len() && data[index + 1] != b'\n' && linelen + 1 >= QP_MAX_LINE { + qp_soft_break(&mut out, crlf); + linelen = 0; + } + out.push(if options.header && byte == b' ' { b'_' } else { byte }); + linelen += 1; + index += 1; + } + } + Ok(out) +} + +/// Upper bound on what [`qp_encode`] writes, so it can reserve exactly once. +/// +/// A flat bound of the 3.125 bytes per byte a fully escaped input reaches +/// would reject plain text, which encodes to a little over its own length. +/// Counting what can actually expand keeps the bound tight for any input. +fn qp_encoded_size(data: &[u8], options: QpOptions, crlf: bool) -> usize { + // The one position rule that can catch a byte the per-byte rules do not: + // a space or tab last in the input is quoted for being last. + let mut extra = 2 * usize::from(matches!(data.last(), Some(b' ' | b'\t'))); + for (index, byte) in data.iter().enumerate() { + extra += if options.istext && *byte == b'\n' { + // A bare `\n` may become `\r\n`, and a space or tab before the line + // ending is quoted so transit cannot eat it. + let start = if index > 0 && data[index - 1] == b'\r' { + index - 1 + } else { + index + }; + let bare = usize::from(crlf && start == index); + let trailing = start > 0 && matches!(data[start - 1], b' ' | b'\t'); + bare + 2 * usize::from(trailing) + } else if qp_always_quotes(*byte, options) + || (*byte == b'.' && matches!(data.get(index + 1), None | Some(b'\n' | b'\r' | b'\0'))) + { + // The dot rule also needs the dot to start a line; counting it + // regardless keeps this a bound without tracking line position. + 2 + } else { + 0 + }; + } + let body = data.len().saturating_add(extra); + // A soft break needs three bytes, and cannot fire before column 73. + let breaks = body / (QP_MAX_LINE - 3) + 1; + body.saturating_add(breaks.saturating_mul(3)) +} + +/// Whether the byte at `index` has to be written as an `=XX` escape. +/// +/// Beyond the obvious (non-printable, `=`, and `_` in header mode) this covers +/// three positional rules: trailing whitespace, which would not survive +/// transit; whitespace anywhere under `quotetabs`; and a `.` alone on a line, +/// which an SMTP relay would read as the end of the message. +fn qp_needs_quoting(data: &[u8], index: usize, linelen: usize, options: QpOptions) -> bool { + let byte = data[index]; + let last = index + 1 == data.len(); + let leading_dot = byte == b'.' && linelen == 0 && matches!(data.get(index + 1), None | Some(b'\n' | b'\r' | b'\0')); + + qp_always_quotes(byte, options) || leading_dot || (matches!(byte, b'\t' | b' ') && last) +} + +/// The half of [`qp_needs_quoting`] that depends only on the byte. +/// +/// Split out so [`qp_encoded_size`] shares one copy of the rules. +fn qp_always_quotes(byte: u8, options: QpOptions) -> bool { + byte > 126 + || byte == b'=' + || (options.header && byte == b'_') + || (!options.istext && matches!(byte, b'\r' | b'\n')) + || (byte < 33 && byte != b'\r' && byte != b'\n' && (options.quotetabs || !matches!(byte, b'\t' | b' '))) +} + +/// Writes a soft line break — an `=` swallowed by the decoder, then the +/// newline the rest of the output uses. +fn qp_soft_break(out: &mut Vec, crlf: bool) { + out.push(b'='); + if crlf { + out.push(b'\r'); + } + out.push(b'\n'); +} + +/// The two uppercase hex digits an `=XX` escape carries. +fn qp_hex(byte: u8) -> [u8; 2] { + const UPPER_HEX: &[u8; 16] = b"0123456789ABCDEF"; + [UPPER_HEX[usize::from(byte >> 4)], UPPER_HEX[usize::from(byte & 0x0f)]] +} + +/// Decodes quoted-printable. +/// +/// Never fails: a malformed escape is copied through as the literal text it +/// was, which is what lets the format survive a mangled message. +fn qp_decode(data: &[u8], header: bool) -> Vec { + let mut out = Vec::with_capacity(data.len()); + let mut index = 0; + while index < data.len() { + match data[index] { + b'=' => { + index += 1; + match data.get(index) { + // A trailing `=` is dropped along with the rest of the line. + None => break, + Some(b'\n' | b'\r') => { + // A soft break runs to the newline, so a bare `\r` (or + // a `\r\r\n`) swallows everything up to it. + while index < data.len() && data[index] != b'\n' { + index += 1; + } + index += usize::from(index < data.len()); + } + // `==` is not an escape, but broken encoders emit it. + Some(b'=') => { + out.push(b'='); + index += 1; + } + Some(first) => match (hex_digit(*first), data.get(index + 1).and_then(|b| hex_digit(*b))) { + (Some(hi), Some(lo)) => { + out.push((hi << 4) | lo); + index += 2; + } + // Not a complete escape: the `=` stands for itself and + // the following bytes are re-read as ordinary text. + _ => out.push(b'='), + }, + } + } + b'_' if header => { + out.push(b' '); + index += 1; + } + byte => { + out.push(byte); + index += 1; + } + } + } + out +} diff --git a/crates/bashkit-monty/src/modules/bisect.rs b/crates/bashkit-monty/src/modules/bisect.rs new file mode 100644 index 000000000..f586477eb --- /dev/null +++ b/crates/bashkit-monty/src/modules/bisect.rs @@ -0,0 +1,242 @@ +//! Binary search and sorted insertion, matching CPython's `_bisect` accelerator. + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + expressions::CmpOperator, + heap::{HeapData, HeapId, HeapReadOutput}, + intern::StaticStrings, + modules::ModuleFunctions, + types::{Module, PyTrait, Type}, + value::{EitherStr, Value}, +}; + +/// The aliases share the same callable value as their canonical function. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum BisectFunctions { + BisectLeft, + BisectRight, + InsortLeft, + InsortRight, +} + +/// Creates the module and its two aliases. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Bisect, vm.interns); + for (name, function) in [ + (StaticStrings::BisectLeft, BisectFunctions::BisectLeft), + (StaticStrings::BisectRight, BisectFunctions::BisectRight), + (StaticStrings::Bisect, BisectFunctions::BisectRight), + (StaticStrings::InsortLeft, BisectFunctions::InsortLeft), + (StaticStrings::InsortRight, BisectFunctions::InsortRight), + (StaticStrings::Insort, BisectFunctions::InsortRight), + ] { + module.set_attr(name, Value::ModuleFunction(ModuleFunctions::Bisect(function)), vm); + } + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Clinic's nullable slice-index conversion for `hi`; -1 means the length, +/// even when explicitly supplied. Other negative values are not normalized. +fn convert_hi(value: &Value, vm: &mut VM<'_>) -> RunResult { + if matches!(value, Value::None) { + return Ok(-1); + } + let Some(index) = value.py_index_impl(vm)? else { + return Err(ExcType::type_error(format!( + "argument should be integer or None, not '{}'", + value.py_type_name(vm) + ))); + }; + // The index protocol validated an integer; only overflow can fail here. + // CPython names the original object, including a user __index__ provider. + let result = index.as_int(vm).map_err(|_| { + ExcType::overflow_error(format!( + "cannot fit '{}' into an index-sized integer", + value.py_type_name(vm) + )) + }); + index.drop_with(vm); + result +} + +// Separate derives preserve each function's name in Clinic binding errors. +macro_rules! arguments { + ($ty:ident, $name:literal) => { + #[derive(FromArgs)] + #[from_args(name = $name, style = c_named)] + struct $ty { + a: Value, + x: Value, + #[from_args(default = Value::Int(0))] + lo: Value, + #[from_args(default = Value::None)] + hi: Value, + #[from_args(kw_only, default = Value::None)] + key: Value, + } + }; +} +arguments!(BisectLeftArgs, "bisect_left"); +arguments!(BisectRightArgs, "bisect_right"); +arguments!(InsortLeftArgs, "insort_left"); +arguments!(InsortRightArgs, "insort_right"); + +/// Dispatch with shared search logic and CPython's key evaluation order. +pub(super) fn call(vm: &mut VM<'_>, function: BisectFunctions, args: ArgValues) -> RunResult { + let (a, x, lo, hi, key) = match function { + BisectFunctions::BisectLeft => { + let BisectLeftArgs { a, x, lo, hi, key } = BisectLeftArgs::from_args(args, vm)?; + (a, x, lo, hi, key) + } + BisectFunctions::BisectRight => { + let BisectRightArgs { a, x, lo, hi, key } = BisectRightArgs::from_args(args, vm)?; + (a, x, lo, hi, key) + } + BisectFunctions::InsortLeft => { + let InsortLeftArgs { a, x, lo, hi, key } = InsortLeftArgs::from_args(args, vm)?; + (a, x, lo, hi, key) + } + BisectFunctions::InsortRight => { + let InsortRightArgs { a, x, lo, hi, key } = InsortRightArgs::from_args(args, vm)?; + (a, x, lo, hi, key) + } + }; + defer_drop!(a, vm); + defer_drop!(x, vm); + defer_drop!(key, vm); + defer_drop!(lo, vm); + defer_drop!(hi, vm); + // Clinic validates the complete signature before converting lo, then hi. + // Keeping raw fields in FromArgs makes unknown/duplicate kwargs win over + // conversion errors, unlike PyArg_ParseTupleAndKeywords-style extraction. + let lo = lo.as_int(vm)?; + let hi = convert_hi(hi, vm)?; + let insert = matches!(function, BisectFunctions::InsortLeft | BisectFunctions::InsortRight); + let left = matches!(function, BisectFunctions::BisectLeft | BisectFunctions::InsortLeft); + let search_x = if insert && !matches!(key, Value::None) { + let argument = x.clone_with_heap(vm); + vm.evaluate_function(key, ArgValues::One(argument))? + } else { + x.clone_with_heap(vm) + }; + defer_drop!(search_x, vm); + let index = search(vm, a, search_x, (lo, hi), key, left)?; + if insert { + let Value::Ref(_) = a else { + return Err(ExcType::attribute_error(a.py_type_name(vm), "insert")); + }; + let argument = x.clone_with_heap(vm); + let result = a.py_value(vm).py_call_attr( + vm, + &EitherStr::Interned(vm.interns.intern_static(StaticStrings::Insert)), + ArgValues::Two(Value::Int(index), argument), + )?; + let CallResult::Value(result) = result else { + unreachable!("built-in sequence insert methods are synchronous"); + }; + result.drop_with(vm); + Ok(Value::None) + } else { + Ok(Value::Int(index)) + } +} + +/// Search without retaining a borrowed container across Python callbacks. +fn search(vm: &mut VM<'_>, a: &Value, x: &Value, bounds: (i64, i64), key: &Value, left: bool) -> RunResult { + let (mut lo, mut hi) = bounds; + if lo < 0 { + return Err(ExcType::value_error("lo must be non-negative")); + } + if hi == -1 { + // Ranges can exceed usize without allocating elements. Use their exact + // length so Monty's fixed i64 index limit also applies on 32-bit wasm. + hi = if let Some(HeapReadOutput::Range(range)) = a.read_heap(vm) { + i64::try_from(range.get(vm.heap).len_i128()).map_err(|_| ExcType::overflow_c_ssize_t())? + } else { + let len = a + .py_len(vm) + .ok_or_else(|| ExcType::type_error(format!("object of type '{}' has no len()", a.py_type_name(vm))))?; + i64::try_from(len).map_err(|_| ExcType::overflow_c_ssize_t())? + }; + } + // _bisect obtains sq_item even when the search interval is empty. + match a.py_type(vm) { + Type::List + | Type::Tuple + | Type::NamedTuple + | Type::Str + | Type::Bytes + | Type::Range + | Type::Deque + | Type::Counter => {} + Type::Dict | Type::DefaultDict => { + return Err(ExcType::type_error(format!("{} is not a sequence", a.py_type_name(vm)))); + } + _ => { + return Err(ExcType::type_error(format!( + "'{}' object does not support indexing", + a.py_type_name(vm) + ))); + } + } + let mut steps = 0; + while lo < hi { + vm.heap.tracker.check_time_every(steps)?; + steps += 1; + let mid = lo + (hi - lo) / 2; + let item = a.py_getitem(&Value::Int(mid), vm)?; + let item = if matches!(key, Value::None) { + item + } else { + vm.evaluate_function(key, ArgValues::One(item))? + }; + defer_drop!(item, vm); + let less = if left { + less_than(vm, item, x)? + } else { + less_than(vm, x, item)? + }; + if less == left { + lo = mid + 1; + } else { + hi = mid; + } + } + Ok(lo) +} + +/// Lists and tuples compare the first unequal pair with `<`, rather than +/// deriving `<` from a three-way ordering. This preserves identity/equality +/// shortcuts (including NaNs) and reports errors on the offending elements. +fn less_than(vm: &mut VM<'_>, a: &Value, b: &Value) -> RunResult { + if !matches!( + (a.py_type(vm), b.py_type(vm)), + (Type::List, Type::List) | (Type::Tuple | Type::NamedTuple, Type::Tuple | Type::NamedTuple) + ) { + return vm.cmp_values(CmpOperator::Lt, a, b); + } + let mut guard = vm.recursion_guard()?; + let vm = &mut *guard; + let mut i = 0; + loop { + let a_len = a.py_len(vm).expect("sequence has length"); + let b_len = b.py_len(vm).expect("sequence has length"); + if i >= a_len.min(b_len) { + return Ok(a_len < b_len); + } + vm.heap.tracker.check_time_every(i)?; + let index = Value::Int(i64::try_from(i).expect("sequence index fits i64")); + let av = a.py_getitem(&index, vm)?; + defer_drop!(av, vm); + let bv = b.py_getitem(&index, vm)?; + defer_drop!(bv, vm); + if !av.py_eq(bv, vm)? { + return less_than(vm, av, bv); + } + i += 1; + } +} diff --git a/crates/bashkit-monty/src/modules/collections/counter.rs b/crates/bashkit-monty/src/modules/collections/counter.rs new file mode 100644 index 000000000..3e251b3a7 --- /dev/null +++ b/crates/bashkit-monty/src/modules/collections/counter.rs @@ -0,0 +1,910 @@ +//! Runtime behaviour for `collections.Counter`. +//! +//! A Counter is a `dict` tagged with a `Counter` [`DictKind`](crate::types::DictKind); +//! operations receive the Counter's heap object handle but re-read its dictionary +//! through the VM whenever Python execution can intervene. This is why the logic +//! lives beside the module surface instead of in `types/dict.rs`. The dict method +//! surface is inherited as-is — only the +//! missing-key read (`0`, no insert), `most_common`/`elements`/`total`/`update`/ +//! `subtract`, and the `+ - & |` algebra are added on top. + +use std::{cmp::Ordering, mem}; + +use smallvec::smallvec; + +use crate::{ + args::{ArgValues, KwargsValues}, + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{DropGuard, DropWithContext, HeapData, HeapObjectRead, HeapReadOutput}, + py_value::PyValue, + resource_checks::check_repeat_size, + types::{Dict, List, PyTrait, allocate_tuple, iter::collect_owned_iterable, py_trait::CmpOrder}, + value::{VALUE_SIZE, Value}, +}; + +/// Adds (or subtracts) `delta` from two counts, with CPython's operator wording +/// when the operand types have no numeric `+`/`-`. +/// +/// A Counter is a plain dict, so its values are ordinary Python objects and +/// CPython never coerces them — floats and big ints must survive arithmetic +/// intact. Both operands are borrowed; the result is a fresh owned `Value`. +fn count_arith(lhs: &Value, rhs: &Value, subtract: bool, vm: &mut VM<'_>) -> RunResult { + // `py_add`/`py_sub` already raise the exact `binary_type_error(op, ...)` this + // needs when the counts aren't addable, so delegate rather than re-derive it. + if subtract { + lhs.py_sub(rhs, vm) + } else { + lhs.py_add(rhs, vm) + } +} + +/// A Python ordering comparison used inside the `Counter` algebra. +/// +/// CPython's Counter methods run different comparisons (`<=` for `<=`/`<`, `>=` +/// for `>=`/`>`, `<` when picking a min/max, `>` for the `> 0` keep-positive +/// filter), and the operator embedded in an unorderable-count `TypeError` is the +/// one that actually ran — so the caller picks the variant to keep CPython's +/// wording. It also decides how `NaN` (an *unordered* pair) resolves. +#[derive(Clone, Copy)] +enum CountCmp { + Le, + Lt, + Ge, + Gt, +} + +impl CountCmp { + /// The operator symbol CPython names in the `TypeError`. + fn symbol(self) -> &'static str { + match self { + Self::Le => "<=", + Self::Lt => "<", + Self::Ge => ">=", + Self::Gt => ">", + } + } + + /// Whether `lhs rhs` holds given the three-way `ordering` of the pair. + fn holds(self, ordering: Ordering) -> bool { + match self { + Self::Le => ordering != Ordering::Greater, + Self::Lt => ordering == Ordering::Less, + Self::Ge => ordering != Ordering::Less, + Self::Gt => ordering == Ordering::Greater, + } + } +} + +/// Evaluates `lhs rhs` between two counts, raising CPython's operator- +/// specific `TypeError` when the pair has no ordering at all. +/// +/// `NaN` makes a pair *unordered* rather than incomparable, and every IEEE +/// ordering comparison against `NaN` is false — so `nan <= nan` is `false`, which +/// is exactly what CPython's element-wise `Counter` comparisons observe. +fn count_holds(lhs: &Value, rhs: &Value, op: CountCmp, vm: &mut VM<'_>) -> RunResult { + match lhs.py_cmp(rhs, vm)? { + CmpOrder::Ordered(ordering) => Ok(op.holds(ordering)), + CmpOrder::Unordered => Ok(false), + CmpOrder::Incomparable => Err(ExcType::type_error_ordering( + op.symbol(), + &lhs.py_type_name(vm), + &rhs.py_type_name(vm), + )), + } +} + +/// Orders two counts for *sorting* (`most_common`, Counter repr), raising the +/// sort's `<` `TypeError` when they are incomparable. +/// +/// Unlike the algebra's [`count_holds`], a `NaN` pair is treated as **equal** +/// here: Python's `sorted`/`heapq` never raise on `NaN`, they just leave it +/// wherever the (ill-defined for `NaN`) ordering happens to place it. +fn count_sort_cmp(lhs: &Value, rhs: &Value, vm: &mut VM<'_>) -> RunResult { + match lhs.py_cmp(rhs, vm)? { + CmpOrder::Ordered(ordering) => Ok(ordering), + CmpOrder::Unordered => Ok(Ordering::Equal), + CmpOrder::Incomparable => Err(ExcType::type_error_ordering( + "<", + &lhs.py_type_name(vm), + &rhs.py_type_name(vm), + )), + } +} + +/// Whether a count is strictly greater than zero (the `Counter` algebra keeps +/// only positive results). CPython's `_keep_positive` filters with `count > 0`, +/// so an unorderable count reports `>` and a `NaN` count is not positive. +fn count_is_positive(value: &Value, vm: &mut VM<'_>) -> RunResult { + count_holds(value, &Value::Int(0), CountCmp::Gt, vm) +} + +/// Converts a count to a repetition length for `elements()`. +/// +/// CPython feeds the count to `itertools.repeat`, which requires a whole +/// number, so a float count raises rather than being truncated. Negative counts +/// yield `0` (the element is skipped). +/// +/// A count outside `ssize_t` raises `OverflowError` *regardless of sign* — +/// CPython converts before it inspects the sign, so a huge negative count is +/// rejected rather than skipped. That boundary is exactly Monty's `Int` +/// (`i64`) / `LongInt` split, so the type of the count decides it. +fn count_repeat_len(value: &Value, vm: &VM<'_>) -> RunResult { + match value { + Value::Int(i) => Ok(usize::try_from(*i).unwrap_or(0)), + Value::Bool(b) => Ok(usize::from(*b)), + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::LongInt(_)) => Err(ExcType::overflow_c_ssize_t()), + Value::InternLongInt(_) => Err(ExcType::overflow_c_ssize_t()), + other => Err(ExcType::type_error_not_an_integer(&other.py_type_name(vm))), + } +} + +/// Adds `delta` to the count for `key` in `counter` (creating the key at +/// `0 + delta` if absent). Takes ownership of `key`, which the dict keeps +/// on success; `delta` is only read, so the caller retains it. +/// +/// `delta_first` selects the operand order for the addition: CPython's mapping +/// update computes `count + self.get(elem, 0)` while element counting computes +/// `self.get(elem, 0) + 1`. The two agree numerically, but the left operand is +/// the one named in a `TypeError`. Ignored when `subtract` is set, which is +/// always `self.get(elem, 0) - count`. +fn counter_bump<'h>( + counter: &mut HeapObjectRead<'h, Dict>, + key: Value, + delta: &Value, + subtract: bool, + delta_first: bool, + vm: &mut VM<'h>, +) -> RunResult<()> { + // Either failure below — `dict_get` hashing an unhashable key (e.g. + // `Counter([[1]])`), or the arithmetic on a non-numeric count — releases the + // key through the guard; only the store at the end takes it out again. + let mut key_guard = DropGuard::new(key, vm); + let (key, vm) = key_guard.as_parts_mut(); + let base = counter.dict_get(key, vm)?.unwrap_or(Value::Int(0)); + let total = if subtract || !delta_first { + count_arith(&base, delta, subtract, vm) + } else { + count_arith(delta, &base, false, vm) + }; + base.drop_with(vm); + let total = total?; + let (key, vm) = key_guard.into_parts(); + if let Some(old) = counter.set(key, total, vm)? { + old.drop_with(vm); + } + Ok(()) +} + +/// Implements `Counter.update`/`subtract` and construction: folds counts from +/// `source` (a mapping adds its values; any other iterable counts occurrences) +/// and from `kwargs` into `counter`. `subtract` negates the deltas. +/// +/// Consumes `source` and `kwargs`. +pub(crate) fn counter_update<'h>( + counter: &mut HeapObjectRead<'h, Dict>, + source: Option, + kwargs: KwargsValues, + subtract: bool, + vm: &mut VM<'h>, +) -> RunResult<()> { + // An explicit `None` source is a no-op (CPython skips it before dispatch), so + // `Counter(None)` and `c.update(None)` only apply the keyword counts below. + if let Some(source) = source + && !matches!(source, Value::None) + { + let is_mapping = matches!(&source, Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::Dict(_))); + if is_mapping { + let Value::Ref(src_id) = source else { + unreachable!("mapping is a ref"); + }; + // Snapshot (key, delta) pairs first so `c.update(c)` is well-defined. + let pairs: Vec<(Value, Value)> = { + let Some(src) = vm.heap.read_as::(src_id) else { + unreachable!("mapping is a dict"); + }; + let src = src.get(vm.heap); + src.iter() + .map(|(k, v)| (k.clone_with_heap(vm.heap), v.clone_with_heap(vm.heap))) + .collect() + }; + source.drop_with(vm); + counter_merge_mapping(counter, pairs, subtract, vm)?; + } else { + // `_count_elements`: `self[elem] = self_get(elem, 0) + 1`, so the + // existing count is the left operand here. + let items = collect_owned_iterable::>(source, vm)?.into_iter(); + // A bump can fail on an unhashable item; the guard releases the + // items it never reached. + defer_drop_mut!(items, vm); + for item in items.by_ref() { + counter_bump(counter, item, &Value::Int(1), subtract, false, vm)?; + } + } + } + + // Keyword counts, e.g. `Counter(a=2)` / `c.update(a=5)`. CPython recurses + // via `self.update(kwds)`, so these follow the mapping path — including the + // empty-Counter fast path, re-evaluated after the iterable was folded in. + let kwarg_pairs = counter_kwarg_deltas(kwargs); + counter_merge_mapping(counter, kwarg_pairs, subtract, vm)?; + Ok(()) +} + +/// Folds mapping `(key, count)` pairs into `counter`. +/// +/// Mirrors `Counter.update`'s mapping branch: into a **non-empty** Counter each +/// count is added as `count + self.get(elem, 0)` (the incoming count is the left +/// operand, which is what CPython's error messages name), while into an **empty** +/// one CPython takes a `super().update()` fast path that stores values verbatim +/// — which is why `Counter({'a': True})` keeps `True` rather than `1`. +/// `subtract` has no fast path and always computes `self.get(elem, 0) - count`. +fn counter_merge_mapping<'h>( + counter: &mut HeapObjectRead<'h, Dict>, + pairs: Vec<(Value, Value)>, + subtract: bool, + vm: &mut VM<'h>, +) -> RunResult<()> { + let is_empty = counter.get(vm.heap).is_empty(); + // A merge can fail on an unhashable key or a non-numeric count; the guard + // releases the pairs it never reached. + let pairs = pairs.into_iter(); + defer_drop_mut!(pairs, vm); + for (key, count) in pairs.by_ref() { + // The fast path stores `count` itself, while a bump only reads it — so + // that branch owns the release. + if is_empty && !subtract { + if let Some(old) = counter.set(key, count, vm)? { + old.drop_with(vm); + } + } else { + let outcome = counter_bump(counter, key, &count, subtract, true, vm); + count.drop_with(vm); + outcome?; + } + } + Ok(()) +} + +/// Converts kwargs into owned `(key_value, count_value)` delta pairs. +fn counter_kwarg_deltas(kwargs: KwargsValues) -> Vec<(Value, Value)> { + match kwargs { + KwargsValues::Empty => Vec::new(), + KwargsValues::Inline(kvs) => kvs.into_iter().map(|(id, v)| (Value::InternString(id), v)).collect(), + KwargsValues::Pairs(kvs) => kvs, + KwargsValues::Dict(dict) => dict.into_iter().collect(), + } +} + +/// `Counter.update`/`subtract` method body: binds `iterable=None, /, **kwargs` +/// and folds the counts in. Returns `None`. +/// +/// The binding is hand-rolled rather than `#[derive(FromArgs)]`: these are +/// pure-Python `def` methods, so CPython's over-arity error counts the implicit +/// `self` (`Counter.update() takes from 1 to 2 positional arguments but 3 were +/// given`), which the derive's `def` family — positional-only, no receiver — +/// cannot express. The `+ 1`s below re-introduce that `self`. +pub(crate) fn counter_update_method<'h>( + counter: &mut HeapObjectRead<'h, Dict>, + args: ArgValues, + subtract: bool, + vm: &mut VM<'h>, +) -> RunResult { + let (mut pos, kwargs) = args.into_parts(); + let total = pos.len(); + let source = (total > 0).then(|| pos.next().expect("len checked")); + // CPython names the specific method (with the `Counter.` qualifier) here. + let name = if subtract { "Counter.subtract" } else { "Counter.update" }; + if total > 1 { + source.drop_with(vm); + pos.drop_with(vm); + kwargs.drop_with(vm); + return Err(ExcType::type_error_too_many_positional_range(name, 1, 2, total + 1, 0)); + } + counter_update(counter, source, kwargs, subtract, vm)?; + Ok(Value::None) +} + +/// `Counter.total()` — the sum of all counts. +/// +/// Sums with real numeric addition (CPython's `sum(self.values())`), so a +/// float or big-int count is preserved in the total rather than truncated. +pub(crate) fn counter_total<'h>(counter: &HeapObjectRead<'h, Dict>, vm: &mut VM<'h>) -> RunResult { + let counts = counter + .get(vm.heap) + .iter() + .map(|(_, count)| count.clone_with_heap(vm.heap)) + .collect::>() + .into_iter(); + // A count that cannot be added raises mid-fold, so both the counts not yet + // folded in and the running total are held by guards that release them. + defer_drop_mut!(counts, vm); + let mut sum_guard = DropGuard::new(Value::Int(0), vm); + for count in counts.by_ref() { + let (sum, vm) = sum_guard.as_parts_mut(); + let next = count_arith(sum, &count, false, vm); + count.drop_with(vm); + // The previous total is replaced rather than dropped in place, so the + // guard always owns exactly one value. + mem::replace(sum, next?).drop_with(vm); + } + Ok(sum_guard.into_inner()) +} + +/// Orders entry indices for `most_common` / Counter repr: count descending, +/// ties in insertion order (the sort is stable). +/// +/// Takes the counts by value because the comparison needs `&mut VM` (big ints +/// live on the heap), which callers cannot hold alongside a `Dict` borrow. +/// Consumes `counts`. +pub(crate) fn counter_order(counts: Vec, vm: &mut VM<'_>) -> RunResult> { + let mut order: Vec = (0..counts.len()).collect(); + // `sort_by` needs an infallible comparator, so a comparison error is stashed + // and reported once the sort finishes; the ordering it produces in that case + // is discarded. + let mut failure = None; + order.sort_by(|&a, &b| { + if failure.is_some() { + return Ordering::Equal; + } + match count_sort_cmp(&counts[b], &counts[a], vm) { + Ok(ordering) => ordering, + Err(e) => { + failure = Some(e); + Ordering::Equal + } + } + }); + counts.drop_with(vm); + match failure { + Some(e) => Err(e), + None => Ok(order), + } +} + +/// `Counter.most_common([n])` — a list of `(element, count)` tuples ordered by +/// count descending (ties in insertion order). `n` omitted/`None` returns all; +/// a non-positive `n` returns an empty list. +pub(crate) fn counter_most_common<'h>( + counter: &HeapObjectRead<'h, Dict>, + args: ArgValues, + vm: &mut VM<'h>, +) -> RunResult { + // Huge positive limits return every item; negative limits return none. + let limit = { + let n_arg = args.get_zero_one_arg("most_common", vm.heap)?; + defer_drop!(n_arg, vm); + match n_arg.as_ref().map(|value| value.py_value(vm)) { + None | Some(PyValue::None) => None, + Some(PyValue::Int(integer)) => Some(integer.collection_limit(vm)), + Some(PyValue::Bool(value)) => Some(usize::from(value)), + Some(other) => return Err(ExcType::type_error_not_integer(&other.py_type_name(vm))), + } + }; + + // CPython's `heapq.nlargest(0, ...)` returns before comparing anything. + if limit == Some(0) { + return Ok(vm.heap.allocate_as(List::new(Vec::new())).into_value()); + } + // Snapshot the entries before ordering: comparing counts can run a user + // `__eq__` that mutates the Counter, so the ordered indices must refer to + // the snapshot. CPython's `sorted(self.items(), ...)` snapshots the same way. + let pairs = counter.clone_all_pairs(vm)?; + defer_drop!(pairs, vm); + let counts = pairs.iter().map(|(_, count)| count.clone_with_heap(vm.heap)).collect(); + let order = counter_order(counts, vm)?; + let take = limit.unwrap_or(order.len()).min(order.len()); + // Below the length, CPython's `heapq.nlargest` compares while iterating the + // live dict, so a comparison that resized it raises there. + if take < pairs.len() && counter.get(vm.heap).len() != pairs.len() { + return Err(ExcType::runtime_error_dict_changed_size()); + } + + let items = order[..take] + .iter() + .map(|&i| { + let (key, count) = &pairs[i]; + allocate_tuple( + smallvec![key.clone_with_heap(vm.heap), count.clone_with_heap(vm.heap)], + vm.heap, + ) + }) + .collect(); + Ok(vm.heap.allocate_as(List::new(items)).into_value()) +} + +/// `Counter.elements()` — a list repeating each element by its count, skipping +/// zero and negative counts (Monty's eager iterator convention returns a list +/// rather than CPython's lazy iterator). +pub(crate) fn counter_elements<'h>( + counter: &HeapObjectRead<'h, Dict>, + args: ArgValues, + vm: &mut VM<'h>, +) -> RunResult { + args.check_zero_args("elements", vm.heap)?; + + // Resolve every repetition length up front: a count that `itertools.repeat` + // rejects — non-integer (TypeError) or outside `ssize_t` (OverflowError) — + // must raise before anything is built. No user code runs here or below, so + // each pass reads the entries under one borrow. + let lengths = { + let vm: &VM<'h> = vm; + counter + .get(vm.heap) + .iter() + .map(|(_, count)| count_repeat_len(count, vm)) + .collect::>>()? + }; + + // Pre-check the total element count against the resource tracker: a single + // large count (e.g. `c['a'] = 10**18`) would otherwise attempt to build a + // multi-exabyte Rust-heap `Vec` before returning a graceful error. + let total = lengths.iter().fold(0usize, |acc, len| acc.saturating_add(*len)); + check_repeat_size(VALUE_SIZE, total, &vm.heap.tracker)?; + + // `Vec::new()` (not `with_capacity(total)`): `total` is attacker-controlled, + // and `check_repeat_size` above is the real guard (it fires before this loop + // whenever a memory limit is set). Pre-reserving would itself panic. + let mut items: Vec = Vec::new(); + for ((key, _), &count) in counter.get(vm.heap).iter().zip(&lengths) { + for _ in 0..count { + items.push(key.clone_with_heap(vm.heap)); + } + } + Ok(vm.heap.allocate_as(List::new(items)).into_value()) +} + +/// The four binary `Counter` algebra operators. +#[derive(Clone, Copy)] +pub(crate) enum CounterOp { + /// `+` — sum counts over the union of keys. + Add, + /// `-` — subtract counts over the union of keys. + Sub, + /// `&` — minimum count over keys present in both. + And, + /// `|` — maximum count over the union of keys. + Or, +} + +/// Computes a binary `Counter` operation, returning a new Counter that keeps +/// only positive counts (CPython's `Counter.__add__` etc.). +pub(crate) fn counter_binary_op<'h>( + lhs: &HeapObjectRead<'h, Dict>, + rhs: &HeapObjectRead<'h, Dict>, + op: CounterOp, + vm: &mut VM<'h>, +) -> RunResult { + let mut result = Dict::new(); + result.make_counter(); + let result = vm.heap.allocate_as(result); + // Guard the freshly allocated result dict: a catchable error below (e.g. + // arithmetic or comparison on non-numeric counts raising `TypeError`) must + // free it, which the bare `?` early-returns would otherwise leak. + let mut result_guard = DropGuard::new(result, vm); + let (result, vm) = result_guard.as_parts_mut(); + let result = result.read(vm.heap); + + // Each operand is snapshotted only when it is about to be consumed: taking + // the right snapshot up front would leak it if folding the left one raised. + match op { + CounterOp::Add => { + let l_pairs = lhs.clone_all_pairs(vm)?; + counter_bump_all(result, l_pairs, false, vm)?; + let r_pairs = rhs.clone_all_pairs(vm)?; + counter_bump_all(result, r_pairs, false, vm)?; + } + CounterOp::Sub => { + let l_pairs = lhs.clone_all_pairs(vm)?; + counter_bump_all(result, l_pairs, false, vm)?; + let r_pairs = rhs.clone_all_pairs(vm)?; + counter_bump_all(result, r_pairs, true, vm)?; + } + // `|` keeps the larger count over the union of keys (see `counter_binary_extreme`). + CounterOp::Or => counter_binary_extreme(result, lhs, rhs, ExtremeOp::Max, vm)?, + // `&` keeps the smaller count over shared keys (see `counter_binary_extreme`). + CounterOp::And => counter_binary_extreme(result, lhs, rhs, ExtremeOp::Min, vm)?, + } + counter_retain_positive(result, vm)?; + Ok(result_guard.into_inner().into_value()) +} + +/// The extreme kept by the binary `&`/`|` algebra. +#[derive(Clone, Copy)] +enum ExtremeOp { + /// `&` — the minimum count, over keys present in both. + Min, + /// `|` — the maximum count, over the union of keys. + Max, +} + +/// Folds a binary `&`/`|` into the fresh `result`. +/// +/// Both walk the *left* operand's keys and pick the extreme of `count` and the +/// right's `other[elem]` (a missing right key reads as `0`), comparing exactly as +/// CPython does — `count < other_count`, left operand first, so an unorderable +/// pair reports `<` with the operands in that order. `|` additionally carries the +/// right-only keys across. The caller's final `retain_positive` performs the +/// `> 0` strip (and raises the `> 0` `TypeError` for an unorderable right-only +/// key, matching CPython's second-loop wording). +fn counter_binary_extreme<'h>( + result: &mut HeapObjectRead<'h, Dict>, + lhs: &HeapObjectRead<'h, Dict>, + rhs: &HeapObjectRead<'h, Dict>, + op: ExtremeOp, + vm: &mut VM<'h>, +) -> RunResult<()> { + // Two guards cover every failure below, so each one is a plain `?`: the outer + // releases the entries the loop never reached, the inner the one in flight. + let l_pairs = lhs.clone_all_pairs(vm)?.into_iter(); + defer_drop_mut!(l_pairs, vm); + for entry in l_pairs.by_ref() { + let mut entry = DropGuard::new(entry, vm); + let ((key, count), vm) = entry.as_parts_mut(); + let other = rhs.dict_get(key, vm)?.unwrap_or(Value::Int(0)); + let mut other = DropGuard::new(other, vm); + let (other_count, vm) = other.as_parts_mut(); + // `count < other`: `|` keeps `count` when it is *not* smaller, `&` keeps + // it when it *is* smaller. The loser is released. + let count_is_smaller = count_holds(count, other_count, CountCmp::Lt, vm)?; + let keep_count = match op { + ExtremeOp::Max => !count_is_smaller, + ExtremeOp::Min => count_is_smaller, + }; + let other = other.into_inner(); + let ((key, count), vm) = entry.into_parts(); + let picked = if keep_count { + other.drop_with(vm); + count + } else { + count.drop_with(vm); + other + }; + if let Some(old) = result.set(key, picked, vm)? { + old.drop_with(vm); + } + } + + if matches!(op, ExtremeOp::Max) { + let r_pairs = rhs.clone_all_pairs(vm)?.into_iter(); + defer_drop_mut!(r_pairs, vm); + for entry in r_pairs.by_ref() { + let mut entry = DropGuard::new(entry, vm); + let ((key, _), vm) = entry.as_parts_mut(); + // Shared keys were already resolved in the left pass, so the guard + // releases this entry; only a right-only key reaches the result. + if let Some(existing) = lhs.dict_get(key, vm)? { + existing.drop_with(vm); + } else { + let ((key, count), vm) = entry.into_parts(); + if let Some(old) = result.set(key, count, vm)? { + old.drop_with(vm); + } + } + } + } + Ok(()) +} + +/// The multiset comparisons CPython defines between two Counters. +#[derive(Clone, Copy)] +pub(crate) enum CounterCmp { + /// `<=` — every count in the left is at most the matching right count. + Le, + /// `<` — `<=` and not equal. + Lt, + /// `>=` — every count in the left is at least the matching right count. + Ge, + /// `>` — `>=` and not equal. + Gt, +} + +/// Evaluates a multiset comparison between two Counters. +/// +/// CPython walks the union of both key sets with a missing key reading as `0` +/// (`all(self[e] <= other[e] for c in (self, other) for e in c)`), so a key +/// present in only one operand still constrains the result. The strict forms +/// are defined in terms of the loose ones: `<` is `<= and !=`, `>` is +/// `>= and !=`. +pub(crate) fn counter_compare<'h>( + lhs: &HeapObjectRead<'h, Dict>, + rhs: &HeapObjectRead<'h, Dict>, + cmp: CounterCmp, + vm: &mut VM<'h>, +) -> RunResult { + // `<` is `<= and !=` and `>` is `>= and !=`, so both strict forms run the + // loose comparison — whose operator is what an unorderable pair reports — and + // add the inequality via the separately tracked `equal`. + let (op, strict) = match cmp { + CounterCmp::Le => (CountCmp::Le, false), + CounterCmp::Lt => (CountCmp::Le, true), + CounterCmp::Ge => (CountCmp::Ge, false), + CounterCmp::Gt => (CountCmp::Ge, true), + }; + // `holds` is false as soon as any pair breaks the loose ordering; `equal` + // tracks whether every compared pair matched, which the strict forms need. + let mut holds = true; + let mut equal = true; + // `counter_union_counts` hands back owned pairs the caller must drop. The + // guard covers every exit — a short-circuit (`!holds`), a failing comparison, + // and normal exhaustion — releasing whatever the loop never compared. + let pairs = counter_union_counts(lhs, rhs, vm)?.into_iter(); + defer_drop_mut!(pairs, vm); + for pair in pairs.by_ref() { + defer_drop!(pair, vm); + let (l, r) = pair; + // One `py_cmp` yields both the loose check and the equality the strict + // forms need. A `NaN` pair is unordered: the loose comparison fails (as + // in CPython, `nan <= x` is false) and the pair counts as not-equal. + match l.py_cmp(r, vm)? { + CmpOrder::Ordered(Ordering::Equal) => {} + CmpOrder::Ordered(ordering) => { + holds &= op.holds(ordering); + equal = false; + } + CmpOrder::Unordered => { + holds = false; + equal = false; + } + CmpOrder::Incomparable => { + return Err(ExcType::type_error_ordering( + op.symbol(), + &l.py_type_name(vm), + &r.py_type_name(vm), + )); + } + } + if !holds { + break; + } + } + Ok(holds && (!strict || !equal)) +} + +/// Pairs up the counts of two Counters over the union of their keys, with a +/// key missing from either side reading as `0`. +/// +/// Returns owned clones so the caller can run comparisons that need `&mut VM`. +/// Every returned pair must be dropped by the caller. +fn counter_union_counts<'h>( + lhs: &HeapObjectRead<'h, Dict>, + rhs: &HeapObjectRead<'h, Dict>, + vm: &mut VM<'h>, +) -> RunResult> { + // Three guards, so a failing lookup is a plain `?`: the pairs accumulated so + // far, the entries not yet visited, and the entry in flight all get released. + let mut pairs = DropGuard::new(Vec::new(), vm); + // Left keys against their right counterparts, then the right-only keys. + for (keys, other, flip) in [(lhs, rhs, false), (rhs, lhs, true)] { + let (collected, vm) = pairs.as_parts_mut(); + let entries = keys.clone_all_pairs(vm)?.into_iter(); + defer_drop_mut!(entries, vm); + for entry in entries.by_ref() { + let mut entry = DropGuard::new(entry, vm); + let ((key, _), vm) = entry.as_parts_mut(); + let other = other.dict_get(key, vm)?; + // On the second pass only keys absent from the left are new; the + // shared ones were already paired, so skip them (the guard releases + // the entry); otherwise the count moves into `collected`. + match (flip, other) { + (true, Some(other)) => other.drop_with(vm), + (true, None) => { + let ((key, count), vm) = entry.into_parts(); + key.drop_with(vm); + collected.push((Value::Int(0), count)); + } + (false, other) => { + let ((key, count), vm) = entry.into_parts(); + key.drop_with(vm); + collected.push((count, other.unwrap_or(Value::Int(0)))); + } + } + } + } + Ok(pairs.into_inner()) +} + +/// Applies a `Counter` algebra operator **in place**, mutating `counter`. +/// +/// CPython's `__iadd__`/`__isub__`/`__iand__`/`__ior__` mutate `self` and return +/// it, so `c += other` keeps the object identity and any alias observes the +/// update — unlike the binary operators, which build a fresh Counter. Each ends +/// with `_keep_positive()`, stripping entries that are not `> 0`. +/// +/// The right operand `rhs` may be **any mapping** (`c += {'a': 2}`), not only a +/// Counter. `+=`/`-=`/`|=` iterate `rhs.items()`, so a non-mapping raises +/// `AttributeError`; `&=` subscripts `rhs[elem]`, so a plain dict raises +/// `KeyError` for a key absent from it (a Counter reads that as `0`). +/// +/// Note the asymmetry CPython has between the directions: `+=` / `-=` walk +/// *other*'s keys (so new keys can appear), whereas `&=` walks *self*'s keys +/// (so no key is ever added), and `|=` walks *other*'s keys keeping the larger. +pub(crate) fn counter_inplace_op<'h>( + counter: &mut HeapObjectRead<'h, Dict>, + rhs: &Value, + op: CounterOp, + vm: &mut VM<'h>, +) -> RunResult<()> { + match op { + // `for elem, count in other.items(): self[elem] += count` + CounterOp::Add => { + let rhs = counter_require_mapping(rhs, vm)?; + counter_bump_all(counter, rhs.clone_all_pairs(vm)?, false, vm)?; + } + CounterOp::Sub => { + let rhs = counter_require_mapping(rhs, vm)?; + counter_bump_all(counter, rhs.clone_all_pairs(vm)?, true, vm)?; + } + // `for elem, other_count in other.items(): if other_count > self[elem]: + // self[elem] = other_count` — walks *other*, so new keys can appear. + CounterOp::Or => { + let rhs = counter_require_mapping(rhs, vm)?; + let r_pairs = rhs.clone_all_pairs(vm)?.into_iter(); + defer_drop_mut!(r_pairs, vm); + for entry in r_pairs.by_ref() { + let mut entry = DropGuard::new(entry, vm); + let ((key, other_count), vm) = entry.as_parts_mut(); + // A key absent from `self` reads as 0 (`self[elem]`). + let count = counter.dict_get(key, vm)?.unwrap_or(Value::Int(0)); + // `other_count > self[elem]`: other first, so the TypeError names it first. + let bigger = count_holds(other_count, &count, CountCmp::Gt, vm); + count.drop_with(vm); + // A count that is not bigger leaves `self` alone, and the guard + // releases the entry — as it does if the comparison raised. + if bigger? { + let ((key, other_count), vm) = entry.into_parts(); + if let Some(old) = counter.set(key, other_count, vm)? { + old.drop_with(vm); + } + } + } + } + // `for elem, count in self.items(): if other[elem] < count: + // self[elem] = other[elem]` — walks *self*, subscripting `other`. + CounterOp::And => { + let pairs = counter.clone_all_pairs(vm)?.into_iter(); + defer_drop_mut!(pairs, vm); + for entry in pairs.by_ref() { + let mut entry = DropGuard::new(entry, vm); + let ((key, count), vm) = entry.as_parts_mut(); + // `other[elem]` is a real subscript: a Counter yields 0 for a + // missing key, a plain dict raises `KeyError`, and a non-mapping + // raises its subscript error — exactly CPython's `__iand__`. An + // empty `self` never reaches here, so `c &= 5` is a no-op then. + let other_count = rhs.py_getitem(key, vm)?; + let mut other_count = DropGuard::new(other_count, vm); + let (other, vm) = other_count.as_parts_mut(); + // `other[elem] < count`: other first, matching CPython's wording. + let is_smaller = count_holds(other, count, CountCmp::Lt, vm)?; + // Only the smaller of the two survives; the guards release the + // loser, the whole entry when nothing changes, and both if the + // comparison raised. + if is_smaller { + let smaller = other_count.into_inner(); + let ((key, count), vm) = entry.into_parts(); + count.drop_with(vm); + if let Some(old) = counter.set(key, smaller, vm)? { + old.drop_with(vm); + } + } + } + } + } + counter_retain_positive(counter, vm) +} + +/// Computes a unary `Counter` operation. `+c` keeps the counts that are `> 0`; +/// `-c` keeps the *strictly negative* counts, storing their negation (CPython's +/// `{elem: -count for elem, count in self.items() if count < 0}`). Both leave +/// only positive counts, so the result is a valid Counter. +pub(crate) fn counter_unary_op<'h>( + counter: &HeapObjectRead<'h, Dict>, + negate: bool, + vm: &mut VM<'h>, +) -> RunResult { + let mut result = Dict::new(); + result.make_counter(); + let result = vm.heap.allocate_as(result); + // Guard the freshly allocated result dict: a catchable error below (e.g. + // comparing a non-numeric count) must free it, which the bare `?` + // early-returns would otherwise leak. + let mut result_guard = DropGuard::new(result, vm); + let (result, vm) = result_guard.as_parts_mut(); + let result = result.read(vm.heap); + // Scoped so the iterator guard releases its borrow of `result_guard` before + // the result is handed back. + { + let pairs = counter.clone_all_pairs(vm)?.into_iter(); + defer_drop_mut!(pairs, vm); + for entry in pairs.by_ref() { + let mut entry = DropGuard::new(entry, vm); + let ((_, count), vm) = entry.as_parts_mut(); + // `-c` filters on `count < 0` first (reporting `<` for an unorderable + // count, dropping a NaN), then stores `0 - count`. `+c` copies the count + // through and lets the trailing `retain_positive` apply the `> 0` strip. + let negated = if negate { + if !count_holds(count, &Value::Int(0), CountCmp::Lt, vm)? { + // Not negative, so nothing is stored; the guard releases the entry. + continue; + } + Some(count_arith(&Value::Int(0), count, true, vm)?) + } else { + None + }; + let ((key, count), vm) = entry.into_parts(); + let stored = match negated { + Some(negated) => { + count.drop_with(vm); + negated + } + None => count, + }; + if let Some(old) = result.set(key, stored, vm)? { + old.drop_with(vm); + } + } + } + counter_retain_positive(result, vm)?; + Ok(result_guard.into_inner().into_value()) +} + +/// Folds a batch of `(key, delta)` pairs into `counter`, releasing any pairs +/// left unconsumed when a bump fails. +fn counter_bump_all<'h>( + counter: &mut HeapObjectRead<'h, Dict>, + pairs: Vec<(Value, Value)>, + subtract: bool, + vm: &mut VM<'h>, +) -> RunResult<()> { + let pairs = pairs.into_iter(); + defer_drop_mut!(pairs, vm); + for (key, delta) in pairs.by_ref() { + // `counter_bump` borrows the delta, so each one is released here. + let outcome = counter_bump(counter, key, &delta, subtract, false, vm); + delta.drop_with(vm); + outcome?; + } + Ok(()) +} + +/// Returns the dictionary handle for an in-place right-hand operand, or raises +/// CPython's `AttributeError: 'X' object has no attribute 'items'` — the failure +/// `c += other` / `-=` / `|=` hit when `other.items()` has no `.items()`. +fn counter_require_mapping<'h>(rhs: &Value, vm: &VM<'h>) -> RunResult> { + match rhs.read_heap(vm) { + Some(HeapReadOutput::Dict(dict)) => Ok(dict), + _ => Err(ExcType::attribute_error(rhs.py_type_name(vm), "items")), + } +} + +/// Removes every entry whose count is not strictly positive from `counter`. +fn counter_retain_positive<'h>(counter: &mut HeapObjectRead<'h, Dict>, vm: &mut VM<'h>) -> RunResult<()> { + // The keys to remove are collected first: the scan clones them out of the + // dict, so popping while iterating is not possible. Both guards release what + // they still hold if a count comparison — or a `pop` hashing a key — raises. + let mut remove = DropGuard::new(Vec::new(), vm); + { + let (remove, vm) = remove.as_parts_mut(); + let entries = counter.clone_all_pairs(vm)?.into_iter(); + defer_drop_mut!(entries, vm); + for (key, count) in entries { + defer_drop_mut!(count, vm); + let mut key_guard = DropGuard::new(key, vm); + if !count_is_positive(count, key_guard.ctx())? { + let key = key_guard.into_inner(); + remove.push(key); + } + } + } + let (remove, vm) = remove.into_parts(); + let remove = remove.into_iter(); + defer_drop_mut!(remove, vm); + for key in remove.by_ref() { + defer_drop!(key, vm); + if let Some(old) = counter.pop(key, vm)? { + old.drop_with(vm); + } + } + Ok(()) +} diff --git a/crates/bashkit-monty/src/modules/collections/defaultdict.rs b/crates/bashkit-monty/src/modules/collections/defaultdict.rs new file mode 100644 index 000000000..5f52eb8e0 --- /dev/null +++ b/crates/bashkit-monty/src/modules/collections/defaultdict.rs @@ -0,0 +1,56 @@ +//! Runtime behaviour for `collections.defaultdict`. +//! +//! A defaultdict is a `dict` tagged with a defaultdict [`DictKind`](crate::types::DictKind), +//! carrying its `default_factory`. The only behavioural addition is the +//! missing-key hook below; everything else is the inherited dict surface. + +use crate::{ + args::ArgValues, + bytecode::VM, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::HeapObjectRead, + types::Dict, + value::Value, +}; + +/// Implements `defaultdict.__missing__(key)` — the hook a missing-key access +/// invokes: if a `default_factory` is set, call it, insert `key -> factory()`, +/// and return the value; otherwise raise `KeyError`. +/// +/// Shared by the getitem miss path (`Value::py_getitem`) and the explicit +/// `__missing__` method. The factory runs via `VM::evaluate_function`, so a +/// factory that performs external/OS calls is unsupported (documented). +pub(crate) fn defaultdict_missing<'h>( + dict: &mut HeapObjectRead<'h, Dict>, + key: &Value, + vm: &mut VM<'h>, +) -> RunResult { + let factory = dict.get(vm.heap).default_factory().map(|f| f.clone_with_heap(vm.heap)); + let Some(factory) = factory else { + return Err(ExcType::key_error(key, vm)); + }; + let value = match vm.evaluate_function(&factory, ArgValues::Empty) { + Ok(value) => value, + Err(e) => { + factory.drop_with(vm); + return Err(e); + } + }; + factory.drop_with(vm); + + // Insert `key -> value` and return the same value (CPython stores and + // returns the one object the factory produced). + let key_clone = key.clone_with_heap(vm.heap); + let value_ret = value.clone_with_heap(vm.heap); + // A `set` failure (e.g. a key `__eq__` raising during collision) must + // release the cloned `value_ret`, which the `?` early-return would leak. + match dict.set(key_clone, value, vm) { + Ok(Some(old)) => old.drop_with(vm), + Ok(None) => {} + Err(e) => { + value_ret.drop_with(vm); + return Err(e); + } + } + Ok(value_ret) +} diff --git a/crates/bashkit-monty/src/modules/collections/mod.rs b/crates/bashkit-monty/src/modules/collections/mod.rs new file mode 100644 index 000000000..f3e7e93b6 --- /dev/null +++ b/crates/bashkit-monty/src/modules/collections/mod.rs @@ -0,0 +1,361 @@ +//! Implementation of the `collections` module. +//! +//! The module surface (the factories and their argument handling) lives here; +//! the runtime behaviour of the two dict-backed types lives in the [`counter`] +//! and [`defaultdict`] submodules, keeping it out of `types/dict.rs`. +//! +//! Monty exposes only the subset of CPython's `collections` that it actually +//! implements — currently `deque` (a type) and the factory functions +//! `namedtuple`, `defaultdict`, and `Counter`. `OrderedDict`, `ChainMap` and +//! the `User*` classes are not (see `limitations/collections.md`). +//! +//! `deque` lives entirely in its runtime type (`crate::types::Deque`). +//! `namedtuple` is a factory: [`namedtuple`] validates its arguments and +//! allocates a [`NamedTupleClass`], the callable class object whose instances +//! are ordinary [`NamedTuple`](crate::types::NamedTuple)s. `defaultdict` and +//! `Counter` reuse the `dict` runtime type: [`defaultdict`] and [`counter`] +//! build a `dict` and tag it via `Dict::make_defaultdict` / `make_counter` +//! rather than introducing a new heap type. + +pub(crate) mod counter; +pub(crate) mod defaultdict; + +use std::iter::once; + +use ruff_python_stdlib::keyword::is_keyword; + +use self::counter::counter_update; +use crate::{ + args::{ArgValues, FromArgs}, + builtins::Builtins, + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{DropWithContext, HeapData, HeapId, HeapReadOutput}, + intern::StaticStrings, + types::{ + Dict, Module, NamedTupleClass, PyTrait, Type, + iter::collect_owned_iterable, + str::{StringRepr, str_isidentifier}, + }, + value::{EitherStr, Value}, +}; + +/// Creates the `collections` module and allocates it on the heap. +/// +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Collections, vm.interns); + + module.set_attr(StaticStrings::Deque, Value::Builtin(Builtins::Type(Type::Deque)), vm); + module.set_attr( + StaticStrings::Namedtuple, + Value::ModuleFunction(super::ModuleFunctions::Collections(CollectionsFunctions::Namedtuple)), + vm, + ); + // Exposed as the type objects themselves (like `deque`), not as factory + // functions, so `type(d) is defaultdict` and `isinstance(c, Counter)` hold. + module.set_attr( + StaticStrings::Defaultdict, + Value::Builtin(Builtins::Type(Type::DefaultDict)), + vm, + ); + module.set_attr( + StaticStrings::Counter, + Value::Builtin(Builtins::Type(Type::Counter)), + vm, + ); + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// The callable functions exposed by the `collections` module. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "lowercase")] +pub(crate) enum CollectionsFunctions { + Namedtuple, +} + +/// Dispatches a `collections` module function call. +pub(super) fn call(vm: &mut VM<'_>, function: CollectionsFunctions, args: ArgValues) -> RunResult { + match function { + CollectionsFunctions::Namedtuple => namedtuple(vm, args), + } +} + +/// The `collections.Counter(iterable_or_mapping=None, /, **kwargs)` constructor. +/// Construction is `Counter().update(...)`: a mapping adds its counts, any +/// other iterable counts occurrences, and keyword arguments add counts. +/// +/// Reached via [`Type::call`](crate::types::Type::call) — `collections.Counter` +/// is exposed as the type object, so `type(c) is Counter` holds. +pub(crate) fn counter_init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (mut pos, kwargs) = args.into_parts(); + let total = pos.len(); + let source = (total > 0).then(|| pos.next().expect("len checked")); + + // Counter accepts at most one positional (the iterable/mapping). + if total > 1 { + source.drop_with(vm); + pos.drop_with(vm); + kwargs.drop_with(vm); + return Err(ExcType::type_error_too_many_positional_range( + "Counter.__init__", + 1, + 2, + total + 1, + 0, + )); + } + + let mut dict = Dict::new(); + dict.make_counter(); + let value = Value::Ref(vm.heap.allocate(HeapData::Dict(dict))); + let Value::Ref(dict_id) = value else { + unreachable!("just allocated a ref"); + }; + let result = { + let HeapReadOutput::Dict(mut counter) = vm.heap.read(dict_id) else { + unreachable!("just allocated a Counter dict"); + }; + counter_update(&mut counter, source, kwargs, false, vm) + }; + if let Err(e) = result { + value.drop_with(vm); + return Err(e); + } + Ok(value) +} + +/// The `collections.defaultdict(default_factory=None, /, *args, **kwargs)` +/// constructor. The first positional argument is the `default_factory` (a +/// callable or `None`); any remaining arguments initialise the dict exactly like +/// `dict(...)`. +/// +/// Reached via [`Type::call`](crate::types::Type::call) — `collections.defaultdict` +/// is exposed as the type object, so `type(d) is defaultdict` holds. +pub(crate) fn defaultdict_init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (mut pos, kwargs) = args.into_parts(); + let factory_arg = (pos.len() > 0).then(|| pos.next().expect("len checked")); + + let factory = match factory_arg { + None | Some(Value::None) => None, + Some(value) if value.is_callable(vm) => Some(value), + Some(value) => { + value.drop_with(vm); + pos.drop_with(vm); + kwargs.drop_with(vm); + return Err(ExcType::defaultdict_factory_not_callable()); + } + }; + + // Everything after the factory initialises the dict via the normal `dict` + // constructor, so `defaultdict`'s init errors match `dict`'s. + let rest: Vec = pos.collect(); + let rest_args = if rest.is_empty() && kwargs.is_empty() { + ArgValues::Empty + } else { + ArgValues::ArgsKargs { args: rest, kwargs } + }; + let dict_value = match Dict::init(vm, rest_args) { + Ok(value) => value, + Err(e) => { + if let Some(factory) = factory { + factory.drop_with(vm); + } + return Err(e); + } + }; + + let Value::Ref(dict_id) = dict_value else { + unreachable!("Dict::init returns a dict ref"); + }; + let HeapReadOutput::Dict(dict) = vm.heap.read(dict_id) else { + unreachable!("Dict::init returns a dict"); + }; + dict.get_mut(vm.heap).make_defaultdict(factory); + Ok(dict_value) +} + +/// Arguments for `collections.namedtuple`. +/// +/// CPython's `namedtuple` is a pure-Python `def`, so fields stay raw `Value` +/// (`def` binding never type-checks) and coercion happens in the body. +#[derive(FromArgs)] +#[from_args(name = "namedtuple", style = def)] +struct NamedtupleArgs { + #[from_args(static_string = "Typename")] + typename: Value, + #[from_args(static_string = "FieldNames")] + field_names: Value, + #[from_args(kw_only, default = Value::Bool(false), static_string = "Rename")] + rename: Value, + #[from_args(kw_only, default = Value::None, static_string = "Defaults")] + defaults: Value, + #[from_args(kw_only, default = Value::None, static_string = "ModuleKwarg")] + module: Value, +} + +/// The `collections.namedtuple(typename, field_names, *, rename, defaults, +/// module)` factory. Validates the type/field names against CPython's rules +/// and allocates a [`NamedTupleClass`]. +/// +/// Divergence from CPython: non-string `typename`/`field_names` elements are not +/// `str()`-coerced beyond what the checks below require. +fn namedtuple(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let NamedtupleArgs { + typename, + field_names, + rename, + defaults, + module, + } = NamedtupleArgs::from_args(args, vm)?; + defer_drop!(typename, vm); + defer_drop!(field_names, vm); + defer_drop!(rename, vm); + defer_drop!(defaults, vm); + defer_drop!(module, vm); + + // CPython applies `str(typename)` before validating, so any object whose + // `__str__` yields a valid identifier is accepted. `validate_names` below + // then rejects the non-identifier cases with CPython's own message. + let type_name = if let Some(name) = typename.as_either_str(vm.heap) { + name + } else { + let as_str = typename.py_str(vm)?; + let owned = as_str.to_str(vm).map(str::to_owned); + as_str.drop_with(vm); + EitherStr::from(owned?) + }; + + // CPython tests `if rename:`, so any truthy value enables it — not just `True`. + let rename = rename.py_bool(vm)?; + let mut names = parse_field_names(field_names, vm)?; + if rename { + apply_rename(&mut names); + } + validate_names(type_name.as_str(vm.interns), &names, rename)?; + + // Collect defaults (rightmost fields), then validate the count. + let default_values = collect_defaults(defaults, vm)?; + if default_values.len() > names.len() { + default_values.drop_with(vm); + return Err(ExcType::type_error("Got more default values than field names")); + } + + // CPython substitutes the calling module's `__name__` for a `None` module, and + // otherwise stores the argument unvalidated (it need not be a string). + let module = match module { + Value::None => Value::InternString(vm.interns.intern_static(StaticStrings::DunderMain)), + other => other.clone_with_heap(vm.heap), + }; + + let field_names: Vec = names.into_iter().map(EitherStr::Heap).collect(); + let class = NamedTupleClass::new(type_name, field_names, default_values, module); + Ok(Value::Ref(vm.heap.allocate(HeapData::NamedTupleClass(Box::new(class))))) +} + +/// Parses the `field_names` argument into owned strings. +/// +/// A single string is split on commas and whitespace (`'x y'`, `'x,y'`, +/// `'x, y'` all yield `['x', 'y']`); any other value is iterated and each +/// element is `str()`-converted, matching CPython's `list(map(str, ...))`. +fn parse_field_names(field_names: &Value, vm: &mut VM<'_>) -> RunResult> { + if let Some(text) = field_names.as_either_str(vm.heap) { + Ok(text + .as_str(vm.interns) + .replace(',', " ") + .split_whitespace() + .map(str::to_owned) + .collect()) + } else { + let items = collect_owned_iterable::>(field_names.clone_with_heap(vm.heap), vm)?; + let mut names = Vec::with_capacity(items.len()); + // A failing `str()` (a field's `__str__` raising) must release the + // current item *and* the un-iterated remainder; the guards cover both. + let iter = items.into_iter(); + defer_drop_mut!(iter, vm); + for item in iter.by_ref() { + defer_drop!(item, vm); + let as_str = item.py_str(vm)?; + defer_drop!(as_str, vm); + names.push(as_str.to_str(vm)?.to_owned()); + } + Ok(names) + } +} + +/// Collects the `defaults` argument (an iterable, or `None`) into values. +fn collect_defaults(defaults: &Value, vm: &mut VM<'_>) -> RunResult> { + if matches!(defaults, Value::None) { + Ok(Vec::new()) + } else { + collect_owned_iterable::>(defaults.clone_with_heap(vm.heap), vm) + } +} + +/// Rewrites invalid field names to positional placeholders (`_0`, `_1`, ...), +/// matching CPython's `rename=True` behaviour. +/// +/// A name is replaced when it is not a valid identifier, is a keyword, starts +/// with an underscore, or duplicates an earlier name. Duplicate detection uses +/// the original names, so `['x', 'x']` becomes `['x', '_1']`. +fn apply_rename(names: &mut [String]) { + let mut seen: Vec = Vec::with_capacity(names.len()); + for (index, name) in names.iter_mut().enumerate() { + let invalid = + !str_isidentifier(name) || is_keyword(name) || name.starts_with('_') || seen.iter().any(|s| s == name); + seen.push(name.clone()); + if invalid { + *name = format!("_{index}"); + } + } +} + +/// Validates the type name and field names against CPython's namedtuple rules, +/// in CPython's order: identifier/keyword checks over `[typename] + fields` +/// first, then the underscore/duplicate checks over the fields. +/// +/// When `rename` is true the underscore check is skipped, matching CPython — +/// `rename=True` deliberately produces `_0`, `_1`, ... placeholders. +fn validate_names(type_name: &str, field_names: &[String], rename: bool) -> RunResult<()> { + for name in once(type_name).chain(field_names.iter().map(String::as_str)) { + if !str_isidentifier(name) { + return Err(ExcType::value_error(format!( + "Type names and field names must be valid identifiers: {}", + repr_name(name) + ))); + } + if is_keyword(name) { + return Err(ExcType::value_error(format!( + "Type names and field names cannot be a keyword: {}", + repr_name(name) + ))); + } + } + + let mut seen: Vec<&str> = Vec::with_capacity(field_names.len()); + for name in field_names { + if name.starts_with('_') && !rename { + return Err(ExcType::value_error(format!( + "Field names cannot start with an underscore: {}", + repr_name(name) + ))); + } + if seen.contains(&name.as_str()) { + return Err(ExcType::value_error(format!( + "Encountered duplicate field name: {}", + repr_name(name) + ))); + } + seen.push(name); + } + Ok(()) +} + +/// Renders a name as a Python string repr for the `%r` in CPython's namedtuple +/// error messages. Uses the runtime's [`StringRepr`], so a name containing a +/// quote or escape is quoted and escaped like CPython (`a'b` → `"a'b"`) rather +/// than wrapped in bare single quotes (`'a'b'`). +fn repr_name(name: &str) -> StringRepr<'_> { + StringRepr(name) +} diff --git a/crates/bashkit-monty/src/modules/copy.rs b/crates/bashkit-monty/src/modules/copy.rs new file mode 100644 index 000000000..b5493fa19 --- /dev/null +++ b/crates/bashkit-monty/src/modules/copy.rs @@ -0,0 +1,686 @@ +//! Implementation of Python's `copy` module. +//! +//! CPython reaches most types through the pickle protocol (`__reduce_ex__`). +//! Monty has no pickle, so both functions dispatch on the heap type directly: +//! immutable values are shared, containers are rebuilt, and anything else +//! raises the `TypeError` CPython's pickler would. `__copy__`/`__deepcopy__` +//! are still honoured. Divergences are listed in `limitations/copy.md`. + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{ContainsHeap, DropGuard, DropWithContext, HeapData, HeapId, HeapReadOutput}, + intern::StaticStrings, + modules::ModuleFunctions, + types::{Dict, List, Module, hash_table::TableCursor, instance_call_copy_hook}, + value::{VALUE_SIZE, Value}, +}; + +/// `copy` module functions, one variant per Python-visible function. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +pub(crate) enum CopyFunctions { + #[strum(serialize = "copy")] + Copy, + #[strum(serialize = "deepcopy")] + Deepcopy, +} + +/// Static mapping of attribute names to functions for module creation. +const COPY_FUNCTIONS: &[(StaticStrings, CopyFunctions)] = &[ + (StaticStrings::Copy, CopyFunctions::Copy), + (StaticStrings::Deepcopy, CopyFunctions::Deepcopy), +]; + +/// Creates the `copy` module on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Copy, vm.interns); + + for (name, func) in COPY_FUNCTIONS { + module.set_attr(*name, Value::ModuleFunction(ModuleFunctions::Copy(*func)), vm); + } + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a call to a `copy` module function. +pub(super) fn call(vm: &mut VM<'_>, function: CopyFunctions, args: ArgValues) -> RunResult { + match function { + CopyFunctions::Copy => call_copy(vm, args), + CopyFunctions::Deepcopy => call_deepcopy(vm, args), + } +} + +/// A pure-Python `def` in CPython, so the parameter binds without a type check. +#[derive(FromArgs)] +#[from_args(name = "copy", style = def)] +struct CopyArgs { + x: Value, +} + +/// `copy.copy(x)`: a new object holding the *same* items as `x`. +fn call_copy(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let CopyArgs { x } = CopyArgs::from_args(args, vm)?; + defer_drop!(x, vm); + shallow_copy(x, vm) +} + +/// CPython's signature. `_nil` is its private "missing from `memo`" sentinel, +/// accepted for arity parity and never read. +#[derive(FromArgs)] +#[from_args(name = "deepcopy", style = def)] +struct DeepcopyArgs { + x: Value, + #[from_args(default = Value::None, static_string = "Memo")] + memo: Value, + #[from_args(default = Value::None, static_string = "NilSentinel")] + _nil: Value, +} + +/// `copy.deepcopy(x, memo=None)`: rebuilds `x` and everything it holds. +fn call_deepcopy(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let DeepcopyArgs { x, memo, _nil: nil } = DeepcopyArgs::from_args(args, vm)?; + defer_drop!(x, vm); + defer_drop!(nil, vm); + let memo = Memo::new(memo, vm)?; + let mut guard = DropGuard::new(memo, vm); + let (memo, vm) = guard.as_parts_mut(); + deep_copy(x, memo, vm) +} + +// =========================================================================== +// Shallow copy +// =========================================================================== + +/// Returns a new container holding the very objects the original holds. +/// +/// [`classify`] settles what happens to each heap type; this only spells out +/// the rebuilds, which need the typed handle its arm binds. +fn shallow_copy(value: &Value, vm: &mut VM<'_>) -> RunResult { + let Value::Ref(id) = value else { + return Ok(value.clone_with_heap(vm.heap)); + }; + let id = *id; + match classify(&vm.heap.read(id)) { + Copyability::Shared | Copyability::ImmutableContainer => Ok(value.clone_with_heap(vm.heap)), + Copyability::Refused => Err(cannot_copy(value, vm)), + Copyability::Rebuilt => match vm.heap.read(id) { + HeapReadOutput::List(list) => { + let items = clone_items(list.get(vm.heap).len(), vm, |index, vm| list.clone_item(index, vm))?; + Ok(Value::Ref(vm.heap.allocate(HeapData::List(List::new(items))))) + } + HeapReadOutput::Dict(dict) => { + let pairs = dict.clone_all_pairs(vm)?; + let copy_id = dict.allocate_empty_like(vm); + let filled = insert_pairs(copy_id, pairs, vm); + release_on_error(Value::Ref(copy_id), filled, vm) + } + HeapReadOutput::Set(set) => { + let copy = set.copy(vm); + Ok(Value::Ref(vm.heap.allocate(HeapData::Set(copy)))) + } + HeapReadOutput::Deque(deque) => { + let items = clone_items(deque.get(vm.heap).len(), vm, |index, vm| { + deque + .get(vm.heap) + .get(index) + .expect("index is in bounds") + .clone_with_heap(vm.heap) + })?; + Ok(deque.allocate_like(items, vm)) + } + HeapReadOutput::NamedTuple(named) => { + let items = clone_items(named.get(vm.heap).field_names().len(), vm, |index, vm| { + named.clone_item(index, vm) + })?; + Ok(named.allocate_like(items, vm)) + } + HeapReadOutput::Instance(instance) => { + if let Some(copy) = instance_call_copy_hook(id, "__copy__", None, vm)? { + Ok(copy) + } else { + let pairs = clone_attrs(id, vm)?; + let copy_id = instance.allocate_empty_like(vm); + let filled = insert_attrs(copy_id, pairs, vm); + release_on_error(Value::Ref(copy_id), filled, vm) + } + } + // A new binding over the same receiver and function, as CPython's + // `getattr(obj, name)` reducer produces. + HeapReadOutput::BoundMethod(bound) => { + let instance = bound.get(vm.heap).instance.clone_with_heap(vm.heap); + Ok(bound.allocate_like(instance, vm)) + } + // A new partial over the same callable and bound values, as CPython's + // reducer produces. Unlike the immutable containers `classify` shares, + // this is a distinct object in CPython too, so sharing it would be visible. + HeapReadOutput::Partial(partial) => partial.allocate_like(vm), + // A second generator at the same point in the same sequence, which is + // what CPython's `__getstate__`/`__setstate__` pair produces. + HeapReadOutput::Random(random) => Ok(random.allocate_like(vm)), + // `Context.__copy__`: the same settings and flags in a new object. + HeapReadOutput::DecimalContext(context) => { + let settings = *context.get(vm.heap); + Ok(Value::Ref(vm.heap.allocate(HeapData::DecimalContext(settings)))) + } + _ => unreachable!("`classify` said this type is rebuilt, so `shallow_copy` must rebuild it"), + }, + } +} + +// =========================================================================== +// Deep copy +// =========================================================================== + +/// Deep-copying, implemented by the heap types `copy.deepcopy` rebuilds. +/// +/// Narrow on purpose: only eleven of the sixty-seven heap types implement it (a +/// `decimal.Context`, holding no references, is rebuilt inline), so this is a +/// trait of its own rather than a method on [`PyTrait`](crate::types::PyTrait) +/// that the others would carry meaninglessly. The method is required, with no +/// default — a default would be the "refuse it" answer, which is legitimate for +/// most types, so forgetting to override it would look exactly like deciding +/// not to. Which types reach this at all is settled by [`classify`]. +/// +/// Implementations memoize an empty shell before filling it, so a container +/// holding itself resolves to the shell instead of recursing forever, and hold +/// that shell in a `DropGuard` so a failure partway releases it. +pub(crate) trait PyDeepCopy<'h> { + /// Returns a new object holding deep copies of everything this one holds. + /// + /// `source` is the `Value` being copied — the memo key, and what a type + /// that turns out not to need rebuilding hands back unchanged. + fn py_deep_copy(&self, source: &Value, memo: &mut Memo, vm: &mut VM<'h>) -> RunResult; +} + +/// Returns a deep copy of `value`, reusing anything this pass already copied. +/// +/// The memo is what makes a graph that reaches the same object twice — itself +/// included — copy to a graph with the same sharing. +/// +/// The whole walk runs inside one call, past no instruction checkpoint, so +/// every fill loop polls the duration limit as the container iterators do. +pub(crate) fn deep_copy(source: &Value, memo: &mut Memo, vm: &mut VM<'_>) -> RunResult { + let Value::Ref(id) = source else { + return Ok(source.clone_with_heap(vm.heap)); + }; + let id = *id; + if let Some(hit) = memo.get(source, vm)? { + return Ok(hit); + } + // One level per step, as every other Rust-side walk charges. A step costs + // ~770 bytes of native stack for a list and ~1.1 KiB for a dict or an + // instance, so a limit's worth of the latter exceeds a wasm worker's 1 MiB + // — the same exposure `py_eq` and `py_repr` have, and the same fix (a + // smaller `RunError`). See `tests/copy_module.rs`. + let mut guard = vm.recursion_guard()?; + let vm = &mut *guard; + // Dispatched here rather than in a function of its own: every frame live + // across the recursion is paid once per level of nesting. `classify` + // returns before the recursion, so its frame is not one of them. + let copy = match classify(&vm.heap.read(id)) { + Copyability::Shared => Ok(source.clone_with_heap(vm.heap)), + Copyability::Refused => Err(cannot_copy(source, vm)), + // An immutable container's items still change, so `deepcopy` rebuilds + // the ones `copy` shares. + Copyability::Rebuilt | Copyability::ImmutableContainer => match vm.heap.read(id) { + HeapReadOutput::List(list) => list.py_deep_copy(source, memo, vm), + HeapReadOutput::Dict(dict) => dict.py_deep_copy(source, memo, vm), + HeapReadOutput::Deque(deque) => deque.py_deep_copy(source, memo, vm), + HeapReadOutput::Set(set) => set.py_deep_copy(source, memo, vm), + HeapReadOutput::FrozenSet(frozen) => frozen.py_deep_copy(source, memo, vm), + HeapReadOutput::Instance(instance) => instance.py_deep_copy(source, memo, vm), + HeapReadOutput::Tuple(tuple) => tuple.py_deep_copy(source, memo, vm), + HeapReadOutput::NamedTuple(named) => named.py_deep_copy(source, memo, vm), + HeapReadOutput::BoundMethod(bound) => bound.py_deep_copy(source, memo, vm), + HeapReadOutput::Partial(partial) => partial.py_deep_copy(source, memo, vm), + HeapReadOutput::Random(random) => random.py_deep_copy(source, memo, vm), + // A context holds no references, so its deep copy is its shallow one. + HeapReadOutput::DecimalContext(context) => { + let settings = *context.get(vm.heap); + Ok(Value::Ref(vm.heap.allocate(HeapData::DecimalContext(settings)))) + } + _ => unreachable!("`classify` said this type is rebuilt, so `deep_copy` must rebuild it"), + }, + }?; + // CPython only memoizes a copy that is a new object ("if y is not x"). + if same_object(source, ©) { + Ok(copy) + } else { + match memo.insert_if_absent(source, ©, vm) { + Ok(()) => Ok(copy), + Err(e) => { + copy.drop_with(vm); + Err(e) + } + } + } +} + +// =========================================================================== +// Classification +// =========================================================================== + +/// What `copy` does with a heap type. +/// +/// [`classify`] is the one exhaustive match over `HeapReadOutput`, so a new +/// heap type is a compile error there until someone picks a variant here, +/// rather than falling into "cannot pickle" because nobody looked. +enum Copyability { + /// Rebuilt by both passes. The caller matches the type again, because only + /// its own arm holds the typed handle a rebuild needs. + Rebuilt, + /// Shared by both passes. Values CPython shares too, so rebuilding one + /// would be the divergence — its `_copy_atomic_types` set. + Shared, + /// Shared by `copy`, which keeps the same items, and rebuilt by `deepcopy`, + /// which does not. + ImmutableContainer, + /// Refused, with the `TypeError` CPython's pickler raises. + Refused, +} + +/// Decides what the two passes do with a heap value. +fn classify(output: &HeapReadOutput<'_>) -> Copyability { + match output { + HeapReadOutput::List(_) + | HeapReadOutput::Dict(_) + | HeapReadOutput::Set(_) + | HeapReadOutput::Deque(_) + | HeapReadOutput::NamedTuple(_) + | HeapReadOutput::Instance(_) + | HeapReadOutput::BoundMethod(_) + | HeapReadOutput::Partial(_) + | HeapReadOutput::Random(_) + | HeapReadOutput::DecimalContext(_) => Copyability::Rebuilt, + // A shallow copy of an immutable container holds the same items, so + // CPython hands back the original; only `deepcopy` rebuilds these. + HeapReadOutput::Tuple(_) | HeapReadOutput::FrozenSet(_) => Copyability::ImmutableContainer, + // CPython's cache wrappers share their state through both copy operations. + HeapReadOutput::LruCache(_) => Copyability::Shared, + // Leaves and immutable containers Monty can never mutate, so a copy + // that shared them is indistinguishable from one that rebuilt them. + HeapReadOutput::Str(_) + | HeapReadOutput::Bytes(_) + | HeapReadOutput::LongInt(_) + | HeapReadOutput::Complex(_) + | HeapReadOutput::Decimal(_) + | HeapReadOutput::Range(_) + | HeapReadOutput::Slice(_) + | HeapReadOutput::RePattern(_) + | HeapReadOutput::ReMatch(_) + | HeapReadOutput::Exception(_) + | HeapReadOutput::Date(_) + | HeapReadOutput::Time(_) + | HeapReadOutput::DateTime(_) + | HeapReadOutput::TimeDelta(_) + | HeapReadOutput::TimeZone(_) + | HeapReadOutput::Path(_) + // Classes and functions. A `def`/`lambda` only reaches the heap once + // it captures an enclosing scope or evaluates a default; a plain one + // is a `Value::Function` and never gets here. Their state is mutable + // (`nonlocal`, class attributes) but CPython shares them anyway, so + // rebuilding would be the divergence. + | HeapReadOutput::Class(_) + | HeapReadOutput::NamedTupleClass(_) + | HeapReadOutput::HostClassType(_) + | HeapReadOutput::Closure(_) + | HeapReadOutput::DataclassMethod(_) + // Type forms: `list[int]` and `int | None`. Nothing can mutate one, so + // sharing is visible only to `is` — CPython rebuilds them through + // `operator.getitem`, see `limitations/copy.md`. + | HeapReadOutput::GenericAlias(_) + | HeapReadOutput::Union(_) + | HeapReadOutput::FunctionDefaults(_) => Copyability::Shared, + // Refused, with the `TypeError` CPython's pickler raises. Views and + // iterators are positions into something else; the rest are host + // objects or interpreter internals with no Python-visible + // constructor to rebuild them from. A `HostClass` is the clearest of + // those: its identity belongs to the host, so a rebuilt one would + // answer lazy attribute reads through the very object it was supposed + // to be detached from. See `limitations/copy.md` for the cases where + // CPython manages to copy one of these and Monty does not. + HeapReadOutput::HostClass(_) + | HeapReadOutput::HashObject(_) + | HeapReadOutput::DictKeysView(_) + | HeapReadOutput::DictItemsView(_) + | HeapReadOutput::DictValuesView(_) + | HeapReadOutput::ListIterator(_) + | HeapReadOutput::DequeIterator(_) + | HeapReadOutput::TupleIterator(_) + | HeapReadOutput::StringIterator(_) + | HeapReadOutput::BytesIterator(_) + | HeapReadOutput::RangeIterator(_) + | HeapReadOutput::DictKeyIterator(_) + | HeapReadOutput::DictItemIterator(_) + | HeapReadOutput::DictValueIterator(_) + | HeapReadOutput::SetIterator(_) + | HeapReadOutput::CallableIterator(_) + | HeapReadOutput::DirScan(_) + | HeapReadOutput::Itertools(_) + | HeapReadOutput::Csv(_) + | HeapReadOutput::Module(_) + | HeapReadOutput::Coroutine(_) + | HeapReadOutput::GatherFuture(_) + | HeapReadOutput::ExternalFuture(_) + | HeapReadOutput::OpenFile(_) + | HeapReadOutput::ExtFunction(_) + | HeapReadOutput::Cell(_) + | HeapReadOutput::DataclassField(_) + | HeapReadOutput::DataclassParams(_) + | HeapReadOutput::DecimalSignalDict(_) + | HeapReadOutput::DecimalContextManager(_) => Copyability::Refused, + } +} + +/// Fills an instance copy's `__dict__` from the original's, going +/// through the attribute dict rather than `setattr` so frozen ones can be +/// rebuilt — the bypass CPython's `__dict__.update` is. +pub(crate) fn deep_copy_attrs( + source_id: HeapId, + copy_id: HeapId, + source: &Value, + memo: &mut Memo, + vm: &mut VM<'_>, +) -> RunResult { + let mut guard = DropGuard::new(Value::Ref(copy_id), vm); + let (copy, vm) = guard.as_parts_mut(); + memo.insert(source, copy, vm)?; + let expected_len = attrs(source_id, vm).len(); + // Preflighted whole, for the reason the dict copy is: the loop below + // rejects a resize rather than following it, so this is the final width. + vm.heap + .tracker + .check_allocation(expected_len.saturating_mul(2 * VALUE_SIZE))?; + // `__dict__` is a dict, and CPython copies it by iterating it. + let mut cursor = TableCursor::new(expected_len); + for index in 0.. { + let (_, vm) = guard.as_parts_mut(); + vm.heap.tracker.check_time_every(index)?; + let Some((key, value)) = attrs(source_id, vm).clone_next_pair(&mut cursor, vm.heap)? else { + break; + }; + let (key_copy, value_copy) = deep_copy_pair(key, value, memo, vm)?; + let HeapReadOutput::Instance(instance) = vm.heap.read(copy_id) else { + unreachable!("caller allocated an instance") + }; + let replaced = instance.attrs_mut().set(key_copy, value_copy, vm)?; + if let Some(replaced) = replaced { + replaced.drop_with(vm); + } + } + let (copy, _) = guard.into_parts(); + Ok(copy) +} + +/// Deep-copies `len` items into a vector, for the immutable containers that +/// cannot be built until they have all of them. +pub(crate) fn deep_copy_slots<'h>( + len: usize, + memo: &mut Memo, + vm: &mut VM<'h>, + mut clone_item: impl FnMut(usize, &mut VM<'h>) -> Value, +) -> RunResult> { + vm.heap.tracker.check_allocation(len.saturating_mul(VALUE_SIZE))?; + let mut guard = DropGuard::new(Vec::with_capacity(len), vm); + for index in 0..len { + let (copied, vm) = guard.as_parts_mut(); + vm.heap.tracker.check_time_every(index)?; + let item = clone_item(index, vm); + let result = deep_copy(&item, memo, vm); + item.drop_with(vm); + copied.push(result?); + } + let (copied, _) = guard.into_parts(); + Ok(copied) +} + +/// Deep-copies an owned key and value, releasing both either way. +pub(crate) fn deep_copy_pair(key: Value, value: Value, memo: &mut Memo, vm: &mut VM<'_>) -> RunResult<(Value, Value)> { + let key_copy = deep_copy(&key, memo, vm); + key.drop_with(vm); + let key_copy = match key_copy { + Ok(key_copy) => key_copy, + Err(e) => { + value.drop_with(vm); + return Err(e); + } + }; + let value_copy = deep_copy(&value, memo, vm); + value.drop_with(vm); + match value_copy { + Ok(value_copy) => Ok((key_copy, value_copy)), + Err(e) => { + key_copy.drop_with(vm); + Err(e) + } + } +} + +// =========================================================================== +// The memo +// =========================================================================== + +/// One `deepcopy` pass's memo: CPython's `id(source) -> copy` dict, plus the +/// sources it has seen. +/// +/// Sources are pinned for the whole pass because heap ids are recycled: one +/// dying mid-pass would let a later object inherit its id, and its entry. +pub(crate) struct Memo { + /// The memo dict — the caller's when they passed one, else freshly made. + dict: Value, + /// Every source visited this pass, keeping their ids unique. + keep_alive: Vec, +} + +impl Memo { + /// `None` allocates a fresh dict; a caller's dict is adopted, so they see + /// what the pass recorded. + fn new(memo: Value, vm: &mut VM<'_>) -> RunResult { + let dict = match memo { + Value::None => Value::Ref(vm.heap.allocate(HeapData::Dict(Dict::new()))), + Value::Ref(id) if matches!(vm.heap.read(id), HeapReadOutput::Dict(_)) => memo, + other => { + let type_name = other.py_type_name(vm); + other.drop_with(vm); + return Err(ExcType::type_error(format!( + "deepcopy() memo must be a dict or None, not {type_name}" + ))); + } + }; + Ok(Self { + dict, + keep_alive: Vec::new(), + }) + } + + /// Returns the copy this pass already made for `source`, if any. + pub(crate) fn get(&self, source: &Value, vm: &mut VM<'_>) -> RunResult> { + let key = source.id().into_value(vm.heap); + defer_drop!(key, vm); + let HeapReadOutput::Dict(dict) = vm.heap.read(self.dict_id()) else { + unreachable!("memo is a dict") + }; + dict.dict_get(key, vm) + } + + /// Records `copy` unless this pass already has an entry for `source`. + /// + /// Most rebuilt types memoize their own shell before filling it — they have + /// to, or a cycle through a child would not terminate — so by the time + /// [`deep_copy`] finishes, the entry usually exists. Whether it does is a + /// per-call fact rather than a per-type one: an instance memoizes on the + /// attribute-copy path but not when a `__deepcopy__` hook answered, and the + /// hook's result still has to be recorded. Asking the memo covers both, + /// where re-inserting would re-hash the key, drop the copy it displaced and + /// pin the source a second time. + fn insert_if_absent(&mut self, source: &Value, copy: &Value, vm: &mut VM<'_>) -> RunResult<()> { + match self.get(source, vm)? { + Some(existing) => { + existing.drop_with(vm); + Ok(()) + } + None => self.insert(source, copy, vm), + } + } + + /// Records `copy` as the copy of `source`, and pins `source` for the pass. + pub(crate) fn insert(&mut self, source: &Value, copy: &Value, vm: &mut VM<'_>) -> RunResult<()> { + let key = source.id().into_value(vm.heap); + let value = copy.clone_with_heap(vm.heap); + let HeapReadOutput::Dict(dict) = vm.heap.read(self.dict_id()) else { + unreachable!("memo is a dict") + }; + if let Some(replaced) = dict.set(key, value, vm)? { + replaced.drop_with(vm); + } + vm.heap.tracker.check_allocation(VALUE_SIZE)?; + self.keep_alive.push(source.clone_with_heap(vm.heap)); + Ok(()) + } + + /// The memo dict as an owned value, for handing to `__deepcopy__`. + pub(crate) fn dict_value(&self, vm: &VM<'_>) -> Value { + self.dict.clone_with_heap(vm.heap) + } + + fn dict_id(&self) -> HeapId { + self.dict.ref_id().expect("memo dict is heap allocated") + } +} + +impl DropWithContext for Memo { + fn drop_with(self, context: &mut C) { + self.dict.drop_with(context); + self.keep_alive.drop_with(context); + } +} + +// =========================================================================== +// Filling helpers +// =========================================================================== + +/// Clones `len` items out of a container, preflighting the slot bytes. +/// +/// Polls the clock as the deep-copy loops do: a shallow copy of a large +/// container reaches no instruction checkpoint between entering `copy.copy` +/// and returning, so without this the whole walk is invisible to the time +/// limits. The clones are guarded because that poll can now cut the +/// loop short with items already taken. +pub(crate) fn clone_items<'h>( + len: usize, + vm: &mut VM<'h>, + mut clone_item: impl FnMut(usize, &mut VM<'h>) -> Value, +) -> RunResult> { + vm.heap.tracker.check_allocation(len.saturating_mul(VALUE_SIZE))?; + let mut guard = DropGuard::new(Vec::with_capacity(len), vm); + for index in 0..len { + let (items, vm) = guard.as_parts_mut(); + vm.heap.tracker.check_time_every(index)?; + items.push(clone_item(index, vm)); + } + Ok(guard.into_inner()) +} + +/// Clones an instance's `__dict__` entries, polling and guarded for the reason +/// [`clone_items`] is. +fn clone_attrs(id: HeapId, vm: &mut VM<'_>) -> RunResult> { + let len = attrs(id, vm).len(); + vm.heap + .tracker + .check_allocation(len.saturating_mul(2).saturating_mul(VALUE_SIZE))?; + let mut guard = DropGuard::new(Vec::with_capacity(len), vm); + let (pairs, vm) = guard.as_parts_mut(); + // One borrow for the whole snapshot, so no user code can run under it. + for (index, (key, value)) in attrs(id, vm).iter().enumerate() { + vm.heap.tracker.check_time_every(index)?; + pairs.push((key.clone_with_heap(vm.heap), value.clone_with_heap(vm.heap))); + } + Ok(guard.into_inner()) +} + +/// Borrows an instance's attribute dict. +fn attrs<'a>(id: HeapId, vm: &'a VM<'_>) -> &'a Dict { + match vm.heap.get(id) { + HeapData::Instance(instance) => instance.attrs(), + _ => unreachable!("caller checked the type"), + } +} + +/// Moves owned `pairs` into a dict copy. +/// +/// The iterator is guarded because `set` re-hashes each key, running a user +/// `__hash__` that can raise: the pairs the loop has not reached yet are still +/// owned here, and a plain `for` would drop them without releasing them. +/// +/// That re-hashing also makes this the most expensive of the shallow-copy +/// loops — a wide dict spends hundreds of milliseconds here — so it polls the +/// clock as well; see `timeout_in_shallow_copy_fill_loop`. The poll runs +/// *before* each pair is taken from the iterator, so a timeout leaves every +/// remaining pair inside the guard; pulling first would strand the one in hand. +fn insert_pairs(dict_id: HeapId, pairs: Vec<(Value, Value)>, vm: &mut VM<'_>) -> RunResult<()> { + let pairs = pairs.into_iter(); + defer_drop_mut!(pairs, vm); + for index in 0.. { + vm.heap.tracker.check_time_every(index)?; + let Some((key, value)) = pairs.next() else { + break; + }; + let HeapReadOutput::Dict(dest) = vm.heap.read(dict_id) else { + unreachable!("copy was allocated as a dict") + }; + // `set` takes ownership of the pair and releases it on failure. + if let Some(replaced) = dest.set(key, value, vm)? { + replaced.drop_with(vm); + } + } + Ok(()) +} + +/// Moves owned `pairs` into the `__dict__` of an instance copy, bypassing +/// `setattr` as [`deep_copy_attrs`] does. Guarded, and polled before the pull, +/// for the reasons [`insert_pairs`] is. +fn insert_attrs(id: HeapId, pairs: Vec<(Value, Value)>, vm: &mut VM<'_>) -> RunResult<()> { + let pairs = pairs.into_iter(); + defer_drop_mut!(pairs, vm); + for index in 0.. { + vm.heap.tracker.check_time_every(index)?; + let Some((key, value)) = pairs.next() else { + break; + }; + let HeapReadOutput::Instance(instance) = vm.heap.read(id) else { + unreachable!("caller allocated an instance") + }; + let replaced = instance.attrs_mut().set(key, value, vm)?; + if let Some(replaced) = replaced { + replaced.drop_with(vm); + } + } + Ok(()) +} + +// =========================================================================== +// Small helpers +// =========================================================================== + +/// Releases a half-built copy when filling it failed. +fn release_on_error(copy: Value, filled: RunResult<()>, vm: &mut VM<'_>) -> RunResult { + match filled { + Ok(()) => Ok(copy), + Err(e) => { + copy.drop_with(vm); + Err(e) + } + } +} + +/// Whether the two values are the same object (Python's `is`). +fn same_object(a: &Value, b: &Value) -> bool { + a.id() == b.id() +} + +/// The `TypeError` CPython's pickler raises for a type it cannot rebuild. +fn cannot_copy(value: &Value, vm: &VM<'_>) -> RunError { + ExcType::type_error(format!("cannot pickle '{}' object", value.py_type_name(vm))) +} diff --git a/crates/bashkit-monty/src/modules/csv.rs b/crates/bashkit-monty/src/modules/csv.rs new file mode 100644 index 000000000..8ab8f3ff5 --- /dev/null +++ b/crates/bashkit-monty/src/modules/csv.rs @@ -0,0 +1,505 @@ +//! Implementation of the `csv` module. +//! +//! `reader()`, `writer()`, `DictReader`, `DictWriter`, the `QUOTE_*` constants, `Error`, the +//! three built-in dialects (`excel`, `excel_tab`, `unix_dialect`, exposed as `_csv.Dialect` +//! objects), `get_dialect()`, `list_dialects()` and a fixed `field_size_limit()`. There is no +//! dialect registry (`register_dialect`) and no `Sniffer`; see `limitations/csv.md`. +//! +//! A reader over a file nobody has read yet cannot load it from `__next__`, so `reader(f)` +//! and `DictReader(f)` yield the host read with a `LoadThenCall` effect and the call is +//! replayed once the buffer is in place. Every later consumer, `list(reader)` included, then +//! works. + +use std::mem; + +use crate::{ + args::{ArgValues, FromArgs, KwargsValues}, + builtins::Builtins, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{DropGuard, DropWithContext, HeapData, HeapId, HeapReadOutput}, + intern::StaticStrings, + modules::ModuleFunctions, + os_dispatch::PostConversionEffect, + types::{ + CsvObject, List, Module, PyTrait, Type, + csv::{ + DIALECT_NAMES, Dialect, DictReader, DictWriter, FIELD_SIZE_LIMIT, FmtParams, Quoting, Reader, Writer, + write_method, + }, + iter::collect_iterable, + str::allocate_string, + }, + value::Value, +}; + +/// Module-level `csv` functions; `DictReader` and `DictWriter` are types. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum CsvFunctions { + /// `csv.reader(csvfile, dialect='excel', **fmtparams)`. + Reader, + /// `csv.writer(csvfile, dialect='excel', **fmtparams)`. + Writer, + /// `csv.get_dialect(name)`. + GetDialect, + /// `csv.list_dialects()`. + ListDialects, + /// `csv.field_size_limit([new_limit])`. + FieldSizeLimit, +} + +/// Allocates the `csv` module and returns its `HeapId`. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Csv, vm.interns); + + for (name, function) in [ + (StaticStrings::Reader, CsvFunctions::Reader), + (StaticStrings::Writer, CsvFunctions::Writer), + (StaticStrings::GetDialect, CsvFunctions::GetDialect), + (StaticStrings::ListDialects, CsvFunctions::ListDialects), + (StaticStrings::FieldSizeLimit, CsvFunctions::FieldSizeLimit), + ] { + module.set_attr(name, Value::ModuleFunction(ModuleFunctions::Csv(function)), vm); + } + for (name, type_) in [ + (StaticStrings::DictReader, Type::CsvDictReader), + (StaticStrings::DictWriter, Type::CsvDictWriter), + (StaticStrings::DialectClass, Type::CsvDialect), + ] { + module.set_attr(name, Value::Builtin(Builtins::Type(type_)), vm); + } + for (name, quoting) in [ + (StaticStrings::QuoteMinimal, Quoting::Minimal), + (StaticStrings::QuoteAll, Quoting::All), + (StaticStrings::QuoteNonnumeric, Quoting::Nonnumeric), + (StaticStrings::QuoteNone, Quoting::None), + (StaticStrings::QuoteStrings, Quoting::Strings), + (StaticStrings::QuoteNotnull, Quoting::Notnull), + ] { + module.set_attr(name, Value::Int(quoting.as_int()), vm); + } + module.set_attr( + StaticStrings::ErrorClass, + Value::Builtin(Builtins::ExcType(ExcType::CsvError)), + vm, + ); + // CPython's are classes; Monty exposes the resolved dialects, which `dialect=` accepts alike. + for (name, dialect) in [ + (StaticStrings::Excel, Dialect::excel()), + (StaticStrings::ExcelTab, Dialect::excel_tab()), + (StaticStrings::UnixDialect, Dialect::unix()), + ] { + module.set_attr(name, CsvObject::Dialect(dialect).allocate(vm), vm); + } + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a call to a `csv` module function. +pub(super) fn call(vm: &mut VM<'_>, function: CsvFunctions, args: ArgValues) -> RunResult { + match function { + CsvFunctions::Reader => call_reader(vm, args), + CsvFunctions::Writer => call_writer(vm, args).map(CallResult::Value), + CsvFunctions::GetDialect => call_get_dialect(vm, args).map(CallResult::Value), + CsvFunctions::ListDialects => call_list_dialects(vm, args).map(CallResult::Value), + CsvFunctions::FieldSizeLimit => call_field_size_limit(vm, args).map(CallResult::Value), + } +} + +/// `csv.reader(csvfile, dialect='excel', **fmtparams)`, loading an unread file first. +fn call_reader(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let callable = Value::ModuleFunction(ModuleFunctions::Csv(CsvFunctions::Reader)); + match load_then_call(callable, args, None, vm) { + Ok(load) => Ok(load), + Err(args) => reader_init(vm, args).map(CallResult::Value), + } +} + +/// `csv.DictReader(f, ...)` as called from Python, loading an unread file first. +pub(crate) fn dict_reader_call(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let callable = Value::Builtin(Builtins::Type(Type::CsvDictReader)); + match load_then_call(callable, args, Some("f"), vm) { + Ok(load) => Ok(load), + Err(args) => dict_reader_init(vm, args).map(CallResult::Value), + } +} + +/// When the file argument (the first positional, or the keyword `file_keyword` names) is a +/// readable file nobody has read, the host read that loads it, with `callable(args)` +/// replayed on resume. Otherwise hands `args` back. +fn load_then_call( + callable: Value, + args: ArgValues, + file_keyword: Option<&str>, + vm: &mut VM<'_>, +) -> Result { + let file = args + .first_positional() + .or_else(|| file_keyword.and_then(|name| args.keyword(name, vm.heap, vm.interns))); + let file_id = match file { + Some(Value::Ref(id)) + if let HeapReadOutput::OpenFile(file) = vm.heap.read(*id) + && file.needs_buffer_load(vm) => + { + *id + } + _ => return Err(args), + }; + let HeapReadOutput::OpenFile(file) = vm.heap.read(file_id) else { + unreachable!("checked above") + }; + let effect = PostConversionEffect::LoadThenCall { + file_id, + callable, + args, + }; + Ok(file.buffer_load_call(vm, effect)) +} + +/// The positional shape of `reader()` / `writer()`: CPython unpacks them with +/// `PyArg_UnpackTuple(args, "", 1, 2)` before the dialect kwargs are parsed. +/// Hands `args` back on success and releases them on failure. +fn check_positional_shape(name: &str, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let error = match args.count() { + 0 => ExcType::type_error_at_least(name, 1, 0), + n if n > 2 => ExcType::type_error_at_most(name, 2, n), + _ => return Ok(args), + }; + args.drop_with(vm); + Err(error) +} + +/// `reader(csvfile, dialect='excel', **fmtparams)` and `writer(...)`, as CPython parses them: +/// the positionals by `PyArg_UnpackTuple` (checked first by `check_positional_shape`), the +/// format parameters by `Dialect`'s anonymous `PyArg_ParseTupleAndKeywords`. +#[derive(FromArgs)] +#[from_args(name = "reader", style = c)] +struct FmtParamArgs { + #[from_args(pos_only)] + f: Value, + #[from_args(default = None)] + dialect: Option, + #[from_args(kw_only, default = None)] + delimiter: Option, + #[from_args(kw_only, default = None)] + doublequote: Option, + #[from_args(kw_only, default = None)] + escapechar: Option, + #[from_args(kw_only, default = None)] + lineterminator: Option, + #[from_args(kw_only, default = None)] + quotechar: Option, + #[from_args(kw_only, default = None)] + quoting: Option, + #[from_args(kw_only, default = None)] + skipinitialspace: Option, + #[from_args(kw_only, default = None)] + strict: Option, +} + +impl FmtParamArgs { + /// Splits the parse into the source, the `dialect` argument and the format parameters. + fn into_parts(self) -> (Value, Option, FmtParams) { + let params = FmtParams { + delimiter: self.delimiter, + doublequote: self.doublequote, + escapechar: self.escapechar, + lineterminator: self.lineterminator, + quotechar: self.quotechar, + quoting: self.quoting, + skipinitialspace: self.skipinitialspace, + strict: self.strict, + }; + (self.f, self.dialect, params) + } +} + +/// Builds a `_csv.reader` from already-loaded (or non-file) input. +fn reader_init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let args = check_positional_shape("reader", args, vm)?; + let (csvfile, dialect, params) = FmtParamArgs::from_args(args, vm)?.into_parts(); + defer_drop!(csvfile, vm); + defer_drop!(dialect, vm); + let dialect = Dialect::resolve(dialect.as_ref(), params, vm)?; + let source = csvfile.py_iter(vm)?.require_synchronous(vm)?; + Ok(CsvObject::Reader(Reader::new(source, dialect)).allocate(vm)) +} + +/// `csv.writer(csvfile, dialect='excel', **fmtparams)`. +fn call_writer(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let args = check_positional_shape("writer", args, vm)?; + let (target, dialect, params) = FmtParamArgs::from_args(args, vm)?.into_parts(); + defer_drop!(dialect, vm); + let mut target_guard = DropGuard::new(target, vm); + let (target, vm) = target_guard.as_parts_mut(); + let dialect = Dialect::resolve(dialect.as_ref(), params, vm)?; + let Some(write) = write_method(target, vm)? else { + return Err(ExcType::type_error("argument 1 must have a \"write\" method")); + }; + let (target, vm) = target_guard.into_parts(); + Ok(CsvObject::Writer(Writer::new(target, write, dialect)).allocate(vm)) +} + +/// `csv.get_dialect(name)`: one of the built-in dialects. +fn call_get_dialect(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let GetDialectArgs { name } = GetDialectArgs::from_args(args, vm)?; + defer_drop!(name, vm); + let dialect = if name.is_str(vm.heap) { + Dialect::by_name(name.to_str(vm)?) + } else { + None + }; + dialect + .map(|dialect| CsvObject::Dialect(dialect).allocate(vm)) + .ok_or_else(ExcType::csv_unknown_dialect) +} + +/// `csv.list_dialects()`: the built-in dialect names. +fn call_list_dialects(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + args.check_zero_args("list_dialects", vm.heap)?; + let names = DIALECT_NAMES + .iter() + .map(|name| allocate_string(*name, vm.heap)) + .collect(); + Ok(Value::Ref(vm.heap.allocate(HeapData::List(List::new(names))))) +} + +/// `get_dialect(name)`: Argument Clinic, so `name` may be a keyword. +#[derive(FromArgs)] +#[from_args(name = "get_dialect", style = c_named, at_most_total)] +struct GetDialectArgs { + name: Value, +} + +/// `csv.field_size_limit([new_limit])`: reports CPython's default; the limit cannot change. +fn call_field_size_limit(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let FieldSizeLimitArgs { new_limit: limit } = FieldSizeLimitArgs::from_args(args, vm)?; + defer_drop!(limit, vm); + match limit { + None => Ok(Value::Int( + i64::try_from(FIELD_SIZE_LIMIT).expect("the limit fits an int"), + )), + Some(limit) if limit.py_type(vm) == Type::Int && !matches!(limit, Value::Bool(_)) => { + Err(ExcType::not_implemented("field_size_limit(): changing the limit is not supported").into()) + } + Some(_) => Err(ExcType::type_error("limit must be an integer")), + } +} + +/// `field_size_limit(new_limit=)`: Argument Clinic, so the keyword form works. +#[derive(FromArgs)] +#[from_args(name = "field_size_limit", style = c_named, at_most_total)] +struct FieldSizeLimitArgs { + #[from_args(default)] + new_limit: Option, +} + +/// `_csv.Dialect(dialect=None, **fmtparams)`: a resolved dialect object. +pub(crate) fn dialect_init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let DialectArgs { + dialect, + delimiter, + doublequote, + escapechar, + lineterminator, + quotechar, + quoting, + skipinitialspace, + strict, + } = DialectArgs::from_args(args, vm)?; + defer_drop!(dialect, vm); + let params = FmtParams { + delimiter, + doublequote, + escapechar, + lineterminator, + quotechar, + quoting, + skipinitialspace, + strict, + }; + let dialect = Dialect::resolve(dialect.as_ref(), params, vm)?; + Ok(CsvObject::Dialect(dialect).allocate(vm)) +} + +/// `Dialect(dialect=None, delimiter=..., ...)`: every parameter optional, `dialect` positional too. +#[derive(FromArgs)] +#[from_args(name = "Dialect", style = c)] +struct DialectArgs { + #[from_args(default = None)] + dialect: Option, + #[from_args(kw_only, default = None)] + delimiter: Option, + #[from_args(kw_only, default = None)] + doublequote: Option, + #[from_args(kw_only, default = None)] + escapechar: Option, + #[from_args(kw_only, default = None)] + lineterminator: Option, + #[from_args(kw_only, default = None)] + quotechar: Option, + #[from_args(kw_only, default = None)] + quoting: Option, + #[from_args(kw_only, default = None)] + skipinitialspace: Option, + #[from_args(kw_only, default = None)] + strict: Option, +} + +/// `DictReader(f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)`. +#[derive(FromArgs)] +#[from_args(name = "DictReader.__init__", style = def)] +struct DictReaderArgs { + f: Value, + #[from_args(default = Value::None)] + fieldnames: Value, + #[from_args(default = Value::None)] + restkey: Value, + #[from_args(default = Value::None)] + restval: Value, + #[from_args(default = None)] + dialect: Option, + #[from_args(varargs)] + args: Vec, + #[from_args(varkwargs)] + kwds: KwargsValues, +} + +/// Builds a `csv.DictReader`; the wrapped `_csv.reader` gets `f`, `dialect` and the extras. +pub(crate) fn dict_reader_init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let DictReaderArgs { + f, + fieldnames, + restkey, + restval, + dialect, + args, + kwds, + } = DictReaderArgs::from_args(args, vm)?; + let dialect = dialect.unwrap_or_else(|| excel_name(vm)); + // Everything is guarded before the first fallible step, so any rejection releases it all. + let dialect_arg = dialect.clone_with_heap(vm.heap); + let mut owned = DropGuard::new( + ( + [fieldnames, restkey, restval, dialect], + forwarded_args(f, dialect_arg, args, kwds), + ), + vm, + ); + let (([fieldnames, ..], _), vm) = owned.as_parts_mut(); + materialize_fieldnames(fieldnames, vm)?; + let ((owned_values, reader_args), vm) = owned.into_parts(); + let mut owned = DropGuard::new(owned_values, vm); + let (_, vm) = owned.as_parts_mut(); + let reader = reader_init(vm, reader_args)?; + let ([fieldnames, restkey, restval, dialect], vm) = owned.into_parts(); + let fieldnames = match fieldnames { + Value::None => None, + names => Some(names), + }; + Ok(CsvObject::DictReader(DictReader::new(reader, fieldnames, restkey, restval, dialect)).allocate(vm)) +} + +/// The arguments the wrapped `reader()` / `writer()` receives: `f`, `dialect`, then `*args` and `**kwds`. +fn forwarded_args(f: Value, dialect: Value, args: Vec, kwds: KwargsValues) -> ArgValues { + let positional = [f, dialect].into_iter().chain(args).collect(); + ArgValues::from_parts(positional, kwds) +} + +/// `DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)`. +#[derive(FromArgs)] +#[from_args(name = "DictWriter.__init__", style = def)] +struct DictWriterArgs { + f: Value, + fieldnames: Value, + #[from_args(default = None)] + restval: Option, + #[from_args(default = None)] + extrasaction: Option, + #[from_args(default = None)] + dialect: Option, + #[from_args(varargs)] + args: Vec, + #[from_args(varkwargs)] + kwds: KwargsValues, +} + +/// Builds a `csv.DictWriter`; the wrapped `_csv.writer` gets `f`, `dialect` and the extras. +pub(crate) fn dict_writer_init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let DictWriterArgs { + f, + fieldnames, + restval, + extrasaction, + dialect, + args, + kwds, + } = DictWriterArgs::from_args(args, vm)?; + let restval = restval.unwrap_or_else(|| static_str(StaticStrings::EmptyString, vm)); + let extrasaction = extrasaction.unwrap_or_else(|| static_str(StaticStrings::Raise, vm)); + let dialect = dialect.unwrap_or_else(|| excel_name(vm)); + // Everything is guarded before the first fallible step, so any rejection releases it all. + let dialect_arg = dialect.clone_with_heap(vm.heap); + let mut owned = DropGuard::new( + ( + [fieldnames, restval, extrasaction], + forwarded_args(f, dialect_arg, args, kwds), + ), + vm, + ); + let (([fieldnames, _, extrasaction], _), vm) = owned.as_parts_mut(); + materialize_fieldnames(fieldnames, vm)?; + let lowered = check_extrasaction(extrasaction, vm)?; + mem::replace(extrasaction, lowered).drop_with(vm); + let ((owned_values, writer_args), vm) = owned.into_parts(); + let mut owned = DropGuard::new(owned_values, vm); + let (_, vm) = owned.as_parts_mut(); + let writer = call_writer(vm, writer_args)?; + let ([fieldnames, restval, extrasaction], vm) = owned.into_parts(); + Ok(CsvObject::DictWriter(DictWriter::new(writer, fieldnames, restval, extrasaction)).allocate(vm)) +} + +/// `if fieldnames is not None and iter(fieldnames) is fieldnames: fieldnames = list(fieldnames)`, +/// as both constructors open: an iterator is read once into a list, and a `fieldnames` +/// that is not iterable at all is rejected here rather than at the first row. +fn materialize_fieldnames(fieldnames: &mut Value, vm: &mut VM<'_>) -> RunResult<()> { + if matches!(fieldnames, Value::None) { + return Ok(()); + } + let iterator = fieldnames.py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iterator, vm); + if iterator.is(fieldnames) { + let names = collect_iterable(fieldnames, vm)?; + let list = Value::Ref(vm.heap.allocate(HeapData::List(List::new(names)))); + mem::replace(fieldnames, list).drop_with(vm); + } + Ok(()) +} + +/// `extrasaction.lower()`, which must be `'raise'` or `'ignore'` and is what gets stored. +fn check_extrasaction(extrasaction: &Value, vm: &VM<'_>) -> RunResult { + if !extrasaction.is_str(vm.heap) { + return Err(ExcType::attribute_error(extrasaction.py_type_name(vm), "lower")); + } + let text = extrasaction.to_str(vm)?; + let lowered = text.to_lowercase(); + if lowered == "raise" || lowered == "ignore" { + Ok(allocate_string(lowered, vm.heap)) + } else { + Err(ExcType::value_error(format!( + "extrasaction ({text}) must be 'raise' or 'ignore'" + ))) + } +} + +/// The default `dialect` argument, the string `'excel'`. +fn excel_name(vm: &VM<'_>) -> Value { + static_str(StaticStrings::Excel, vm) +} + +/// An interned static string as a value. +fn static_str(name: StaticStrings, vm: &VM<'_>) -> Value { + Value::InternString(vm.interns.intern_static(name)) +} diff --git a/crates/bashkit-monty/src/modules/dataclasses/field.rs b/crates/bashkit-monty/src/modules/dataclasses/field.rs new file mode 100644 index 000000000..f87246e3c --- /dev/null +++ b/crates/bashkit-monty/src/modules/dataclasses/field.rs @@ -0,0 +1,384 @@ +//! The `dataclasses.Field` objects making up a class's `__dataclass_fields__`: +//! the type itself, the `field()` constructor, and the accessors that decode one +//! back out of the heap. The decorator that builds and adopts them lives in the +//! parent module. + +use std::fmt::Write; + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + hash::{HashValue, identity_hash}, + heap::{ContainsHeap, DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapItem, HeapObjectRead}, + intern::{StaticStrings, StringId}, + types::{LazyHeapSet, PyTrait, Type, str::allocate_string}, + value::{EitherStr, Marker, Value}, +}; + +/// One entry of a class's `__dataclass_fields__`: CPython's `dataclasses.Field`. +/// +/// Also what `dataclasses.field(...)` returns, as in CPython — the decorator +/// fills in the `name` and `annotation` of the very object the class body bound +/// and stores it, so `C.__dataclass_fields__['x'] is f` holds. Until then both +/// are `None`, which is what an un-adopted `field()` result reports. +/// +/// **Owns heap references** (`annotation`, `default`, `default_factory`), +/// reported in `py_dec_ref_ids` below and `heap::for_each_child_id` — a default +/// or a factory can reach back to its class, closing a cycle. Only the +/// attributes Monty can model are stored; the rest are constants or refused +/// (see `py_getattr` below). +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct DataclassField { + /// The interned field name (from an `__annotations__` key, always interned), + /// or `None` before a decorator adopts the field. + name: Option, + /// `Field.type`: the annotation as source text, never evaluated. `None` + /// until adopted, alongside `name`. + annotation: Option, + /// The default **captured when `@dataclass` ran**, or `None` for a required + /// field — rebinding the class attribute afterwards must not change it. + default: Option, + /// `field(default_factory=...)`: a callable invoked once per construction to + /// build this field's default. Mutually exclusive with `default`. + default_factory: Option, +} + +impl DataclassField { + /// Builds an adopted field, taking ownership of `annotation` and `default`. + /// + /// For a plain `x: int = 5`, where no `field()` object exists at all. + #[must_use] + pub fn new(name: StringId, annotation: Value, default: Option) -> Self { + Self { + name: Some(name), + annotation: Some(annotation), + default, + default_factory: None, + } + } + + /// Builds the un-adopted field `field(...)` returns, owning `default` and + /// `default_factory`. The decorator supplies the name and annotation later. + #[must_use] + pub fn new_spec(default: Option, default_factory: Option) -> Self { + Self { + name: None, + annotation: None, + default, + default_factory, + } + } + + /// The interned field name, as the generated `__init__` binds it, or + /// `None` for a `field()` result no decorator has adopted. + #[must_use] + pub fn name(&self) -> Option { + self.name + } + + /// `Field.type`, borrowed — the annotation the class was defined with, or + /// `None` for a `field()` result no decorator has adopted. + #[must_use] + pub fn annotation(&self) -> Option<&Value> { + self.annotation.as_ref() + } + + /// The captured default, or `None` for a required field. + #[must_use] + pub fn default(&self) -> Option<&Value> { + self.default.as_ref() + } + + /// The captured `default_factory`, or `None` when the field has none. + #[must_use] + pub fn default_factory(&self) -> Option<&Value> { + self.default_factory.as_ref() + } + + /// Whether the field is optional in the generated `__init__`: it has + /// either a captured default or a factory to call. + #[must_use] + pub fn has_default(&self) -> bool { + self.default.is_some() || self.default_factory.is_some() + } + + /// Adopts a `field()` result into a class, taking ownership of `annotation`. + /// + /// Mirrors CPython, which sets `f.name`/`f.type` on the object the class + /// body bound rather than building a new one. One `field()` object can be + /// adopted more than once — bound under two names, or by two classes — so + /// the annotation it already held is returned for the caller to release. + #[must_use] + pub fn adopt(&mut self, name: StringId, annotation: Value) -> Option { + self.name = Some(name); + self.annotation.replace(annotation) + } + + /// Every stored value that is a heap reference: the field's children, for + /// the cycle collector's walk. + pub fn ref_children(&self) -> impl Iterator + '_ { + [&self.annotation, &self.default, &self.default_factory] + .into_iter() + .flatten() + .filter_map(|value| match value { + Value::Ref(id) => Some(*id), + _ => None, + }) + } +} + +/// Releases a field that never reached the heap — one the decorator collected +/// before rejecting the class. +impl DropWithContext for DataclassField { + fn drop_with(self, ctx: &mut C) { + self.annotation.drop_with(ctx); + self.default.drop_with(ctx); + self.default_factory.drop_with(ctx); + } +} + +/// `dataclasses.field(...)`: builds the [`DataclassField`] a class body binds, +/// which `@dataclass` then adopts by filling in its name and annotation. +/// +/// Legal outside a class body too (`f = field(default=1)`), which is why it is +/// a value rather than a decoration-time form. +pub(super) fn field(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let FieldArgs { + default, + default_factory, + init, + repr, + compare, + hash, + metadata, + kw_only, + doc, + } = FieldArgs::from_args(args, vm)?; + // `MISSING` means "not given", since `None` is a legitimate default. + let spec = DataclassField::new_spec( + (!is_missing(&default)).then_some(default), + (!is_missing(&default_factory)).then_some(default_factory), + ); + // Guarded together, because the spec owns the captured default and factory + // before anything below has run and reading a flag's truthiness can raise + // (`NotImplemented` refuses it), which would otherwise strand them. + let mut guard = DropGuard::new((spec, [init, repr, hash, compare, metadata, kw_only, doc]), vm); + let ((spec, flags), vm) = guard.as_parts(); + // Both given is CPython's own error, raised before it builds the `Field` at + // all — so it outranks the Monty-only refusals below, and no flag may be + // read ahead of it. + if spec.default().is_some() && spec.default_factory().is_some() { + return Err(ExcType::value_error("cannot specify both default and default_factory")); + } + // Arguments Monty does not implement are refused when set away from their + // CPython default, as `@dataclass(...)` refuses its own. That includes the + // three flags: nothing consults them when the dunders are generated, so + // accepting `init=False` would silently give the field an `__init__` + // parameter anyway. Listed in signature order, which is the order CPython + // would hit them. + let [init, repr, hash, compare, metadata, kw_only, doc] = flags; + let unimplemented = [ + ("init", !init.py_bool(vm)?), + ("repr", !repr.py_bool(vm)?), + ("hash", !matches!(hash, Value::None)), + ("compare", !compare.py_bool(vm)?), + ("metadata", !matches!(metadata, Value::None)), + ("kw_only", !is_missing(kw_only)), + ("doc", !matches!(doc, Value::None)), + ] + .into_iter() + .find(|&(_, given)| given); + if let Some((name, _)) = unimplemented { + return Err(ExcType::not_implemented(format!("field() does not yet support the {name} argument")).into()); + } + let ((spec, flags), vm) = guard.into_parts(); + flags.drop_with(vm); + Ok(vm.heap.allocate_as(spec).into_value()) +} + +/// Whether an argument was left at the `MISSING` sentinel `field()` defaults to. +fn is_missing(value: &Value) -> bool { + matches!(value, Value::Marker(Marker(StaticStrings::Missing))) +} + +/// `field()` arguments, mirroring CPython's all-keyword-only signature. +/// `MISSING` is the "not given" sentinel, since `None` is a legitimate default. +#[derive(FromArgs)] +#[from_args(name = "field", style = def)] +struct FieldArgs { + #[from_args(kw_only, default = Value::Marker(Marker(StaticStrings::Missing)))] + default: Value, + #[from_args(kw_only, default = Value::Marker(Marker(StaticStrings::Missing)))] + default_factory: Value, + #[from_args(kw_only, default = Value::Bool(true))] + init: Value, + #[from_args(kw_only, default = Value::Bool(true))] + repr: Value, + #[from_args(kw_only, default = Value::None)] + hash: Value, + #[from_args(kw_only, default = Value::Bool(true))] + compare: Value, + #[from_args(kw_only, default = Value::None)] + metadata: Value, + #[from_args(kw_only, default = Value::Marker(Marker(StaticStrings::Missing)))] + kw_only: Value, + /// CPython's optional per-field docstring. Monty stores none, so anything + /// but the `None` default is refused rather than silently dropped. + #[from_args(kw_only, default = Value::None)] + doc: Value, +} + +/// The `Field` a heap id points at, if it is one. +pub(super) fn field_at_id(heap: &Heap, field_id: HeapId) -> Option<&DataclassField> { + match heap.get(field_id) { + HeapData::DataclassField(field) => Some(field), + _ => None, + } +} + +/// The heap `Field` a class-body value is, when the body bound a `field()` +/// result the decorator should adopt rather than treat as a plain default. +pub(super) fn adoptable_field(bound: Option<&Value>, vm: &VM<'_>) -> Option { + match bound { + Some(Value::Ref(id)) if matches!(vm.heap.get(*id), HeapData::DataclassField(_)) => Some(*id), + _ => None, + } +} + +/// `Field` attributes CPython has but Monty has no object for, paired with what +/// is missing. Refused rather than faked. +const UNMODELLED_ATTRS: [(&str, &str); 2] = [ + ("metadata", "types.MappingProxyType"), + ("_field_type", "dataclasses._FIELD"), +]; + +/// `dataclasses.MISSING`, the sentinel CPython reports for an unset `default` or +/// `default_factory`. +fn missing() -> Value { + Value::Marker(Marker(StaticStrings::Missing)) +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, DataclassField> { + fn py_type(&self, _vm: &VM<'h>) -> Type { + Type::DataclassField + } + + fn py_len(&self, _vm: &VM<'h>) -> Option { + None + } + + fn py_eq_impl(&self, _other: &Value, _vm: &mut VM<'h>) -> RunResult> { + // `Field` defines no `__eq__`, so it compares by identity, which + // `Value::py_eq_impl` resolves before ever reaching here. + Ok(None) + } + + fn py_hash(&self, _vm: &mut VM<'h>) -> RunResult> { + Ok(Some(identity_hash(self.id()))) + } + + /// CPython's `Field.__repr__`, attribute for attribute. `type` is annotation + /// text, the one spelling Monty cannot reproduce (a documented divergence). + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, heap_ids: &mut LazyHeapSet) -> RunResult<()> { + let Ok(mut guard) = vm.recursion_guard() else { + return Ok(f.write_str("...")?); + }; + let vm = &mut *guard; + // Cloned out first: recursing into `py_repr_fmt` needs the heap mutably. + let (name, annotation, default, factory, adopted) = { + let this = self.get(vm.heap); + ( + this.name.map(Value::InternString), + this.annotation.as_ref().map(|v| v.clone_with_heap(vm.heap)), + this.default.as_ref().map(|v| v.clone_with_heap(vm.heap)), + this.default_factory.as_ref().map(|v| v.clone_with_heap(vm.heap)), + this.name.is_some(), + ) + }; + defer_drop!(annotation, vm); + defer_drop!(default, vm); + defer_drop!(factory, vm); + f.write_str("Field(name=")?; + name.as_ref().unwrap_or(&Value::None).py_repr_fmt(f, vm, heap_ids)?; + f.write_str(",type=")?; + annotation + .as_ref() + .unwrap_or(&Value::None) + .py_repr_fmt(f, vm, heap_ids)?; + f.write_str(",default=")?; + default.as_ref().unwrap_or(&missing()).py_repr_fmt(f, vm, heap_ids)?; + f.write_str(",default_factory=")?; + factory.as_ref().unwrap_or(&missing()).py_repr_fmt(f, vm, heap_ids)?; + // Constants, because `field()` refuses every argument that would vary + // them — as `py_getattr` below notes. + f.write_str(",init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=")?; + // A field CPython has not adopted still reports `kw_only` as MISSING and + // `_field_type` as None; adoption is what fills them in. + if adopted { + f.write_str("False")?; + } else { + missing().py_repr_fmt(f, vm, heap_ids)?; + } + let field_type = if adopted { "_FIELD" } else { "None" }; + Ok(write!(f, ",doc=None,_field_type={field_type})")?) + } + + /// Everything but `name`/`type`/`default`/`default_factory` is a constant, + /// because the arguments that would vary them are refused by `field()`, so + /// every field Monty builds carries CPython's defaults. + fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { + let attr_str = attr.as_str(vm.interns); + let value = match attr_str { + // `None` until a decorator adopts the field, as in CPython. + "name" => match self.get(vm.heap).name { + Some(name) => { + let name = vm.interns.get_str(name).to_owned(); + allocate_string(name, vm.heap) + } + None => Value::None, + }, + "type" => match self.get(vm.heap).annotation.as_ref() { + Some(annotation) => annotation.clone_with_heap(vm.heap), + None => Value::None, + }, + // An unset default or factory *is* `MISSING` in CPython. + "default" => clone_or_missing(self.get(vm.heap).default.as_ref(), vm), + "default_factory" => clone_or_missing(self.get(vm.heap).default_factory.as_ref(), vm), + "init" | "repr" | "compare" => Value::Bool(true), + "kw_only" => Value::Bool(false), + "hash" | "doc" => Value::None, + _ => match UNMODELLED_ATTRS.iter().find(|&&(name, _)| name == attr_str) { + Some((name, missing)) => return Err(unmodelled_attr_error(name, missing)), + None => return Err(ExcType::attribute_error("Field", attr_str)), + }, + }; + Ok(Some(CallResult::Value(value))) + } +} + +/// `NotImplementedError` for an attribute CPython has: reading it is a gap in +/// Monty, not a mistake in the calling code. +fn unmodelled_attr_error(attr: &str, missing: &str) -> RunError { + ExcType::not_implemented(format!( + "Field.{attr} is not yet supported, {missing} is not implemented" + )) + .into() +} + +/// Clones a stored slot for `py_getattr`, reporting `MISSING` when it is unset. +fn clone_or_missing(value: Option<&Value>, vm: &VM<'_>) -> Value { + value.map_or_else(missing, |value| value.clone_with_heap(vm.heap)) +} + +impl HeapItem for DataclassField { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + for value in [&mut self.annotation, &mut self.default, &mut self.default_factory] + .into_iter() + .flatten() + { + value.py_dec_ref_ids(stack); + } + } +} diff --git a/crates/bashkit-monty/src/modules/dataclasses/legacy.rs b/crates/bashkit-monty/src/modules/dataclasses/legacy.rs new file mode 100644 index 000000000..0a3dad559 --- /dev/null +++ b/crates/bashkit-monty/src/modules/dataclasses/legacy.rs @@ -0,0 +1,74 @@ +//! Loading dataclasses from dumps written before `@dataclass` generated methods. +//! +//! Dump version 13 builds (1.0 and 1.1) decorated a class by writing only +//! `__dataclass_fields__` and `__dataclass_params__`; the VM read both at every +//! construction, comparison, hash, repr and assignment. Today the decorator also +//! writes `DataclassMethod`s, and a class without them behaves as a plain one. +//! A [`crate::dump_upgrade`] generates the missing methods from those two +//! entries, which hold everything decoration saw. +//! +//! Everything here exists only for that compatibility, so it can be deleted +//! together once `MIN_SUPPORTED_DUMP_VERSION` passes [`LEGACY_DUMP_VERSION`]. + +use super::{DataclassOptions, Installer, install_generated_methods}; +use crate::{ + heap::{DropWithContext, Heap, HeapData, HeapId, HeapReadOutput, HeapReader}, + intern::Interns, + types::instance::namespace_member, + value::Value, +}; + +/// The last dump version written before `@dataclass` generated methods. +pub(crate) const LEGACY_DUMP_VERSION: u16 = 13; + +/// Generates the methods of every dataclass on a heap loaded from a version 13 +/// dump, as [`crate::dump_upgrade`] calls before the session is handed out. +pub(crate) fn upgrade_legacy_classes(heap: &mut Heap, interns: &Interns) { + let class_ids = heap.ids_where(|data| matches!(data, HeapData::Class(_))); + HeapReader::with(heap, &mut (), |heap, ()| { + // Owned references keep every class alive until all are upgraded: + // replacing one class's hook can drop the last reference to another. + let classes: Vec = class_ids + .into_iter() + .map(|id| { + heap.inc_ref(id); + Value::Ref(id) + }) + .collect(); + for class in &classes { + let Value::Ref(class_id) = *class else { + unreachable!("collected as references") + }; + upgrade_class(class_id, heap, interns); + } + classes.drop_with(heap); + }); +} + +/// Generates the methods of `class_id` if it is a dataclass. +fn upgrade_class(class_id: HeapId, heap: &mut HeapReader<'_>, interns: &Interns) { + let Some((fields_id, options)) = legacy_dataclass(class_id, heap, interns) else { + return; + }; + let HeapReadOutput::Class(class) = heap.read(class_id) else { + unreachable!("filtered to classes") + }; + let mut installer = Installer::Upgrade { heap, interns }; + install_generated_methods(class_id, &class, fields_id, options, &mut installer) + .expect("an upgrade's writes skip the memory preflight, so cannot fail"); +} + +/// The fields mapping and options of a dataclass, or `None` for any other class. +fn legacy_dataclass(class_id: HeapId, heap: &Heap, interns: &Interns) -> Option<(HeapId, DataclassOptions)> { + let options = match namespace_member(class_id, "__dataclass_params__", heap, interns) { + Some(Value::Ref(id)) => match heap.get(*id) { + HeapData::DataclassParams(params) => params.options(), + _ => return None, + }, + _ => return None, + }; + match namespace_member(class_id, "__dataclass_fields__", heap, interns) { + Some(Value::Ref(id)) if matches!(heap.get(*id), HeapData::Dict(_)) => Some((*id, options)), + _ => None, + } +} diff --git a/crates/bashkit-monty/src/modules/dataclasses/method.rs b/crates/bashkit-monty/src/modules/dataclasses/method.rs new file mode 100644 index 000000000..ad455c7d8 --- /dev/null +++ b/crates/bashkit-monty/src/modules/dataclasses/method.rs @@ -0,0 +1,787 @@ +//! The methods `@dataclass` writes into a class namespace, and the runtime +//! behind each of them. +//! +//! CPython's decorator generates `__init__`, `__repr__`, `__eq__`, `__hash__` +//! and the frozen `__setattr__`/`__delattr__` as real functions with the +//! decoration's choices built in. A [`DataclassMethod`] is Monty's equivalent: +//! a callable holding a snapshot of what the class was decorated with, so +//! rebinding `__dataclass_fields__` or `__dataclass_params__` afterwards changes +//! nothing, as in CPython. The VM's dunder paths recognise these objects and call +//! the native code directly; explicit calls (`C.__eq__(a, b)`) go through `py_call`. + +use std::{ + collections::hash_map::DefaultHasher, + fmt::Write, + hash::{Hash, Hasher}, + mem, +}; + +use crate::{ + args::{ArgValues, KwargsValues}, + bytecode::{CallResult, VM}, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + hash::{HashValue, identity_hash}, + heap::{ContainsHeap, DropGuard, DropWithContext, HeapData, HeapId, HeapItem, HeapObjectRead, HeapReadOutput}, + intern::{Interns, StaticStrings, StringId}, + types::{ + LazyHeapSet, PyTrait, Type, + host_class::write_dataclass_repr, + instance::{class_dunder, class_name, instance_attr}, + py_trait::PyObjectIdentity, + str::allocate_string, + }, + value::Value, +}; + +/// One method `@dataclass` generated, stored in the class namespace under the +/// dunder its [`MethodKind`] names. +/// +/// **Owns heap references**: an `__init__` holds the defaults and factories it +/// was decorated with (see [`InitPlan`]), reported in `py_dec_ref_ids` and +/// `heap::for_each_child_id`. Reports itself as a `function`, as CPython's +/// generated methods are. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct DataclassMethod { + /// The decorated class's name, fixed at decoration as CPython's generated + /// `__qualname__` is; used in `repr()` and `__init__`'s argument errors. + class_name: String, + /// What the method does, with the decoration-time data it needs. + kind: MethodKind, +} + +/// The behaviour of one [`DataclassMethod`]. +/// +/// The field lists are the names `@dataclass` saw, in definition order; the +/// methods read each field as an attribute (`self.x`), as CPython's do. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum MethodKind { + /// `__init__`: binds arguments to the fields, then runs `__post_init__`. + Init(InitPlan), + /// `__repr__`: `C(x=1, y=2)`. + Repr(Vec), + /// `__eq__`: field-wise, against an instance of the same class only. + Eq(Vec), + /// `__hash__` for `eq=True, frozen=True`: the hash of the field tuple. + Hash(Vec), + /// `frozen=True`'s `__setattr__`: refuses every assignment. + FrozenSetattr, + /// `frozen=True`'s `__delattr__`: refuses every deletion. + FrozenDelattr, +} + +impl MethodKind { + /// Every parameter, `self` first, with whether each is optional, as the + /// generated `def` declares them. + fn params<'a>(&self, interns: &'a Interns) -> Vec<(&'a str, bool)> { + let mut params = vec![(self.self_param(interns), false)]; + match self { + Self::Init(plan) => params.extend( + plan.fields + .iter() + .map(|field| (interns.get_str(field.name), field.init.is_optional())), + ), + Self::Repr(_) | Self::Hash(_) => {} + Self::Eq(_) => params.push(("other", false)), + Self::FrozenSetattr => params.extend([("name", false), ("value", false)]), + Self::FrozenDelattr => params.push(("name", false)), + } + params + } + + /// The name of the `self` parameter: CPython's `__init__` renames it to + /// `__dataclass_self__` when a field is called `self`. + fn self_param(&self, interns: &Interns) -> &'static str { + match self { + Self::Init(plan) if plan.fields.iter().any(|field| interns.get_str(field.name) == "self") => { + "__dataclass_self__" + } + _ => "self", + } + } + + /// The dunder this method is stored under, and named by. + pub fn dunder(&self) -> StaticStrings { + match self { + Self::Init(_) => StaticStrings::DunderInit, + Self::Repr(_) => StaticStrings::DunderRepr, + Self::Eq(_) => StaticStrings::DunderEq, + Self::Hash(_) => StaticStrings::DunderHash, + Self::FrozenSetattr => StaticStrings::DunderSetattr, + Self::FrozenDelattr => StaticStrings::DunderDelattr, + } + } +} + +/// What a generated `__init__` was decorated with. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct InitPlan { + /// One entry per field, in signature order. + fields: Vec, + /// Whether the class defined `__post_init__` when decorated. CPython's + /// generated `__init__` calls `self.__post_init__()` only if so, looking the + /// hook up at each call. + post_init: bool, + /// Whether the decoration was `frozen=True`. A frozen `__init__` writes + /// through `object.__setattr__`; any other assigns as `self.x = x` does, so + /// a later frozen re-decoration makes construction raise, as in CPython. + frozen: bool, +} + +/// One parameter of a generated `__init__`. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct InitField { + name: StringId, + /// The default or factory captured at decoration; [`FieldInit::Unsupplied`] + /// for a required field. + init: FieldInit, +} + +/// What a generated `__init__` supplies for a field the call left unbound. +/// +/// Stored in the [`InitPlan`], and cloned per construction before any factory +/// runs: a factory re-enters the VM, where sandbox code can rebind `__init__` +/// and free the plan it came from. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum FieldInit { + /// Nothing to supply — the field is required, or the call bound it. + Unsupplied, + /// The default captured at decoration. + Default(Value), + /// The `default_factory` callable, called once per construction. + Factory(Value), +} + +impl FieldInit { + /// Whether the parameter is optional: a factory counts, as it does in + /// CPython's generated signature. + pub fn is_optional(&self) -> bool { + !matches!(self, Self::Unsupplied) + } + + /// An owned copy, taking a fresh reference to any captured value. + fn clone_with_heap(&self, heap: &impl ContainsHeap) -> Self { + match self { + Self::Unsupplied => Self::Unsupplied, + Self::Default(value) => Self::Default(value.clone_with_heap(heap)), + Self::Factory(value) => Self::Factory(value.clone_with_heap(heap)), + } + } + + /// The captured value, if any. + fn value(&self) -> Option<&Value> { + match self { + Self::Unsupplied => None, + Self::Default(value) | Self::Factory(value) => Some(value), + } + } +} + +impl DropWithContext for FieldInit { + fn drop_with(self, ctx: &mut C) { + match self { + Self::Unsupplied => {} + Self::Default(value) | Self::Factory(value) => value.drop_with(ctx), + } + } +} + +impl DataclassMethod { + /// A generated `__init__` taking ownership of the captured defaults in `fields`. + pub fn init(class_name: String, fields: Vec<(StringId, FieldInit)>, post_init: bool, frozen: bool) -> Self { + let fields = fields + .into_iter() + .map(|(name, init)| InitField { name, init }) + .collect(); + Self::new( + class_name, + MethodKind::Init(InitPlan { + fields, + post_init, + frozen, + }), + ) + } + + /// Any other generated method. + pub fn new(class_name: String, kind: MethodKind) -> Self { + Self { class_name, kind } + } + + /// Every captured value that is a heap reference, for the cycle collector: + /// a default or factory can reach back to its class. + pub fn ref_children(&self) -> impl Iterator + '_ { + let fields = match &self.kind { + MethodKind::Init(plan) => plan.fields.as_slice(), + _ => &[], + }; + fields.iter().filter_map(|field| match field.init.value() { + Some(Value::Ref(id)) => Some(*id), + _ => None, + }) + } + + /// The dunder this method is stored under. + pub fn dunder(&self) -> StaticStrings { + self.kind.dunder() + } + + /// `C.__init__`, as CPython's generated `__qualname__` reads. + fn qualname(&self) -> String { + let dunder: &'static str = self.kind.dunder().into(); + format!("{}.{dunder}", self.class_name) + } +} + +/// Releases a method that never reached the heap. +impl DropWithContext for DataclassMethod { + fn drop_with(self, ctx: &mut C) { + if let MethodKind::Init(plan) = self.kind { + for field in plan.fields { + field.init.drop_with(ctx); + } + } + } +} + +impl HeapItem for DataclassMethod { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + if let MethodKind::Init(plan) = &mut self.kind { + for field in &mut plan.fields { + if let FieldInit::Default(value) | FieldInit::Factory(value) = &mut field.init { + value.py_dec_ref_ids(stack); + } + } + } + } +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, DataclassMethod> { + fn py_type(&self, _vm: &VM<'h>) -> Type { + Type::Function + } + + fn py_len(&self, _vm: &VM<'h>) -> Option { + None + } + + fn py_eq_impl(&self, _other: &Value, _vm: &mut VM<'h>) -> RunResult> { + // Functions compare by identity, which `Value::py_eq_impl` resolves first. + Ok(None) + } + + fn py_hash(&self, _vm: &mut VM<'h>) -> RunResult> { + Ok(Some(identity_hash(self.id()))) + } + + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, _heap_ids: &mut LazyHeapSet) -> RunResult<()> { + let qualname = self.get(vm.heap).qualname(); + Ok(write!( + f, + "", + self.py_identity().encoded() + )?) + } + + /// An explicit call, `self` first: `C.__eq__(a, b)` or a bound `a.__eq__(b)`. + /// Implicit dispatch (`a == b`, `C(...)`) skips this for the direct paths below. + fn py_call(&mut self, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + call_method(self.id(), args, vm).map(CallResult::Value) + } +} + +/// Runs an explicitly called generated method. +/// +/// Arguments bind as the generated `def` would — `self` first, by position or +/// keyword — with CPython's wording. `self` must then be an instance of a +/// sandbox class: CPython's methods accept any object with the right +/// attributes, a documented divergence. +fn call_method(method_id: HeapId, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let interns = vm.interns; + let method = method_at(method_id, vm); + let qualname = method.qualname(); + let dunder = method.dunder(); + let params = method.kind.params(interns); + // Binding leaves every required slot filled, `self` among them; only an + // `__init__` field with a default can still be empty. + let mut slots = bind_def(&qualname, ¶ms, false, args, vm)?.into_iter(); + let this = slots.next().flatten().expect("binding fills the required self"); + let rest: Vec> = slots.collect(); + defer_drop_mut!(rest, vm); + defer_drop!(this, vm); + let self_id = require_instance(this, &qualname, vm)?; + match dunder { + StaticStrings::DunderInit => { + init_instance(method_id, self_id, mem::take(rest), vm)?; + Ok(Value::None) + } + StaticStrings::DunderRepr => { + let mut repr = String::new(); + let names = field_names(method_id, vm); + dataclass_repr_fmt(self_id, &names, &mut repr, vm, &mut LazyHeapSet::default())?; + Ok(allocate_string(repr, vm.heap)) + } + StaticStrings::DunderEq => { + let names = field_names(method_id, vm); + let other = required(rest, 0).clone_with_heap(vm.heap); + defer_drop!(other, vm); + Ok(dataclass_eq(self_id, &names, other, vm)?.map_or(Value::NotImplemented, Value::Bool)) + } + StaticStrings::DunderHash => { + let names = field_names(method_id, vm); + let hash = dataclass_hash(self_id, &names, vm)?; + Ok(Value::Int(hash.raw().cast_signed())) + } + StaticStrings::DunderSetattr => Err(frozen_field_error("assign to", required(rest, 0), vm)?), + StaticStrings::DunderDelattr => Err(frozen_field_error("delete", required(rest, 0), vm)?), + _ => unreachable!("MethodKind::dunder names one of the six generated methods"), + } +} + +/// The bound value of the required parameter at `idx` after `self`. +fn required(slots: &[Option], idx: usize) -> &Value { + slots[idx].as_ref().expect("binding fills required parameters") +} + +/// The `DataclassMethod` at `method_id`. +/// +/// # Panics +/// If `method_id` is not one — callers reach here only through a method they +/// already matched. +fn method_at<'a>(method_id: HeapId, vm: &'a VM<'_>) -> &'a DataclassMethod { + match vm.heap.get(method_id) { + HeapData::DataclassMethod(method) => method, + _ => unreachable!("dataclass method dispatch on another heap value"), + } +} + +/// A repr/eq/hash method's field names, cloned out so the heap is free while +/// the fields are read (which can run user `__eq__`/`__repr__`). +fn field_names(method_id: HeapId, vm: &VM<'_>) -> Vec { + match &method_at(method_id, vm).kind { + MethodKind::Repr(names) | MethodKind::Eq(names) | MethodKind::Hash(names) => names.clone(), + _ => Vec::new(), + } +} + +/// The instance `self` names, or the `TypeError` Monty raises for any other `self`. +fn require_instance(this: &Value, qualname: &str, vm: &VM<'_>) -> RunResult { + match this { + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::Instance(_)) => Ok(*id), + _ => Err(ExcType::type_error(format!( + "{qualname}() requires a class instance as self, not '{}'", + this.py_type_name(vm) + ))), + } +} + +/// The generated method `class_id` stores under `dunder`, if that member is one +/// of the matching kind — the test the VM's dunder paths make before taking +/// the direct route. +pub(crate) fn generated_method(class_id: HeapId, dunder: &str, vm: &VM<'_>) -> Option { + match class_dunder(class_id, dunder, vm) { + Some(Value::Ref(id)) => match vm.heap.get(*id) { + HeapData::DataclassMethod(method) if <&'static str>::from(method.kind.dunder()) == dunder => Some(*id), + _ => None, + }, + _ => None, + } +} + +/// [`generated_method`] for a repr/eq/hash dunder, returning its field names. +pub(crate) fn generated_fields(class_id: HeapId, dunder: &str, vm: &VM<'_>) -> Option> { + generated_method(class_id, dunder, vm).map(|id| field_names(id, vm)) +} + +/// Whether `value` is a generated `__init__`, which construction calls directly. +pub(crate) fn is_generated_init(value: &Value, vm: &VM<'_>) -> bool { + matches!(value, Value::Ref(id) if matches!( + vm.heap.get(*id), + HeapData::DataclassMethod(method) if matches!(method.kind, MethodKind::Init(_)) + )) +} + +/// The error assigning `name` raises on an instance of `class_id`, or `None` +/// when the write may proceed: CPython's frozen `__setattr__`, which refuses +/// every attribute, declared field or not. +/// +/// Every instance assignment passes through here, so it is one namespace lookup +/// for a plain class. +pub(crate) fn frozen_assignment_error(class_id: HeapId, name: &Value, vm: &mut VM<'_>) -> Option { + generated_method(class_id, "__setattr__", vm)?; + Some(match frozen_field_error("assign to", name, vm) { + Ok(error) | Err(error) => error, + }) +} + +/// `FrozenInstanceError: cannot {action} field {name!r}`, as CPython's frozen +/// `__setattr__`/`__delattr__` raise it. `Err` only when `repr(name)` raised. +fn frozen_field_error(action: &str, name: &Value, vm: &mut VM<'_>) -> RunResult { + let name = name.py_repr(vm)?; + defer_drop!(name, vm); + let message = format!("cannot {action} field {}", name.to_str(vm)?); + Ok(SimpleException::new_msg(ExcType::FrozenInstanceError, message).into()) +} + +/// Constructs an instance with a generated `__init__`, taking ownership of the +/// freshly allocated `instance` and handing it back on success. +/// +/// `init` is the caller's reference to the method, which keeps its plan alive +/// while factories and `__post_init__` re-enter the VM. +pub(crate) fn run_init(vm: &mut VM<'_>, init: &Value, instance: Value, args: ArgValues) -> RunResult { + let &Value::Ref(method_id) = init else { + unreachable!("is_generated_init matched a heap method") + }; + let mut guard = DropGuard::new(instance, vm); + let (instance, vm) = guard.as_parts(); + let &Value::Ref(instance_id) = instance else { + unreachable!("the caller just allocated the instance") + }; + let method = method_at(method_id, vm); + let qualname = method.qualname(); + let params = method.kind.params(vm.interns); + // `self` is the new instance, already bound; its slot holds a placeholder. + let slots = bind_def(&qualname, ¶ms, true, args, vm)?; + init_instance(method_id, instance_id, slots.into_iter().skip(1).collect(), vm)?; + Ok(guard.into_inner()) +} + +/// The body of a generated `__init__`, given its bound field arguments: +/// supplies the defaults and factories for the unbound ones, stores one +/// attribute per field, then calls `__post_init__` if the class had one when +/// decorated. +/// +/// Runs through [`VM::evaluate_function`] for factories and the hook, so neither +/// can suspend on an external or OS call — see `limitations/dataclasses.md`. +fn init_instance(method_id: HeapId, instance_id: HeapId, slots: Vec>, vm: &mut VM<'_>) -> RunResult<()> { + let mut guard = DropGuard::new(slots, vm); + let (slots, vm) = guard.as_parts_mut(); + let MethodKind::Init(plan) = &method_at(method_id, vm).kind else { + unreachable!("init_instance on a non-__init__ method") + }; + let (post_init, frozen) = (plan.post_init, plan.frozen); + let names: Vec = plan.fields.iter().map(|field| field.name).collect(); + fill_unbound_fields(method_id, slots, vm)?; + let (slots, vm) = guard.into_parts(); + let values = slots + .into_iter() + .map(|v| v.expect("every field is bound or filled")) + .collect(); + store_fields(instance_id, &names, values, frozen, vm)?; + if post_init { + run_post_init(instance_id, vm)?; + } + Ok(()) +} + +/// Fills each unbound slot from the field's captured default, or by calling its +/// `default_factory`, in field order. +/// +/// Everything needed is cloned out of the plan before a single factory runs: +/// past that point nothing reads the method, so a factory that rebinds +/// `__init__` cannot leave the loop reading a freed plan. Each entry is taken +/// as it is used, so an error part-way leaves the guard only those to come. +fn fill_unbound_fields(method_id: HeapId, slots: &mut [Option], vm: &mut VM<'_>) -> RunResult<()> { + let plan = snapshot_field_inits(method_id, slots, vm); + defer_drop_mut!(plan, vm); + for idx in 0..plan.len() { + // Each factory re-enters `run()` with a fresh dispatch countdown, so a + // short one reaches no checkpoint: this is the construction's only clock + // poll, as it is for the sorting key loop. + vm.heap.tracker.check_time_every(idx)?; + if slots[idx].is_some() { + continue; + } + slots[idx] = Some(match mem::replace(&mut plan[idx], FieldInit::Unsupplied) { + FieldInit::Default(default) => default, + FieldInit::Factory(factory) => { + defer_drop!(factory, vm); + vm.evaluate_function(factory, ArgValues::Empty)? + } + FieldInit::Unsupplied => unreachable!("binding rejected every unbound required field"), + }); + } + Ok(()) +} + +/// Clones every unbound field's default or factory out of the plan, in field +/// order. A slot the call already bound is skipped, so a construction that +/// supplies every argument clones nothing. +fn snapshot_field_inits(method_id: HeapId, slots: &[Option], vm: &VM<'_>) -> Vec { + let MethodKind::Init(plan) = &method_at(method_id, vm).kind else { + unreachable!("snapshot_field_inits on a non-__init__ method") + }; + slots + .iter() + .zip(&plan.fields) + .map(|(bound, field)| match bound { + Some(_) => FieldInit::Unsupplied, + None => field.init.clone_with_heap(vm.heap), + }) + .collect() +} + +/// Calls `self.__post_init__()`, as CPython's generated `__init__` ends by +/// doing. A hook removed since decoration raises `AttributeError`; its return +/// value is discarded. +fn run_post_init(instance_id: HeapId, vm: &mut VM<'_>) -> RunResult<()> { + let Some(post_init) = instance_attr(instance_id, "__post_init__", vm) else { + let class_name = class_name(instance_class(instance_id, vm), vm.heap, vm.interns).into_owned(); + return Err(ExcType::attribute_error(&class_name, "__post_init__")); + }; + defer_drop!(post_init, vm); + let result = vm.evaluate_function(post_init, ArgValues::Empty)?; + result.drop_with(vm); + Ok(()) +} + +/// Stores one bound value per field on the instance, consuming `values`. +/// +/// A frozen `__init__` writes straight to `__dict__` (CPython's +/// `object.__setattr__`); any other goes through the class's assignment check, +/// so a frozen `__setattr__` installed by a later decoration refuses it. +fn store_fields( + instance_id: HeapId, + names: &[StringId], + values: Vec, + frozen: bool, + vm: &mut VM<'_>, +) -> RunResult<()> { + defer_drop_mut!(values, vm); + let HeapReadOutput::Instance(instance) = vm.heap.read(instance_id) else { + unreachable!("init_instance runs on an instance") + }; + for i in 0..values.len() { + let value = mem::replace(&mut values[i], Value::None); + let name = Value::InternString(names[i]); + let replaced = if frozen { + instance.set_attr_unchecked(name, value, vm)? + } else { + instance.set_attr(name, value, vm)? + }; + replaced.drop_with(vm); + } + Ok(()) +} + +/// Binds `args` to `params` as a generated `def` would, returning one slot per +/// parameter: every required one filled, an optional one left `None` if unbound. +/// +/// `self_bound` marks `self` (the first parameter) as bound before the call, as +/// a constructor binds the new instance: its slot holds a `None` placeholder, +/// and CPython's arity messages and `self=` duplicate error count it. Errors +/// follow CPython's order: keywords first, then too many positionals, then +/// missing ones. Bound arguments are guarded, so every error releases them. +/// +/// Every key is a string here: `**` unpacking is the only way a non-string one +/// could arrive, and `DictMerge` raises `keywords must be strings` while +/// building the call's kwargs — before any binder runs, as CPython does. +/// +/// TODO(dataclass-keywords): a third binder alongside `args::bind_native` and +/// `args::bind_python`, all three reproducing CPython's error wording and able +/// to drift. Fold into `Signature::bind` when the `@dataclass(...)` keyword form +/// lands — not a drop-in, as that needs a static name and spec where this binds +/// a signature known only at decoration. +fn bind_def( + qualname: &str, + params: &[(&str, bool)], + self_bound: bool, + args: ArgValues, + vm: &mut VM<'_>, +) -> RunResult>> { + let n_params = params.len(); + let (pos_iter, kwargs) = args.into_parts(); + let mut slots: Vec> = (0..n_params).map(|_| None).collect(); + let first = usize::from(self_bound); + if self_bound { + slots[0] = Some(Value::None); + } + let mut guard = DropGuard::new(slots, vm); + let (slots, vm) = guard.as_parts_mut(); + + // Positionals fill the leftmost free slots; one beyond the last parameter is + // dropped here and only counted, since CPython binds keywords first: `P(1, + // 2, 3, y=4)` is "multiple values for argument 'y'", not an arity error. + let mut n_pos = first; + for (slot, value) in (first..).zip(pos_iter) { + n_pos += 1; + match slots.get_mut(slot) { + Some(unbound) => *unbound = Some(value), + None => value.drop_with(vm), + } + } + + bind_keyword_args(slots, params, kwargs, qualname, vm)?; + + if n_pos > n_params { + let required = params.iter().filter(|(_, optional)| !optional).count(); + return Err(ExcType::type_error_too_many_positional_range( + qualname, required, n_params, n_pos, 0, + )); + } + + let missing: Vec<&str> = params + .iter() + .zip(slots.iter()) + .filter(|((_, optional), slot)| !optional && slot.is_none()) + .map(|((name, _), _)| *name) + .collect(); + if !missing.is_empty() { + return Err(ExcType::type_error_missing_positional_with_names(qualname, &missing)); + } + Ok(guard.into_inner()) +} + +/// Fills the named slots from the keyword arguments. +/// +/// The iterator is guarded, so an error mid-mapping raises on the spot and the +/// pairs it never reached are still released. Keys are known to be strings — +/// the caller rejects a non-string one before any binding happens. +fn bind_keyword_args( + slots: &mut [Option], + params: &[(&str, bool)], + kwargs: KwargsValues, + qualname: &str, + vm: &mut VM<'_>, +) -> RunResult<()> { + let kwargs = kwargs.into_iter(); + defer_drop_mut!(kwargs, vm); + for (key, value) in kwargs.by_ref() { + defer_drop!(key, vm); + let name = key + .as_either_str(vm.heap) + .expect("DictMerge rejects non-string keys before the call") + .as_str(vm.interns) + .to_owned(); + // Resolved before the value is guarded, which borrows the VM. + let slot = params.iter().position(|(param, _)| *param == name); + let value = DropGuard::new(value, vm); + match slot { + Some(idx) if slots[idx].is_none() => slots[idx] = Some(value.into_inner()), + Some(_) => return Err(ExcType::type_error_duplicate_arg(qualname, &name)), + None => return Err(ExcType::type_error_unexpected_keyword(qualname, &name)), + } + } + Ok(()) +} + +/// Field-wise `__eq__`: equal only to an instance of the *same* class with equal +/// fields. Any other operand is `NotImplemented` (`Ok(None)`). +/// +/// Mirrors CPython 3.14's generated `__eq__`: identity first, then +/// `self.a == other.a and ...` left to right, stopping at the first unequal +/// pair, each compared with the `==` *operator* rather than container equality. +pub(crate) fn dataclass_eq( + self_id: HeapId, + field_names: &[StringId], + other: &Value, + vm: &mut VM<'_>, +) -> RunResult> { + let &Value::Ref(other_id) = other else { + return Ok(None); + }; + if other_id == self_id { + return Ok(Some(true)); + } + let class_id = instance_class(self_id, vm); + if !matches!(vm.heap.get(other_id), HeapData::Instance(inst) if inst.class() == class_id) { + return Ok(None); + } + // Charge a recursion level: two distinct cyclic dataclasses (`a.x = a; + // b.x = b; a == b`) re-enter here per level and would otherwise overflow + // the host stack. + let mut guard = vm.recursion_guard()?; + let vm = &mut *guard; + for name_id in field_names { + let field_name = vm.interns.get_str(*name_id).to_owned(); + // Both reads are guarded so a failing comparison below (or an early + // return) cannot strand either value. + let a = instance_attr(self_id, &field_name, vm); + defer_drop!(a, vm); + let b = instance_attr(other_id, &field_name, vm); + defer_drop!(b, vm); + match (a, b) { + (Some(a), Some(b)) if !a.py_eq_operator(b, vm)? => return Ok(Some(false)), + (Some(_), Some(_)) => {} + // The generated `__eq__` reads each field as an attribute, so one + // that resolves nowhere raises rather than comparing unequal. + _ => { + let class_name = class_name(class_id, vm.heap, vm.interns).into_owned(); + return Err(ExcType::attribute_error(&class_name, &field_name)); + } + } + } + Ok(Some(true)) +} + +/// Generated `__hash__` for `eq=True, frozen=True`: the hash of the field values +/// as a tuple, matching CPython's `hash((self.f1, ...))`. +/// +/// An unhashable field raises naming *its* type, as hashing that tuple would; +/// fields are read as attributes, so an uninitialised one raises too. +pub(crate) fn dataclass_hash(self_id: HeapId, field_names: &[StringId], vm: &mut VM<'_>) -> RunResult { + let class_id = instance_class(self_id, vm); + // Charge a recursion level, as `dataclass_eq` does: instances can cycle + // through a field, which would otherwise re-enter here per level. + let mut guard = vm.recursion_guard()?; + let vm = &mut *guard; + // Same walk as `Tuple::py_hash`, so `hash(Point(1, 2)) == hash((1, 2))`. + let mut hasher = DefaultHasher::new(); + for name_id in field_names { + let field_name = vm.interns.get_str(*name_id).to_owned(); + let value = instance_attr(self_id, &field_name, vm); + defer_drop!(value, vm); + let Some(value) = value else { + let class_name = class_name(class_id, vm.heap, vm.interns).into_owned(); + return Err(ExcType::attribute_error(&class_name, &field_name)); + }; + match value.py_hash(vm)? { + Some(h) => h.hash(&mut hasher), + None => return Err(ExcType::type_error_unhashable(&value.py_type_name(vm))), + } + } + Ok(HashValue::new(hasher.finish())) +} + +/// Generated `__repr__`: `ClassName(f1=v1, ...)`, with an instance already being +/// printed rendered as `...` as CPython's `recursive_repr` wrapper does. +/// Formatting is shared with the host-supplied `Dataclass` via +/// [`write_dataclass_repr`] so the two cannot drift. +pub(crate) fn dataclass_repr_fmt( + self_id: HeapId, + field_names: &[StringId], + f: &mut impl Write, + vm: &mut VM<'_>, + heap_ids: &mut LazyHeapSet, +) -> RunResult<()> { + if heap_ids.contains(&self_id) { + return Ok(f.write_str("...")?); + } + let class_id = instance_class(self_id, vm); + let name = class_name(class_id, vm.heap, vm.interns).to_string(); + heap_ids.insert(self_id); + // Each field is read as an attribute at the point it is written, so a field + // whose `__repr__` mutates a later one is observed, exactly as CPython's + // generated f-string does. A field that resolves nowhere raises. + let result = write_dataclass_repr(f, &name, field_names.len(), vm, heap_ids, |i, vm| { + let field_name = vm.interns.get_str(field_names[i]).to_owned(); + match instance_attr(self_id, &field_name, vm) { + Some(value) => Ok((field_name, Some(value))), + None => Err(ExcType::attribute_error(&name, &field_name)), + } + }); + heap_ids.remove(&self_id); + result +} + +/// Returns the `HeapId` of an instance's class object. +/// +/// # Panics +/// If `self_id` is not an `Instance` — callers check, or reached here through +/// a dunder lookup on one. +fn instance_class(self_id: HeapId, vm: &VM<'_>) -> HeapId { + match vm.heap.get(self_id) { + HeapData::Instance(inst) => inst.class(), + _ => unreachable!("dataclass dispatch on a non-instance"), + } +} diff --git a/crates/bashkit-monty/src/modules/dataclasses/mod.rs b/crates/bashkit-monty/src/modules/dataclasses/mod.rs new file mode 100644 index 000000000..47edf7500 --- /dev/null +++ b/crates/bashkit-monty/src/modules/dataclasses/mod.rs @@ -0,0 +1,799 @@ +//! Implementation of Python's `dataclasses` module. +//! +//! Native, in-sandbox `@dataclass`: the decorator writes a `__dataclass_fields__` +//! mapping of [`DataclassField`]s into the class namespace, then the dunders +//! CPython would generate, each a [`DataclassMethod`] holding a snapshot of the +//! decoration — no `exec`, no generated bytecode. The VM's construction and +//! value-dunder paths call those methods' native code directly (see `method`). +//! +//! See `limitations/dataclasses.md` for divergences from CPython. + +mod field; +mod legacy; +mod method; +mod options; + +pub(crate) use self::{ + field::DataclassField, + legacy::{LEGACY_DUMP_VERSION, upgrade_legacy_classes}, + method::{ + DataclassMethod, dataclass_eq, dataclass_hash, dataclass_repr_fmt, frozen_assignment_error, generated_fields, + is_generated_init, run_init, + }, + options::{DataclassOptions, DataclassParams}, +}; +use self::{ + field::{adoptable_field, field_at_id}, + method::{FieldInit, MethodKind}, +}; +use crate::{ + args::{ArgValues, FromArgs}, + builtins::Builtins, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapRead, HeapReadMut, HeapReadOutput, HeapReader}, + intern::{Interns, StaticStrings, StringId}, + modules::ModuleFunctions, + types::{ + Class, Dict, Module, PyTrait, TupleVec, allocate_tuple, + host_class::host_class_type, + instance::{class_defines, namespace_member}, + }, + value::{Marker, Value}, +}; + +/// `dataclasses` module functions — each variant is a Python-visible callable. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum DataclassesFunctions { + /// The `@dataclass` decorator. + Dataclass, + /// `is_dataclass(obj)` — true for a dataclass class or instance. + IsDataclass, + /// `field(...)` — builds the `Field` a class body binds and the decorator + /// then adopts. + Field, + /// The decorator `@dataclass(...)` returns while it waits for the class, + /// carrying the bound options so `d = dataclass(frozen=True)` then `@d` + /// works. Named for the user-visible decorator, not the variant. + #[strum(serialize = "dataclass")] + Configured(DataclassOptions), +} + +/// Creates the `dataclasses` module and allocates it on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Dataclasses, vm.interns); + module.set_attr( + StaticStrings::Dataclass, + Value::ModuleFunction(ModuleFunctions::Dataclasses(DataclassesFunctions::Dataclass)), + vm, + ); + module.set_attr( + StaticStrings::IsDataclass, + Value::ModuleFunction(ModuleFunctions::Dataclasses(DataclassesFunctions::IsDataclass)), + vm, + ); + module.set_attr( + StaticStrings::FrozenInstanceError, + Value::Builtin(Builtins::ExcType(ExcType::FrozenInstanceError)), + vm, + ); + module.set_attr( + StaticStrings::Field, + Value::ModuleFunction(ModuleFunctions::Dataclasses(DataclassesFunctions::Field)), + vm, + ); + // `MISSING` is a bare sentinel compared by identity, so it needs no state + // beyond its name — a `Marker` like `sys.stdout`, with a type of its own. + module.set_attr( + StaticStrings::Missing, + Value::Marker(Marker(StaticStrings::Missing)), + vm, + ); + vm.heap.allocate_as(module).into_id() +} + +/// Dispatches a `dataclasses` module function call. +pub(super) fn call(vm: &mut VM<'_>, func: DataclassesFunctions, args: ArgValues) -> RunResult { + match func { + DataclassesFunctions::Dataclass => dataclass_decorator(vm, args), + DataclassesFunctions::IsDataclass => is_dataclass(vm, args), + DataclassesFunctions::Field => field::field(vm, args), + // The options are already bound; this call supplies the class. + DataclassesFunctions::Configured(options) => { + let ConfiguredArgs { cls } = ConfiguredArgs::from_args(args, vm)?; + apply_dataclass(vm, cls, options) + } + } +} + +/// The `@dataclass` decorator, in both spellings: applied bare the class +/// arrives here directly, while `@dataclass(...)` has none yet and gets back a +/// [`DataclassesFunctions::Configured`] that receives it on the next call. +fn dataclass_decorator(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let DataclassArgs { + cls, + init, + repr, + eq, + order, + unsafe_hash, + frozen, + match_args, + kw_only, + slots, + weakref_slot, + } = DataclassArgs::from_args(args, vm)?; + // CPython's `dataclass` is a `def`, so it type-checks nothing and takes each + // option's truthiness. That runs user code — a `__bool__` may raise — so + // `cls` and all ten flags are guarded before the first read. + let mut guard = DropGuard::new( + [ + cls, + init, + repr, + eq, + order, + unsafe_hash, + frozen, + match_args, + kw_only, + slots, + weakref_slot, + ], + vm, + ); + let (values, vm) = guard.as_parts(); + let mut truthy = [false; 10]; + for (slot, flag) in truthy.iter_mut().zip(&values[1..]) { + *slot = flag.py_bool(vm)?; + } + let [ + init, + repr, + eq, + order, + unsafe_hash, + frozen, + match_args, + kw_only, + slots, + weakref_slot, + ] = truthy; + let options = DataclassOptions { eq, frozen }; + // Options Monty does not implement are refused when set away from their + // CPython default, rather than accepted and ignored. + let unimplemented = [ + ("init", init, true), + ("repr", repr, true), + ("order", order, false), + ("unsafe_hash", unsafe_hash, false), + ("match_args", match_args, true), + ("kw_only", kw_only, false), + ("slots", slots, false), + ("weakref_slot", weakref_slot, false), + ] + .into_iter() + .find(|&(_, given, default)| given != default); + // Only truthiness is kept, so the flags are released here; `cls` alone lives + // on, into the return value. + let (values, vm) = guard.into_parts(); + let [cls, flags @ ..] = values; + flags.drop_with(vm); + match unimplemented { + Some((name, _, _)) => { + cls.drop_with(vm); + Err(ExcType::not_implemented(format!("dataclass() does not yet support the {name} option")).into()) + } + // `@dataclass(...)`: no class yet, so hand back the configured decorator. + None if matches!(cls, Value::None) => Ok(Value::ModuleFunction(ModuleFunctions::Dataclasses( + DataclassesFunctions::Configured(options), + ))), + None => apply_dataclass(vm, cls, options), + } +} + +/// `@dataclass` arguments, mirroring CPython's +/// `dataclass(cls=None, /, *, init=True, repr=True, ...)`. +/// +/// Raw `Value` fields because CPython's `def` type-checks nothing; the body +/// takes each option's truthiness instead. +#[derive(FromArgs)] +#[from_args(name = "dataclass", style = def)] +struct DataclassArgs { + #[from_args(pos_only, default = Value::None)] + cls: Value, + #[from_args(kw_only, default = Value::Bool(true))] + init: Value, + #[from_args(kw_only, default = Value::Bool(true))] + repr: Value, + #[from_args(kw_only, default = Value::Bool(true))] + eq: Value, + #[from_args(kw_only, default = Value::Bool(false))] + order: Value, + #[from_args(kw_only, default = Value::Bool(false))] + unsafe_hash: Value, + #[from_args(kw_only, default = Value::Bool(false))] + frozen: Value, + #[from_args(kw_only, default = Value::Bool(true))] + match_args: Value, + #[from_args(kw_only, default = Value::Bool(false))] + kw_only: Value, + #[from_args(kw_only, default = Value::Bool(false))] + slots: Value, + #[from_args(kw_only, default = Value::Bool(false))] + weakref_slot: Value, +} + +/// The class a [`DataclassesFunctions::Configured`] decorator is waiting for. +/// +/// CPython's `dataclass` closes over a plain `def wrap(cls)`, so the class binds +/// positionally *or* by keyword, and the arity errors name that closure rather +/// than `dataclass` itself. Raw `Value` for [`DataclassArgs`]' reason: a `def` +/// type-checks nothing, and `apply_dataclass` makes the class check the body +/// would. +#[derive(FromArgs)] +#[from_args(name = "dataclass..wrap", style = def)] +struct ConfiguredArgs { + cls: Value, +} + +/// Writes `__dataclass_fields__`, `__dataclass_params__` and the generated +/// dunders into the class namespace, and returns the class itself. +/// +/// Ownership of `cls` passes straight through to the return value, so no extra +/// refcount work is needed on the happy path; the guard releases it on every +/// path that rejects the class instead. +fn apply_dataclass(vm: &mut VM<'_>, cls: Value, options: DataclassOptions) -> RunResult { + let mut guard = DropGuard::new(cls, vm); + let (cls, vm) = guard.as_parts(); + // Read once and pass the handle down: everything below then works from a + // value already known to be a class, and the guard's reference keeps it alive. + let Value::Ref(class_id) = cls else { + return Err(non_class_error(cls, vm)); + }; + let HeapReadOutput::Class(class) = vm.heap.read(*class_id) else { + return Err(non_class_error(cls, vm)); + }; + let fields = build_dataclass_fields(&class, vm)?; + let Value::Ref(fields_id) = fields else { + unreachable!("the fields mapping is a dict") + }; + // Fields first, so nothing owns the mapping while the params allocation + // can still fail; a class left with fields alone acts as a default one. + store_dataclass_fields(&class, fields, vm)?; + // Now that the mapping owns them, the `field()` objects the class body left + // as attributes can be rewritten to what CPython leaves behind. + rewrite_field_attributes(&class, fields_id, vm)?; + store_dataclass_params(&class, options, vm)?; + install_generated_methods(*class_id, &class, fields_id, options, &mut Installer::Decorate(vm))?; + store_match_args(&class, fields_id, vm)?; + Ok(guard.into_inner()) +} + +/// `dataclass()` applied to something that is not a class. +fn non_class_error(cls: &Value, vm: &VM<'_>) -> RunError { + let type_name = cls.py_type_name(vm); + SimpleException::new_msg( + ExcType::TypeError, + format!("dataclass() should be called on a class, not '{type_name}'"), + ) + .into() +} + +/// Builds the `name -> Field` mapping for `class` from its `__annotations__`: +/// the annotated names in definition order, minus `ClassVar` entries, each +/// owning the default the class namespace bound for it (`y: int = 5`). +/// +/// Also where a class body Monty cannot yet honour is rejected, so an +/// unimplemented feature raises rather than producing a subtly wrong class +/// (see `limitations/dataclasses.md`). The fields are guarded throughout, so a +/// rejection releases the defaults already captured. +fn build_dataclass_fields<'h>(class: &HeapRead<'h, Class>, vm: &mut VM<'h>) -> RunResult { + let fields = collect_annotated_fields(class, vm); + let mut guard = DropGuard::new(fields, vm); + let (fields, vm) = guard.as_parts(); + // Field validation runs first, so a class CPython would reject reports + // CPython's own message and the Monty-only guards can only fire after. + validate_fields(vm, fields)?; + let (fields, vm) = guard.into_parts(); + allocate_fields_dict(vm, fields) +} + +/// Allocates the dict `__dataclass_fields__` holds, consuming the collected +/// fields. The dict owns every `Field` from its first insertion, so a failure +/// part-way releases them with it. +fn allocate_fields_dict(vm: &mut VM<'_>, fields: Vec) -> RunResult { + let dict = vm.heap.allocate_as(Dict::with_capacity(fields.len())); + let mut guard = DropGuard::new(dict, vm); + let (dict, vm) = guard.as_parts_mut(); + let dict = dict.read(vm.heap); + for field_value in fields { + // Consumed rather than matched: the reference moves into the dict below, + // so the original must not also be released. + let Some(field_id) = field_value.into_ref_id() else { + unreachable!("collection produces only heap fields") + }; + let name = field_at_id(vm.heap, field_id) + .expect("collection produces only `Field`s") + .name() + .expect("collection adopts every field"); + // One `field()` object bound under two names is adopted twice and keyed + // by the second, so a replacement does happen — CPython collapses the + // pair the same way. A dict rejected by the memory limit releases the + // field it was handed. + let replaced = dict.set(Value::InternString(name), Value::Ref(field_id), vm)?; + replaced.drop_with(vm); + } + Ok(guard.into_inner().into_value()) +} + +/// Writes `__dataclass_fields__` into the class namespace, taking ownership of +/// `fields`. Re-decorating replaces the previous mapping, which nothing else +/// owns once it is out of the namespace. +fn store_dataclass_fields<'h>(class: &HeapReadMut<'h, Class>, fields: Value, vm: &mut VM<'h>) -> RunResult<()> { + let name = Value::InternString(vm.interns.intern_static(StaticStrings::DataclassFields)); + let replaced = class.set_attr(name, fields, vm)?; + replaced.drop_with(vm); + Ok(()) +} + +/// Writes `__dataclass_params__` into the class namespace, as CPython's +/// `_DataclassParams` records the same options. +/// +/// A record only: the generated methods carry their own copy of what they +/// need, so rebinding this entry changes nothing, as in CPython. +fn store_dataclass_params<'h>( + class: &HeapReadMut<'h, Class>, + options: DataclassOptions, + vm: &mut VM<'h>, +) -> RunResult<()> { + let params = vm.heap.allocate_as(DataclassParams::new(options)).into_value(); + let name = Value::InternString(vm.interns.intern_static(StaticStrings::DataclassParams)); + let replaced = class.set_attr(name, params, vm)?; + replaced.drop_with(vm); + Ok(()) +} + +/// Writes `__match_args__` into the class namespace: the field names in +/// definition order, so `case Point(x, y):` binds positionally. A class that +/// defines its own `__match_args__` keeps it, as in CPython. +fn store_match_args<'h>(class: &HeapReadMut<'h, Class>, fields_id: HeapId, vm: &mut VM<'h>) -> RunResult<()> { + let name_id = vm.interns.intern_static(StaticStrings::MatchArgsDunder); + let namespace = class.get(vm.heap).namespace(); + if namespace.get_by_str("__match_args__", vm.heap, vm.interns).is_some() { + return Ok(()); + } + let names: TupleVec = adopted_field_ids(fields_id, vm.heap) + .into_iter() + .map(|(name, _)| Value::InternString(name)) + .collect(); + let match_args = allocate_tuple(names, vm.heap); + let replaced = class.set_attr(Value::InternString(name_id), match_args, vm)?; + replaced.drop_with(vm); + Ok(()) +} + +/// Writes the dunders CPython's `_process_class` generates, each a +/// [`DataclassMethod`] built from the fields just stored. +/// +/// `__init__`, `__repr__` and `__eq__` are only added when the class body did +/// not define them. Frozen classes refuse a body `__setattr__`/`__delattr__` +/// with CPython's `TypeError`. `__hash__` follows CPython's `_hash_action` +/// table and overwrites whatever the body left, as CPython assigns it outright. +/// [`Installer::Upgrade`] changes three of those choices; see its docs. +fn install_generated_methods<'h>( + class_id: HeapId, + class: &HeapReadMut<'h, Class>, + fields_id: HeapId, + options: DataclassOptions, + installer: &mut Installer<'_, 'h>, +) -> RunResult<()> { + let class_name = class + .get(installer.heap()) + .name() + .as_str(installer.interns()) + .to_owned(); + let names: Vec = adopted_field_ids(fields_id, installer.heap()) + .into_iter() + .map(|(name, _)| name) + .collect(); + // Read before anything is added: CPython's `has_explicit_hash` sees the body + // alone. A `__hash__ = None` beside a body `__eq__` is the opt-out `type` + // inserted, not one the author wrote, so a generated hash replaces it. + let explicit_hash = installer + .member(class_id, "__hash__") + .is_some_and(|hash| !(matches!(hash, Value::None) && installer.defines(class_id, "__eq__"))); + let post_init = installer.is_decorating() && installer.defines(class_id, "__post_init__"); + + if !installer.defines(class_id, "__init__") { + let init = DataclassMethod::init( + class_name.clone(), + init_fields(fields_id, installer.heap()), + post_init, + options.frozen, + ); + installer.set_method(class, init)?; + } + if !installer.defines(class_id, "__repr__") { + let repr = DataclassMethod::new(class_name.clone(), MethodKind::Repr(names.clone())); + installer.set_method(class, repr)?; + } + if options.eq && !installer.defines(class_id, "__eq__") { + let eq = DataclassMethod::new(class_name.clone(), MethodKind::Eq(names.clone())); + installer.set_method(class, eq)?; + } + if options.frozen { + for kind in [MethodKind::FrozenSetattr, MethodKind::FrozenDelattr] { + let dunder: &'static str = kind.dunder().into(); + if installer.is_decorating() && installer.defines(class_id, dunder) { + return Err(ExcType::type_error(format!( + "Cannot overwrite attribute {dunder} in class {class_name}" + ))); + } + installer.set_method(class, DataclassMethod::new(class_name.clone(), kind))?; + } + } + // CPython's `_hash_action` rows for `unsafe_hash=False`, which Monty requires. + match (options.eq, options.frozen, explicit_hash) { + (true, true, false) => { + let hash = DataclassMethod::new(class_name, MethodKind::Hash(names)); + installer.set_method(class, hash) + } + (true, false, false) => installer.set_member(class, StaticStrings::DunderHash, Value::None), + _ => Ok(()), + } +} + +/// Each field's `__init__` parameter: its name and the default or factory +/// captured at decoration, as owned references for the method to hold. +fn init_fields(fields_id: HeapId, heap: &Heap) -> Vec<(StringId, FieldInit)> { + adopted_field_ids(fields_id, heap) + .into_iter() + .map(|(name, field_id)| { + let field = field_at_id(heap, field_id).expect("adopted ids name fields"); + let init = match (field.default(), field.default_factory()) { + (Some(default), _) => FieldInit::Default(default.clone_with_heap(heap)), + (None, Some(factory)) => FieldInit::Factory(factory.clone_with_heap(heap)), + (None, None) => FieldInit::Unsupplied, + }; + (name, init) + }) + .collect() +} + +/// Who is installing the generated methods, holding what each needs to write. +enum Installer<'a, 'h> { + /// `@dataclass` itself, as CPython's `_process_class` would. + Decorate(&'a mut VM<'h>), + /// A dataclass from a version 13 dump (see `legacy`), upgraded inside + /// `Dump::load` before any VM exists. The 1.x rules win: no `__post_init__` + /// is called (1.x refused one in the body, and never ran one attached later), + /// a body `__setattr__`/`__delattr__` is replaced rather than refused (1.x + /// kept the class frozen regardless), and no write can fail. + Upgrade { + heap: &'a mut HeapReader<'h>, + interns: &'a Interns, + }, +} + +impl<'h> Installer<'_, 'h> { + fn heap(&self) -> &HeapReader<'h> { + match self { + Self::Decorate(vm) => vm.heap, + Self::Upgrade { heap, .. } => heap, + } + } + + fn interns(&self) -> &Interns { + match self { + Self::Decorate(vm) => vm.interns, + Self::Upgrade { interns, .. } => interns, + } + } + + fn is_decorating(&self) -> bool { + matches!(self, Self::Decorate(_)) + } + + /// Borrows `name` from the class's own namespace. + fn member(&self, class_id: HeapId, name: &str) -> Option<&Value> { + namespace_member(class_id, name, self.heap(), self.interns()) + } + + /// Whether the class's own namespace defines `name`. + fn defines(&self, class_id: HeapId, name: &str) -> bool { + self.member(class_id, name).is_some() + } + + /// Allocates `method` and stores it in the class namespace under its dunder. + fn set_method(&mut self, class: &HeapReadMut<'h, Class>, method: DataclassMethod) -> RunResult<()> { + let dunder = method.dunder(); + let method = self.heap().allocate_as(method).into_value(); + self.set_member(class, dunder, method) + } + + /// Stores `value` in the class namespace under `name`, releasing what it + /// replaces. Only the decorator's write can fail, on its memory preflight; + /// an upgrade adds at most six entries to a class and skips it. + fn set_member(&mut self, class: &HeapReadMut<'h, Class>, name: StaticStrings, value: Value) -> RunResult<()> { + match self { + Self::Decorate(vm) => { + let name = Value::InternString(vm.interns.intern_static(name)); + let replaced = class.set_attr(name, value, vm)?; + replaced.drop_with(&mut **vm); + } + Self::Upgrade { heap, interns } => { + let replaced = class.set_interned_attr(interns.intern_static(name), value, heap, interns); + replaced.drop_with(&mut **heap); + } + } + Ok(()) + } +} + +/// Rewrites the class attribute each `field()` left behind, as CPython does: +/// a plain default becomes the attribute, and a field with only a factory — +/// which has no single value to expose — loses it. +/// +/// Runs once the fields are stored, so the mapping is the list of names to fix. +fn rewrite_field_attributes<'h>(class: &HeapReadMut<'h, Class>, fields_id: HeapId, vm: &mut VM<'h>) -> RunResult<()> { + for (name, field_id) in adopted_field_ids(fields_id, vm.heap) { + // Only an attribute that *is* the field object needs rewriting; a plain + // `x: int = 5` already binds the value CPython would leave behind. + let bound = class + .get(vm.heap) + .namespace() + .get_by_str(vm.interns.get_str(name), vm.heap, vm.interns); + if !matches!(bound, Some(Value::Ref(id)) if *id == field_id) { + continue; + } + let default = + field_at_id(vm.heap, field_id).and_then(|field| field.default().map(|v| v.clone_with_heap(vm.heap))); + let name = Value::InternString(name); + let replaced = match default { + Some(default) => class.set_attr(name, default, vm)?, + None => class.pop_attr(&name, vm)?, + }; + replaced.drop_with(vm); + } + Ok(()) +} + +/// The `(name, field_id)` of every field in a `__dataclass_fields__` dict. +/// +/// The name is the mapping **key**, not the live `Field.name`: adoption writes +/// the name into the `field()` object itself, so one object shared by two +/// classes ends up reporting the *second* class's name. +fn adopted_field_ids(fields_id: HeapId, heap: &Heap) -> Vec<(StringId, HeapId)> { + let HeapData::Dict(fields) = heap.get(fields_id) else { + return Vec::new(); + }; + fields + .iter() + .filter_map(|(key, value)| match (key, value) { + (Value::InternString(name), Value::Ref(id)) if field_at_id(heap, *id).is_some() => Some((*name, *id)), + _ => None, + }) + .collect() +} + +/// Collects the dataclass fields from `__annotations__`, in definition order, +/// dropping `ClassVar` entries, as owned references to heap `Field`s. +/// +/// A class-body value that is already a `field()` result is **adopted in place** +/// — the same object gains the name and annotation and goes on to +/// `__dataclass_fields__`, as CPython's decorator does — so +/// `C.__dataclass_fields__['x'] is f`. Anything else is an ordinary default and +/// gets a fresh `Field` built around it. +/// +/// The returned references are owned, so a caller that discards them must +/// release them (`drop_with`). +fn collect_annotated_fields<'h>(class: &HeapRead<'h, Class>, vm: &mut VM<'h>) -> Vec { + let names = annotated_field_names(class, vm); + let mut guard = DropGuard::new(Vec::with_capacity(names.len()), vm); + let (fields, vm) = guard.as_parts_mut(); + for name_id in names { + let namespace = class.get(vm.heap).namespace(); + // Captured now, as CPython bakes it into the generated `__init__`: + // rebinding the class attribute later must not change it. + let bound = namespace + .get_by_str(vm.interns.get_str(name_id), vm.heap, vm.interns) + .map(|v| v.clone_with_heap(vm.heap)); + let annotation = field_annotation(class, name_id, vm); + // The class body bound a `field()` result: it *is* the field, so it + // takes the name and annotation and the list keeps that reference. + // Anything else is a plain default, wrapped in a field of its own. + if let Some(field_id) = adoptable_field(bound.as_ref(), vm) { + let HeapReadOutput::DataclassField(field) = vm.heap.read(field_id) else { + unreachable!("adoptable_field matched the variant") + }; + let replaced = field.get_mut(vm.heap).adopt(name_id, annotation); + replaced.drop_with(vm); + fields.push(bound.expect("adoptable_field matched a bound value")); + } else { + let field = DataclassField::new(name_id, annotation, bound); + fields.push(vm.heap.allocate_as(field).into_value()); + } + } + guard.into_parts().0 +} + +/// The annotated field names in definition order, minus `ClassVar` entries. +/// +/// Names alone, so the collection loop can take the heap mutably instead of +/// holding a borrow of the annotations dict across an allocation. +fn annotated_field_names<'h>(class: &HeapRead<'h, Class>, vm: &VM<'h>) -> Vec { + let Some(annotations) = annotations_dict(class, vm) else { + return Vec::new(); + }; + annotations + .into_iter() + .filter_map(|(key, annotation)| match key { + Value::InternString(name_id) if !is_classvar(&annotation_text(annotation, vm)) => Some(*name_id), + _ => None, + }) + .collect() +} + +/// One field's annotation, cloned as an owned reference for the `Field` to hold. +fn field_annotation<'h>(class: &HeapRead<'h, Class>, name: StringId, vm: &VM<'h>) -> Value { + annotations_dict(class, vm) + .and_then(|annotations| annotations.get_by_str(vm.interns.get_str(name), vm.heap, vm.interns)) + .map_or(Value::None, |annotation| annotation.clone_with_heap(vm.heap)) +} + +/// The class's `__annotations__` dict, or `None` for a class body with none. +fn annotations_dict<'a, 'h>(class: &HeapRead<'h, Class>, vm: &'a VM<'h>) -> Option<&'a Dict> { + match class + .get(vm.heap) + .namespace() + .get_by_str("__annotations__", vm.heap, vm.interns) + { + Some(Value::Ref(id)) => match vm.heap.get(*id) { + HeapData::Dict(annotations) => Some(annotations), + _ => None, + }, + _ => None, + } +} + +/// A stringized annotation as text, or `""` for the non-string annotations +/// Monty never produces (it always stores annotations as source text). +fn annotation_text(annotation: &Value, vm: &VM<'_>) -> String { + annotation + .as_either_str(vm.heap) + .map(|s| s.as_str(vm.interns).to_owned()) + .unwrap_or_default() +} + +/// Rejects field lists Monty cannot honour, in CPython's checking order. +/// +/// CPython validates defaults per field as it collects them, so a mutable +/// default is reported before the whole-list non-default-after-default check. +fn validate_fields(vm: &mut VM<'_>, fields: &[Value]) -> RunResult<()> { + for field_value in fields { + // Read out first: hashing a default needs the heap mutably. + let Some((name, annotation_text, default)) = read_field(field_value, vm) else { + continue; + }; + defer_drop!(default, vm); + let name = vm.interns.get_str(name).to_owned(); + if is_initvar(&annotation_text) { + return Err(ExcType::not_implemented(format!( + "dataclass() does not yet support InitVar (field {name}), which would become an ordinary field" + )) + .into()); + } + if let Some(default) = default { + // CPython's rule is hashability, not a list/dict/set type check, so + // a class with `__hash__ = None` is rejected the same way. A factory + // is exempt: it is the sanctioned way to have a mutable default. + if default.py_hash(vm)?.is_none() { + let ty = default.py_type_name(vm); + return Err(ExcType::value_error(format!( + "mutable default for field {name} is not allowed: use default_factory" + ))); + } + } + } + // CPython rejects the class outright rather than failing at construction. + if let Some((prev, field)) = first_non_default_after_default(fields, vm) { + let (prev, field) = (vm.interns.get_str(prev), vm.interns.get_str(field)); + return Err(ExcType::type_error(format!( + "non-default argument '{field}' follows default argument '{prev}'" + ))); + } + Ok(()) +} + +/// A collected field's name, annotation text, and a **cloned** default — the +/// three things validation needs, read before it takes the heap mutably. +fn read_field(field: &Value, vm: &VM<'_>) -> Option<(StringId, String, Option)> { + let Value::Ref(id) = field else { return None }; + let field = field_at_id(vm.heap, *id)?; + let annotation = field.annotation().map_or_else(String::new, |a| annotation_text(a, vm)); + Some(( + field.name().expect("collection adopts every field"), + annotation, + field.default().map(|d| d.clone_with_heap(vm.heap)), + )) +} + +/// The first `(defaulted, non_defaulted)` field pair that would produce an +/// invalid `__init__` signature, or `None` when the order is valid. +/// +/// A `default_factory` counts as a default, as it does in CPython's generated +/// signature. +fn first_non_default_after_default(fields: &[Value], vm: &VM<'_>) -> Option<(StringId, StringId)> { + let mut last_default = None; + fields.iter().find_map(|field| { + let Value::Ref(id) = field else { return None }; + let field = field_at_id(vm.heap, *id)?; + let name = field.name().expect("collection adopts every field"); + match (field.has_default(), last_default) { + (true, _) => { + last_default = Some(name); + None + } + (false, Some(prev)) => Some((prev, name)), + (false, None) => None, + } + }) +} + +/// Whether a stringized annotation denotes `typing.ClassVar`, so the field is +/// excluded. +/// +/// Detection is textual where CPython resolves the annotation through the +/// defining module, so neither the import nor a dotted spelling's module is +/// checked — both divergences are in `limitations/dataclasses.md`. +fn is_classvar(annotation: &str) -> bool { + annotation_head(annotation, "ClassVar") +} + +/// Whether a stringized annotation denotes `dataclasses.InitVar`. Matched the +/// same way as [`is_classvar`], and with the same textual-only caveats. +fn is_initvar(annotation: &str) -> bool { + annotation_head(annotation, "InitVar") +} + +/// Whether a stringized annotation names `name`, bare, subscripted, or +/// dotted (`typing.ClassVar[int]`), ignoring surrounding whitespace and quotes. +/// +/// Quotes must be stripped because a quoted annotation (`x: "ClassVar[int]"`) +/// is stringized with its quotes intact. The subscript is split off before the +/// qualifier check so a dotted type argument (`ClassVar[a.b]`) still matches. +fn annotation_head(annotation: &str, name: &str) -> bool { + let s = annotation.trim().trim_matches(|c| c == '\'' || c == '"').trim(); + let head = s.split_once('[').map_or(s, |(head, _)| head).trim_end(); + head.rsplit('.').next() == Some(name) +} + +/// Whether `class_id` names a dataclass: CPython's `hasattr(cls, +/// '__dataclass_fields__')`, whatever the attribute now holds. +pub(crate) fn is_dataclass_class(class_id: HeapId, vm: &VM<'_>) -> bool { + let name: &'static str = StaticStrings::DataclassFields.into(); + class_defines(class_id, name, vm) +} + +/// `is_dataclass(obj)` — true when `obj` is a dataclass **class** or an +/// **instance** of one (matching CPython, which accepts both). +fn is_dataclass(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let arg = args.get_one_arg("is_dataclass", vm.heap)?; + let result = match &arg { + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Class(_) => is_dataclass_class(*id, vm), + HeapData::Instance(instance) => is_dataclass_class(instance.class(), vm), + // Host-backed instances and classes carry dataclass-ness as a flag + // set by the host when the class crossed the wire. + HeapData::HostClass(hc) => host_class_type(vm.heap, hc.class_id()).is_dataclass(), + HeapData::HostClassType(ty) => ty.is_dataclass(), + _ => false, + }, + _ => false, + }; + arg.drop_with(vm); + Ok(Value::Bool(result)) +} diff --git a/crates/bashkit-monty/src/modules/dataclasses/options.rs b/crates/bashkit-monty/src/modules/dataclasses/options.rs new file mode 100644 index 000000000..b008165c5 --- /dev/null +++ b/crates/bashkit-monty/src/modules/dataclasses/options.rs @@ -0,0 +1,124 @@ +//! The `@dataclass(...)` options, and the `__dataclass_params__` object a +//! decorated class keeps them in. + +use std::fmt::Write; + +use crate::{ + bytecode::{CallResult, VM}, + exception_private::{ExcType, ExcTypeExt, RunResult}, + hash::{HashValue, identity_hash}, + heap::{HeapId, HeapItem, HeapObjectRead}, + types::{LazyHeapSet, PyTrait, Type}, + value::{EitherStr, Value}, +}; + +/// The `@dataclass(...)` options Monty implements. +/// +/// Small and `Copy`, so it doubles as the payload of the *configured decorator* +/// (`dataclass(frozen=True)`) without a heap allocation. Every other CPython +/// flag is rejected at the call, so each is either stored here or known to hold +/// its default. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) struct DataclassOptions { + /// Synthesize a field-wise `__eq__` (CPython's `eq`, default `True`). + pub eq: bool, + /// Reject attribute assignment, and hash by field values when `eq` is also + /// set (CPython's `frozen`, default `False`). + pub frozen: bool, +} + +impl Default for DataclassOptions { + /// CPython's defaults: `eq=True, frozen=False`. + fn default() -> Self { + Self { + eq: true, + frozen: false, + } + } +} + +/// The `__dataclass_params__` object `@dataclass` writes into a class +/// namespace: CPython's `dataclasses._DataclassParams`. +/// +/// A record of the decoration only: the generated methods were built from the +/// options, so rebinding `__dataclass_params__` changes nothing, as in CPython. +/// Holds no heap references. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct DataclassParams { + options: DataclassOptions, +} + +impl DataclassParams { + /// Wraps the options the decorator was called with. + #[must_use] + pub fn new(options: DataclassOptions) -> Self { + Self { options } + } + + /// The options the class was decorated with, which `legacy` rebuilds the + /// generated methods from. + #[must_use] + pub(super) fn options(&self) -> DataclassOptions { + self.options + } +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, DataclassParams> { + fn py_type(&self, _vm: &VM<'h>) -> Type { + Type::DataclassParams + } + + fn py_len(&self, _vm: &VM<'h>) -> Option { + None + } + + fn py_eq_impl(&self, _other: &Value, _vm: &mut VM<'h>) -> RunResult> { + // `_DataclassParams` defines no `__eq__`, so it compares by identity, + // which `Value::py_eq_impl` resolves before ever reaching here. + Ok(None) + } + + fn py_hash(&self, _vm: &mut VM<'h>) -> RunResult> { + Ok(Some(identity_hash(self.id()))) + } + + /// CPython's `_DataclassParams.__repr__`, flag for flag. The eight + /// unimplemented options print as constants, which cannot misreport a class + /// because any other value is refused at decoration. + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, _heap_ids: &mut LazyHeapSet) -> RunResult<()> { + let options = self.get(vm.heap).options; + Ok(write!( + f, + "_DataclassParams(init=True,repr=True,eq={},order=False,unsafe_hash=False,frozen={},\ + match_args=True,kw_only=False,slots=False,weakref_slot=False)", + python_bool(options.eq), + python_bool(options.frozen), + )?) + } + + /// Every flag CPython exposes; the unimplemented ones read as the defaults + /// the decorator insists on. + fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { + let attr_str = attr.as_str(vm.interns); + let options = self.get(vm.heap).options; + let value = match attr_str { + "eq" => Value::Bool(options.eq), + "frozen" => Value::Bool(options.frozen), + "init" | "repr" | "match_args" => Value::Bool(true), + "order" | "unsafe_hash" | "kw_only" | "slots" | "weakref_slot" => Value::Bool(false), + _ => return Err(ExcType::attribute_error("_DataclassParams", attr_str)), + }; + Ok(Some(CallResult::Value(value))) + } +} + +/// Python's spelling of a bool, for the constant flags in the repr above. +fn python_bool(value: bool) -> &'static str { + if value { "True" } else { "False" } +} + +impl HeapItem for DataclassParams { + fn py_dec_ref_ids(&mut self, _stack: &mut Vec) { + // Two bools, no heap references. + } +} diff --git a/crates/bashkit-monty/src/modules/datetime.rs b/crates/bashkit-monty/src/modules/datetime.rs new file mode 100644 index 000000000..597a7bc57 --- /dev/null +++ b/crates/bashkit-monty/src/modules/datetime.rs @@ -0,0 +1,46 @@ +//! Implementation of the `datetime` module. +//! +//! This module exposes a minimal phase-1 surface: +//! - `date` +//! - `datetime` +//! - `time` +//! - `timedelta` +//! - `timezone` +//! +//! Behavior for constructors, arithmetic, and classmethods is implemented by the +//! corresponding runtime types. + +use crate::{ + builtins::Builtins, + bytecode::VM, + heap::{HeapData, HeapId}, + intern::StaticStrings, + types::{Module, Type}, + value::Value, +}; + +/// Creates the `datetime` module and allocates it on the heap. +/// +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Datetime, vm.interns); + + module.set_attr(StaticStrings::Date, Value::Builtin(Builtins::Type(Type::Date)), vm); + module.set_attr( + StaticStrings::Datetime, + Value::Builtin(Builtins::Type(Type::DateTime)), + vm, + ); + module.set_attr(StaticStrings::Time, Value::Builtin(Builtins::Type(Type::Time)), vm); + module.set_attr( + StaticStrings::Timedelta, + Value::Builtin(Builtins::Type(Type::TimeDelta)), + vm, + ); + module.set_attr( + StaticStrings::Timezone, + Value::Builtin(Builtins::Type(Type::TimeZone)), + vm, + ); + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} diff --git a/crates/bashkit-monty/src/modules/decimal.rs b/crates/bashkit-monty/src/modules/decimal.rs new file mode 100644 index 000000000..4dc013361 --- /dev/null +++ b/crates/bashkit-monty/src/modules/decimal.rs @@ -0,0 +1,148 @@ +//! The `decimal` module: `Decimal`, `Context`, the signals and the context functions. +//! +//! The types live in `types::decimal`; this module only assembles the namespace. +//! The three template contexts are session state, so every `import decimal` +//! exposes the same `DefaultContext` object (see `py_context.rs`). + +use crate::{ + args::ArgValues, + builtins::Builtins, + bytecode::VM, + exception_private::{ExcType, RunResult}, + heap::{HeapData, HeapId}, + intern::StaticStrings, + modules::ModuleFunctions, + types::{ + Module, NamedTupleClass, Type, allocate_string, + decimal::{ + context::{MAX_EMAX, MAX_PREC, MIN_EMIN, MIN_ETINY, Rounding}, + py_context::{self, IEEE_CONTEXT_MAX_BITS, Template}, + }, + }, + value::{EitherStr, Value}, +}; + +/// The functions of the `decimal` module. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +pub(crate) enum DecimalFunctions { + #[strum(serialize = "getcontext")] + Getcontext, + #[strum(serialize = "setcontext")] + Setcontext, + #[strum(serialize = "localcontext")] + Localcontext, + #[strum(serialize = "IEEEContext")] + IeeeContext, +} + +/// The signal and condition classes, as `(attribute, exception type)`. +const EXCEPTIONS: [(StaticStrings, ExcType); 14] = [ + (StaticStrings::DecimalException, ExcType::DecimalException), + (StaticStrings::Clamped, ExcType::DecimalClamped), + (StaticStrings::InvalidOperation, ExcType::DecimalInvalidOperation), + (StaticStrings::ConversionSyntax, ExcType::DecimalConversionSyntax), + (StaticStrings::DivisionByZero, ExcType::DecimalDivisionByZero), + (StaticStrings::DivisionImpossible, ExcType::DecimalDivisionImpossible), + (StaticStrings::DivisionUndefined, ExcType::DecimalDivisionUndefined), + (StaticStrings::Inexact, ExcType::DecimalInexact), + (StaticStrings::InvalidContext, ExcType::DecimalInvalidContext), + (StaticStrings::Rounded, ExcType::DecimalRounded), + (StaticStrings::Subnormal, ExcType::DecimalSubnormal), + (StaticStrings::Overflow, ExcType::DecimalOverflow), + (StaticStrings::Underflow, ExcType::DecimalUnderflow), + (StaticStrings::FloatOperation, ExcType::DecimalFloatOperation), +]; + +/// The rounding-mode constants, in [`Rounding::ALL`] order. +const ROUNDING_NAMES: [StaticStrings; 8] = [ + StaticStrings::RoundCeiling, + StaticStrings::RoundFloor, + StaticStrings::RoundUp, + StaticStrings::RoundDown, + StaticStrings::RoundHalfUp, + StaticStrings::RoundHalfDown, + StaticStrings::RoundHalfEven, + StaticStrings::Round05up, +]; + +/// Creates the `decimal` module. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::DecimalMod, vm.interns); + module.set_attr( + StaticStrings::DecimalType, + Value::Builtin(Builtins::Type(Type::Decimal)), + vm, + ); + module.set_attr( + StaticStrings::ContextType, + Value::Builtin(Builtins::Type(Type::DecimalContext)), + vm, + ); + for (name, function) in [ + (StaticStrings::Getcontext, DecimalFunctions::Getcontext), + (StaticStrings::Setcontext, DecimalFunctions::Setcontext), + (StaticStrings::Localcontext, DecimalFunctions::Localcontext), + (StaticStrings::IeeeContext, DecimalFunctions::IeeeContext), + ] { + module.set_attr(name, Value::ModuleFunction(ModuleFunctions::Decimal(function)), vm); + } + for (name, exc_type) in EXCEPTIONS { + module.set_attr(name, Value::Builtin(Builtins::ExcType(exc_type)), vm); + } + for (name, rounding) in ROUNDING_NAMES.into_iter().zip(Rounding::ALL) { + module.set_attr(name, allocate_string(rounding.name(), vm.heap), vm); + } + for (name, template) in [ + (StaticStrings::DefaultContext, Template::Default), + (StaticStrings::BasicContext, Template::Basic), + (StaticStrings::ExtendedContext, Template::Extended), + ] { + let id = py_context::template_id(vm, template); + vm.heap.inc_ref(id); + module.set_attr(name, Value::Ref(id), vm); + } + for (name, value) in [ + (StaticStrings::MaxPrec, MAX_PREC), + (StaticStrings::MaxEmax, MAX_EMAX), + (StaticStrings::MinEmin, MIN_EMIN), + (StaticStrings::MinEtiny, MIN_ETINY), + (StaticStrings::IeeeContextMaxBits, IEEE_CONTEXT_MAX_BITS), + ] { + module.set_attr(name, Value::Int(value), vm); + } + module.set_attr(StaticStrings::HaveThreads, Value::Bool(true), vm); + module.set_attr(StaticStrings::HaveContextvar, Value::Bool(true), vm); + module.set_attr(StaticStrings::DunderVersion, allocate_string("1.70", vm.heap), vm); + module.set_attr( + StaticStrings::DunderLibmpdecVersion, + allocate_string("4.0.1", vm.heap), + vm, + ); + let decimal_tuple = decimal_tuple_class(vm); + module.set_attr(StaticStrings::DecimalTuple, decimal_tuple, vm); + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// `decimal.DecimalTuple`, the named tuple class `Decimal.as_tuple()` builds. +fn decimal_tuple_class(vm: &mut VM<'_>) -> Value { + let field = |name| EitherStr::Interned(vm.interns.intern_static(name)); + let fields = vec![ + field(StaticStrings::Sign), + field(StaticStrings::Digits), + field(StaticStrings::Exponent), + ]; + let name = field(StaticStrings::DecimalTuple); + let module = Value::InternString(vm.interns.intern_static(StaticStrings::DecimalMod)); + let class = NamedTupleClass::new(name, fields, Vec::new(), module); + Value::Ref(vm.heap.allocate(HeapData::NamedTupleClass(Box::new(class)))) +} + +/// Dispatches a `decimal` module function. +pub(super) fn call(vm: &mut VM<'_>, function: DecimalFunctions, args: ArgValues) -> RunResult { + match function { + DecimalFunctions::Getcontext => py_context::getcontext(vm, args), + DecimalFunctions::Setcontext => py_context::setcontext(vm, args), + DecimalFunctions::Localcontext => py_context::localcontext(vm, args), + DecimalFunctions::IeeeContext => py_context::ieee_context(vm, args), + } +} diff --git a/crates/bashkit-monty/src/modules/functools.rs b/crates/bashkit-monty/src/modules/functools.rs new file mode 100644 index 000000000..b6f5bdafe --- /dev/null +++ b/crates/bashkit-monty/src/modules/functools.rs @@ -0,0 +1,178 @@ +//! Implementation of Python's `functools` module. +//! +//! A subset so far: `reduce`, `partial`, `lru_cache`, and `cache`. See +//! `limitations/functools.md` for what diverges from CPython. Unimplemented +//! names are absent from the namespace rather than stubbed, so they raise +//! `AttributeError` up front. + +use crate::{ + args::{ArgValues, FromArgs}, + builtins::{Builtins, BuiltinsFunctions}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, RunResult}, + frozen::FrozenFunction, + heap::{HeapData, HeapId}, + intern::StaticStrings, + modules::ModuleFunctions, + types::{Module, PyTrait, Type, lru_cache}, + value::Value, +}; + +/// Acquires and folds an iterable, allowing both its protocol and the reducer to suspend. +pub(crate) const REDUCE_SOURCE: &str = r" +def __monty_functools_reduce(function, iterable, accumulator, has_initial, iter_, next_, stop_iteration, type_error): + try: + iterator = iter_(iterable) + except type_error: + raise type_error('reduce() arg 2 must support iteration') from None + if not has_initial: + try: + accumulator = next_(iterator) + except stop_iteration: + raise type_error('reduce() of empty iterable with no initial value') from None + while True: + try: + item = next_(iterator) + except stop_iteration: + return accumulator + accumulator = function(accumulator, item) +"; + +/// `functools` module functions, each a Python-visible callable. +/// +/// `partial` is absent because it is exposed as a type object rather than a +/// function, so `type(p) is functools.partial` holds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum FunctoolsFunctions { + Reduce, + Cache, + LruCache, +} + +/// Creates the `functools` module on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Functools, vm.interns); + + module.set_attr( + StaticStrings::Reduce, + Value::ModuleFunction(ModuleFunctions::Functools(FunctoolsFunctions::Reduce)), + vm, + ); + module.set_attr( + StaticStrings::Partial, + Value::Builtin(Builtins::Type(Type::Partial)), + vm, + ); + + module.set_attr( + StaticStrings::Cache, + Value::ModuleFunction(ModuleFunctions::Functools(FunctoolsFunctions::Cache)), + vm, + ); + module.set_attr( + StaticStrings::LruCache, + Value::ModuleFunction(ModuleFunctions::Functools(FunctoolsFunctions::LruCache)), + vm, + ); + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a call to a `functools` module function. +pub(super) fn call(vm: &mut VM<'_>, function: FunctoolsFunctions, args: ArgValues) -> RunResult { + match function { + FunctoolsFunctions::Reduce => call_reduce(vm, args), + FunctoolsFunctions::Cache => call_cache(vm, args).map(CallResult::Value), + FunctoolsFunctions::LruCache => call_lru_cache_factory(vm, args).map(CallResult::Value), + } +} + +/// Argument shape for `reduce(function, iterable, /[, initial])`. +/// +/// CPython's Argument Clinic signature makes the first two positional-only +/// while `initial` is also accepted by keyword, and counts positionals plus +/// keywords together for the maximum (`at_most_total`): `reduce(f, x, 0, +/// initial=1)` reports four arguments. +#[derive(FromArgs)] +#[from_args(name = "reduce", at_most_total)] +struct ReduceArgs { + #[from_args(pos_only)] + function: Value, + #[from_args(pos_only)] + iterable: Value, + #[from_args(default)] + initial: Option, +} + +/// `functools.reduce(function, iterable, /[, initial])` — fold `function` over +/// `iterable` from the left. +/// +/// Native setup binds the arguments; a frozen Python frame owns acquisition, +/// initial accumulator selection, and the callback loop. +fn call_reduce(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReduceArgs { + function, + iterable, + initial, + } = ReduceArgs::from_args(args, vm)?; + + let has_initial = initial.is_some(); + vm.call_frozen_exact( + FrozenFunction::FunctoolsReduce, + [ + function, + iterable, + initial.unwrap_or(Value::None), + Value::Bool(has_initial), + Value::Builtin(Builtins::Type(Type::Iterator)), + Value::Builtin(Builtins::Function(BuiltinsFunctions::Next)), + Value::Builtin(Builtins::ExcType(ExcType::StopIteration)), + Value::Builtin(Builtins::ExcType(ExcType::TypeError)), + ], + ) +} + +/// Arguments to the unbounded caching decorator. +#[derive(FromArgs)] +#[from_args(name = "cache", style = def)] +struct CacheArgs { + #[from_args(pos_only, static_string = "UserFunction")] + user_function: Value, +} + +/// Wraps a callable in an unbounded cache. +fn call_cache(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let CacheArgs { user_function } = CacheArgs::from_args(args, vm)?; + lru_cache::allocate(Some(user_function), None, false, vm) +} + +/// Arguments to the configurable caching decorator; the first may itself be callable. +#[derive(FromArgs)] +#[from_args(name = "lru_cache", style = def)] +struct LruCacheArgs { + #[from_args(default = Value::Int(128))] + maxsize: Value, + #[from_args(default = Value::Bool(false))] + typed: Value, +} + +/// Returns a configured decorator, or wraps a callable passed as the first argument. +fn call_lru_cache_factory(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let LruCacheArgs { maxsize, typed } = LruCacheArgs::from_args(args, vm)?; + defer_drop!(maxsize, vm); + defer_drop!(typed, vm); + let typed_flag = typed.py_bool(vm)?; + match maxsize { + Value::Int(size) => { + let size = u64::try_from(*size).unwrap_or(0); + lru_cache::allocate(None, Some(size), typed_flag, vm) + } + Value::Bool(flag) => lru_cache::allocate(None, Some(u64::from(*flag)), typed_flag, vm), + Value::None => lru_cache::allocate(None, None, typed_flag, vm), + _ if maxsize.is_callable(vm) => { + lru_cache::allocate(Some(maxsize.clone_with_heap(vm)), Some(128), typed_flag, vm) + } + _ => Err(lru_cache::bad_maxsize_error()), + } +} diff --git a/crates/bashkit-monty/src/modules/gc.rs b/crates/bashkit-monty/src/modules/gc.rs new file mode 100644 index 000000000..f235cfc52 --- /dev/null +++ b/crates/bashkit-monty/src/modules/gc.rs @@ -0,0 +1,104 @@ +//! Implementation of Python's `gc` module — only available under the `test-hooks` feature. +//! +//! This module exists purely so integration tests and benches can drive Monty's +//! garbage collector deterministically from Python source. It is **not** part of +//! the public sandbox surface: enabling it from production builds would let +//! untrusted code force GC cycles or suppress them entirely, which is not a +//! behavior we want exposed. +//! +//! The functions provided are: +//! - `gc.collect()` — forces a full GC cycle using the production root walk +//! (the same one the VM runs implicitly when `should_gc()` fires). Returns the +//! number of unreachable heap entries that were freed during the sweep. +//! - `gc.disable()` / `gc.enable()` — toggle automatic collection. +//! Explicit `gc.collect()` calls still run while disabled. + +use crate::{ + args::ArgValues, + bytecode::VM, + exception_private::RunResult, + heap::{HeapData, HeapId}, + intern::StaticStrings, + modules::ModuleFunctions, + types::Module, + value::Value, +}; + +/// Functions exposed by the `gc` module. +/// +/// Just enough surface for tests and benches to script deterministic GC cycles +/// from Python — no observation/tuning APIs (`gc.get_objects`, `gc.set_threshold`, +/// ...) since those would let test code peer at heap internals in ways that +/// aren't stable across Monty versions. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "lowercase")] +pub(crate) enum GcFunctions { + /// `gc.collect()` — forces a full garbage collection cycle. + Collect, + /// `gc.disable()` — suppresses automatic GC until `gc.enable()` is called. + Disable, + /// `gc.enable()` — resumes automatic GC after a prior `gc.disable()`. + Enable, +} + +/// Creates the `gc` module and allocates it on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Gc, vm.interns); + for (name, function) in [ + (StaticStrings::Collect, GcFunctions::Collect), + (StaticStrings::Disable, GcFunctions::Disable), + (StaticStrings::Enable, GcFunctions::Enable), + ] { + module.set_attr(name, Value::ModuleFunction(ModuleFunctions::Gc(function)), vm); + } + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a `gc` module function call. +/// +/// Returns `Value` directly because none of the exposed functions need host +/// involvement — they all run synchronously inside the VM. +pub(super) fn call(vm: &mut VM<'_>, function: GcFunctions, args: ArgValues) -> RunResult { + match function { + GcFunctions::Collect => collect(vm, args), + GcFunctions::Disable => disable(vm, args), + GcFunctions::Enable => enable(vm, args), + } +} + +/// `gc.collect()` — forces a full GC cycle and returns the number of unreachable +/// heap entries freed during the sweep. +/// +/// CPython returns the count of *unreachable objects* found, which is the same +/// number Monty's mark-sweep frees in one pass — every unreachable entry is +/// reclaimed (Monty has no equivalent of CPython's `gc.garbage` for objects with +/// finalizers, so nothing survives the sweep). +/// +/// Counts are clamped to `i64::MAX` if they ever exceed it; in practice a single +/// heap can't hold that many entries, but the conversion is fallible so we +/// saturate rather than panic. +fn collect(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + args.check_zero_args("gc.collect", vm.heap)?; + let freed = vm.__force_gc_for_tests(); + Ok(Value::Int(i64::try_from(freed).unwrap_or(i64::MAX))) +} + +/// `gc.disable()` — suppresses automatic GC until [`enable`] is called. +/// +/// Returns `None` to match CPython. Explicit [`collect`] calls still run while +/// auto-GC is disabled, so a script can build a known amount of garbage and then +/// time exactly one collection pass. +fn disable(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + args.check_zero_args("gc.disable", vm.heap)?; + vm.heap.disable_gc(); + Ok(Value::None) +} + +/// `gc.enable()` — re-enables automatic GC after a prior [`disable`]. +/// +/// Returns `None` to match CPython. Calling on an already-enabled heap is a no-op. +fn enable(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + args.check_zero_args("gc.enable", vm.heap)?; + vm.heap.enable_gc(); + Ok(Value::None) +} diff --git a/crates/bashkit-monty/src/modules/hashlib.rs b/crates/bashkit-monty/src/modules/hashlib.rs new file mode 100644 index 000000000..bc3df891b --- /dev/null +++ b/crates/bashkit-monty/src/modules/hashlib.rs @@ -0,0 +1,787 @@ +//! Implementation of Python's `hashlib` module. +//! +//! The constructors, `new()`, `pbkdf2_hmac()` and the two `algorithms_*` sets +//! are implemented; `file_digest()` and `scrypt()` are not — see +//! `limitations/hashlib.md`. The hash objects themselves live in +//! `types::hashlib`, along with every algorithm, so nothing here depends on +//! OpenSSL: `algorithms_available` is exactly `algorithms_guaranteed`. +//! +//! CPython's constructors are C functions in `_hashlib` (OpenSSL-backed, +//! parsed by Argument Clinic) and `_blake2`, so their signatures use the +//! named C parser style and the bodies reproduce the order in which CPython +//! rejects bad values. + +use std::fmt::Display; + +use monty_types::ResourceTracker; +use num_bigint::Sign; +use num_traits::ToPrimitive; + +use crate::{ + args::{ArgValues, FromArgs, KwargsValues, LaxBool, StrArg, long_int}, + builtins::Builtins, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{ContainsHeap, DropWithContext, HeapData, HeapId}, + intern::StaticStrings, + modules::ModuleFunctions, + types::{ + Module, Set, Type, allocate_string, + bytes::allocate_bytes, + hashlib::{Blake2Params, Blake2b, Blake2s, DigestBytes, HashAlgorithm, HashObject, hash_input}, + }, + value::Value, +}; + +/// `hashlib` module functions, one variant per Python-visible function. +/// +/// `blake2b` and `blake2s` are types rather than functions, as in CPython, so +/// they are not here. Serialized into dumps by variant name, so renaming one +/// needs `#[serde(alias)]`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum HashlibFunctions { + Md5, + Sha1, + Sha224, + Sha256, + Sha384, + Sha512, + Sha3_224, + Sha3_256, + Sha3_384, + Sha3_512, + #[strum(serialize = "shake_128")] + Shake128, + #[strum(serialize = "shake_256")] + Shake256, + New, + Pbkdf2Hmac, +} + +/// Static mapping of attribute names to functions for module creation. +const HASHLIB_FUNCTIONS: &[(StaticStrings, HashlibFunctions)] = &[ + (StaticStrings::Md5, HashlibFunctions::Md5), + (StaticStrings::Sha1, HashlibFunctions::Sha1), + (StaticStrings::Sha224, HashlibFunctions::Sha224), + (StaticStrings::Sha256, HashlibFunctions::Sha256), + (StaticStrings::Sha384, HashlibFunctions::Sha384), + (StaticStrings::Sha512, HashlibFunctions::Sha512), + (StaticStrings::Sha3_224, HashlibFunctions::Sha3_224), + (StaticStrings::Sha3_256, HashlibFunctions::Sha3_256), + (StaticStrings::Sha3_384, HashlibFunctions::Sha3_384), + (StaticStrings::Sha3_512, HashlibFunctions::Sha3_512), + (StaticStrings::Shake128, HashlibFunctions::Shake128), + (StaticStrings::Shake256, HashlibFunctions::Shake256), + (StaticStrings::New, HashlibFunctions::New), + (StaticStrings::Pbkdf2Hmac, HashlibFunctions::Pbkdf2Hmac), +]; + +/// Creates the `hashlib` module on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Hashlib, vm.interns); + for (name, func) in HASHLIB_FUNCTIONS { + module.set_attr(*name, Value::ModuleFunction(ModuleFunctions::Hashlib(*func)), vm); + } + module.set_attr( + StaticStrings::Blake2b, + Value::Builtin(Builtins::Type(Type::Blake2b)), + vm, + ); + module.set_attr( + StaticStrings::Blake2s, + Value::Builtin(Builtins::Type(Type::Blake2s)), + vm, + ); + // Two sets, as in CPython, where mutating one leaves the other alone. + for name in [StaticStrings::AlgorithmsGuaranteed, StaticStrings::AlgorithmsAvailable] { + module.set_attr(name, algorithm_names(vm), vm); + } + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// A fresh `set` of every algorithm name. +fn algorithm_names(vm: &mut VM<'_>) -> Value { + let mut names = Set::with_capacity(HashAlgorithm::ALL.len()); + for algorithm in HashAlgorithm::ALL { + let name = allocate_string(algorithm.name(), vm.heap); + // Adding a str to a set of strs hashes and compares without Python + // code, so the only failure is a memory limit already past its hard ceiling. + names + .add(name, vm) + .expect("adding an interned name to a fresh set cannot raise"); + } + Value::Ref(vm.heap.allocate(HeapData::Set(names))) +} + +/// Dispatches a call to a `hashlib` module function. +pub(super) fn call(vm: &mut VM<'_>, function: HashlibFunctions, args: ArgValues) -> RunResult { + match function { + HashlibFunctions::Md5 => construct(HashAlgorithm::Md5, Md5Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::Sha1 => construct(HashAlgorithm::Sha1, Sha1Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::Sha224 => construct(HashAlgorithm::Sha224, Sha224Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::Sha256 => construct(HashAlgorithm::Sha256, Sha256Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::Sha384 => construct(HashAlgorithm::Sha384, Sha384Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::Sha512 => construct(HashAlgorithm::Sha512, Sha512Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::Sha3_224 => construct(HashAlgorithm::Sha3_224, Sha3_224Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::Sha3_256 => construct(HashAlgorithm::Sha3_256, Sha3_256Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::Sha3_384 => construct(HashAlgorithm::Sha3_384, Sha3_384Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::Sha3_512 => construct(HashAlgorithm::Sha3_512, Sha3_512Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::Shake128 => construct(HashAlgorithm::Shake128, Shake128Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::Shake256 => construct(HashAlgorithm::Shake256, Shake256Args::from_args(args, vm)?.into(), vm), + HashlibFunctions::New => call_new(vm, args), + HashlibFunctions::Pbkdf2Hmac => call_pbkdf2_hmac(vm, args), + } +} + +// ============================================================================ +// The OpenSSL-backed constructors and `new()` +// ============================================================================ + +/// `data=b'', *, usedforsecurity=True, string=None`, the signature every +/// OpenSSL-backed constructor shares once its name is in the error messages. +/// +/// `usedforsecurity` is accepted and ignored: there is no FIPS mode to honour. +struct ConstructorArgs { + data: Option, + usedforsecurity: Value, + string: Option, +} + +impl DropWithContext for ConstructorArgs { + fn drop_with(self, ctx: &mut C) { + self.data.drop_with(ctx); + self.usedforsecurity.drop_with(ctx); + self.string.drop_with(ctx); + } +} + +/// Stamps out one `FromArgs` struct per constructor, since the derive bakes +/// the function name (`openssl_sha256() takes at most …`) into the spec. +macro_rules! openssl_constructor_args { + ($($args:ident => $name:literal),* $(,)?) => {$( + #[derive(FromArgs)] + #[from_args(name = $name, style = c_named, at_most_total)] + struct $args { + #[from_args(default)] + data: Option, + #[from_args(kw_only, default = Value::Bool(true))] + usedforsecurity: Value, + #[from_args(kw_only, default, static_string = "StringAttr")] + string: Option, + } + + impl From<$args> for ConstructorArgs { + fn from(args: $args) -> Self { + let $args { + data, + usedforsecurity, + string, + } = args; + Self { + data, + usedforsecurity, + string, + } + } + } + )*}; +} + +openssl_constructor_args!( + Md5Args => "openssl_md5", + Sha1Args => "openssl_sha1", + Sha224Args => "openssl_sha224", + Sha256Args => "openssl_sha256", + Sha384Args => "openssl_sha384", + Sha512Args => "openssl_sha512", + Sha3_224Args => "openssl_sha3_224", + Sha3_256Args => "openssl_sha3_256", + Sha3_384Args => "openssl_sha3_384", + Sha3_512Args => "openssl_sha3_512", + Shake128Args => "openssl_shake_128", + Shake256Args => "openssl_shake_256", +); + +/// Builds a hash of `algorithm` over the constructor's initial data. +fn construct(algorithm: HashAlgorithm, args: ConstructorArgs, vm: &mut VM<'_>) -> RunResult { + defer_drop!(args, vm); + let mut hash = HashObject::new(algorithm); + if let Some(input) = initial_data(args.data.as_ref(), args.string.as_ref())? { + hash.update(hash_input(input, vm)?, &vm.heap.tracker)?; + } + Ok(hash.allocate(vm.heap)) +} + +/// Picks the initial data between the `data` positional and the deprecated +/// `string` keyword, rejecting both at once as CPython does. +/// +/// Passing either explicitly counts, even as `None`, which then fails the +/// buffer check. +fn initial_data<'a>(data: Option<&'a Value>, string: Option<&'a Value>) -> RunResult> { + match (data, string) { + (Some(_), Some(_)) => Err(ExcType::type_error( + "'data' and 'string' are mutually exclusive and support for 'string' keyword parameter is slated for \ + removal in a future version.", + )), + (Some(data), None) => Ok(Some(data)), + (None, string) => Ok(string), + } +} + +/// `hashlib.new(name, *args, **kwargs)`, a pure-Python `def` that routes +/// BLAKE2 names to the `_blake2` types and everything else to `_hashlib.new`. +#[derive(FromArgs)] +#[from_args(name = "__hash_new", style = def)] +struct HashNewArgs { + name: Value, + #[from_args(varargs)] + args: Vec, + #[from_args(varkwargs)] + kwargs: KwargsValues, +} + +/// `_hashlib.new(name, data=b'', *, usedforsecurity=True, string=None)`. +#[derive(FromArgs)] +#[from_args(name = "new", style = c_named, bad_arg_named, at_most_total)] +struct OpensslNewArgs { + name: StrArg, + #[from_args(default)] + data: Option, + #[from_args(kw_only, default = Value::Bool(true))] + usedforsecurity: Value, + #[from_args(kw_only, default, static_string = "StringAttr")] + string: Option, +} + +/// `hashlib.new()`: the name is checked for a BLAKE2 constructor first, so +/// `new('blake2b', digest_size=16)` reaches `blake2b()`'s own parser; an +/// OpenSSL alias such as `'blake2b512'` takes the plain path, as in CPython. +fn call_new(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let HashNewArgs { name, args, kwargs } = HashNewArgs::from_args(args, vm)?; + let blake2 = name.to_str(vm).ok().and_then(Blake2Kind::from_name); + if let Some(kind) = blake2 { + name.drop_with(vm); + return blake2_init(kind, vm, ArgValues::from_parts(args, kwargs)); + } + // The name rejoins the binder's own vector; `insert` may still grow it, + // but nothing is copied into a fresh buffer before the parser's checks. + let mut positional = args; + positional.insert(0, name); + let OpensslNewArgs { + name, + data, + usedforsecurity, + string, + } = OpensslNewArgs::from_args(ArgValues::from_parts(positional, kwargs), vm)?; + defer_drop!(name, vm); + defer_drop!(data, vm); + defer_drop!(usedforsecurity, vm); + defer_drop!(string, vm); + // The data is checked before the name is resolved, as `_hashlib.new` does. + let input = initial_data(data.as_ref(), string.as_ref())? + .map(|input| hash_input(input, vm)) + .transpose()?; + let name = name.as_str(vm); + let algorithm = HashAlgorithm::from_name(name).ok_or_else(|| unsupported_hash_type(name))?; + let mut hash = HashObject::new(algorithm); + if let Some(input) = input { + hash.update(input, &vm.heap.tracker)?; + } + Ok(hash.allocate(vm.heap)) +} + +/// `ValueError: unsupported hash type `, from `hashlib.new()`. +fn unsupported_hash_type(name: &str) -> RunError { + ExcType::value_error(format!("unsupported hash type {name}")) +} + +// ============================================================================ +// BLAKE2 +// ============================================================================ + +/// Which of the two `_blake2` types a constructor call is for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Blake2Kind { + Blake2b, + Blake2s, +} + +impl Blake2Kind { + /// The kind `hashlib.new(name)` hands to `_blake2`; exact and lowercase, + /// unlike the OpenSSL names. + fn from_name(name: &str) -> Option { + match name { + "blake2b" => Some(Self::Blake2b), + "blake2s" => Some(Self::Blake2s), + _ => None, + } + } + + /// The capitalized name the `digest_size` message uses. + fn display_name(self) -> &'static str { + match self { + Self::Blake2b => "Blake2b", + Self::Blake2s => "Blake2s", + } + } + + fn max_digest_size(self) -> u8 { + match self { + Self::Blake2b => Blake2b::MAX_DIGEST_SIZE, + Self::Blake2s => Blake2s::MAX_DIGEST_SIZE, + } + } + + fn salt_size(self) -> usize { + match self { + Self::Blake2b => Blake2b::SALT_SIZE, + Self::Blake2s => Blake2s::SALT_SIZE, + } + } + + fn max_node_offset(self) -> u64 { + match self { + Self::Blake2b => Blake2b::MAX_NODE_OFFSET, + Self::Blake2s => Blake2s::MAX_NODE_OFFSET, + } + } +} + +/// The constructor arguments before conversion. Every parameter stays a raw +/// `Value` so the body can convert them in signature order, reproducing +/// which error CPython's parser reports first. +struct Blake2RawArgs { + data: Option, + digest_size: Option, + key: Option, + salt: Option, + person: Option, + fanout: Option, + depth: Option, + leaf_size: Option, + node_offset: Option, + node_depth: Option, + inner_size: Option, + last_node: bool, + usedforsecurity: Value, + string: Option, +} + +impl DropWithContext for Blake2RawArgs { + fn drop_with(self, ctx: &mut C) { + self.usedforsecurity.drop_with(ctx); + for value in [ + self.data, + self.digest_size, + self.key, + self.salt, + self.person, + self.fanout, + self.depth, + self.leaf_size, + self.node_offset, + self.node_depth, + self.inner_size, + self.string, + ] { + value.drop_with(ctx); + } + } +} + +/// Stamps out the two `_blake2` constructor signatures, which differ only in +/// the name their errors carry. +macro_rules! blake2_constructor_args { + ($($args:ident => $name:literal),* $(,)?) => {$( + #[derive(FromArgs)] + #[from_args(name = $name, style = c_named, at_most_total)] + struct $args { + #[from_args(default)] + data: Option, + #[from_args(kw_only, default)] + digest_size: Option, + #[from_args(kw_only, default)] + key: Option, + #[from_args(kw_only, default)] + salt: Option, + #[from_args(kw_only, default)] + person: Option, + #[from_args(kw_only, default)] + fanout: Option, + #[from_args(kw_only, default)] + depth: Option, + #[from_args(kw_only, default)] + leaf_size: Option, + #[from_args(kw_only, default)] + node_offset: Option, + #[from_args(kw_only, default)] + node_depth: Option, + #[from_args(kw_only, default)] + inner_size: Option, + #[from_args(kw_only, default = LaxBool::new(false))] + last_node: LaxBool, + #[from_args(kw_only, default = Value::Bool(true))] + usedforsecurity: Value, + #[from_args(kw_only, default, static_string = "StringAttr")] + string: Option, + } + + impl From<$args> for Blake2RawArgs { + fn from(args: $args) -> Self { + let $args { + data, + digest_size, + key, + salt, + person, + fanout, + depth, + leaf_size, + node_offset, + node_depth, + inner_size, + last_node, + usedforsecurity, + string, + } = args; + Self { + data, + digest_size, + key, + salt, + person, + fanout, + depth, + leaf_size, + node_offset, + node_depth, + inner_size, + last_node: last_node.bool(), + usedforsecurity, + string, + } + } + } + )*}; +} + +blake2_constructor_args!(Blake2bArgs => "blake2b", Blake2sArgs => "blake2s"); + +/// `blake2b(...)` / `blake2s(...)`, also reached through `hashlib.new()`. +/// +/// Conversions run in signature order, then the parameter checks in the +/// order `_blake2` makes them, and the data last. +pub(crate) fn blake2_init(kind: Blake2Kind, vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let args: Blake2RawArgs = match kind { + Blake2Kind::Blake2b => Blake2bArgs::from_args(args, vm)?.into(), + Blake2Kind::Blake2s => Blake2sArgs::from_args(args, vm)?.into(), + }; + defer_drop!(args, vm); + let max_digest = kind.max_digest_size(); + let digest_size = args + .digest_size + .as_ref() + .map_or(Ok(i32::from(max_digest)), |v| c_int(v, vm))?; + let key = args.key.as_ref().map_or(Ok(&[][..]), |v| buffer(v, vm))?; + let salt = args.salt.as_ref().map_or(Ok(&[][..]), |v| buffer(v, vm))?; + let person = args.person.as_ref().map_or(Ok(&[][..]), |v| buffer(v, vm))?; + let fanout = args.fanout.as_ref().map_or(Ok(1), |v| c_int(v, vm))?; + let depth = args.depth.as_ref().map_or(Ok(1), |v| c_int(v, vm))?; + let leaf_size = args + .leaf_size + .as_ref() + .map_or(Ok(0), |v| c_unsigned(v, "unsigned long", vm))?; + let node_offset = args + .node_offset + .as_ref() + .map_or(Ok(0), |v| c_unsigned(v, "unsigned long long", vm))?; + let node_depth = args.node_depth.as_ref().map_or(Ok(0), |v| c_int(v, vm))?; + let inner_size = args.inner_size.as_ref().map_or(Ok(0), |v| c_int(v, vm))?; + let input = initial_data(args.data.as_ref(), args.string.as_ref())?; + + let digest_size = u8::try_from(digest_size) + .ok() + .filter(|size| (1..=max_digest).contains(size)) + .ok_or_else(|| { + ExcType::value_error(format!( + "digest_size for {} must be between 1 and {max_digest} bytes, here it is {digest_size}", + kind.display_name() + )) + })?; + let salt_size = kind.salt_size(); + if salt.len() > salt_size { + return Err(ExcType::value_error(format!( + "maximum salt length is {salt_size} bytes" + ))); + } + if person.len() > salt_size { + return Err(ExcType::value_error(format!( + "maximum person length is {salt_size} bytes" + ))); + } + let fanout = u8::try_from(fanout).map_err(|_| ExcType::value_error("fanout must be between 0 and 255"))?; + let depth = u8::try_from(depth) + .ok() + .filter(|depth| *depth >= 1) + .ok_or_else(|| ExcType::value_error("depth must be between 1 and 255"))?; + let leaf_size = u32::try_from(leaf_size).map_err(|_| overflow_error("leaf_size is too large"))?; + if node_offset > kind.max_node_offset() { + return Err(overflow_error("node_offset is too large")); + } + let node_depth = + u8::try_from(node_depth).map_err(|_| ExcType::value_error("node_depth must be between 0 and 255"))?; + let inner_size = u8::try_from(inner_size) + .ok() + .filter(|size| *size <= max_digest) + .ok_or_else(|| ExcType::value_error(format!("inner_size must be between 0 and is {max_digest}")))?; + if key.len() > usize::from(max_digest) { + return Err(ExcType::value_error(format!( + "maximum key length is {max_digest} bytes" + ))); + } + let input = input.map(|input| hash_input(input, vm)).transpose()?; + + let params = Blake2Params { + digest_size, + key, + salt, + person, + fanout, + depth, + leaf_size, + node_offset, + node_depth, + inner_size, + last_node: args.last_node, + }; + let mut hash = match kind { + Blake2Kind::Blake2b => HashObject::blake2b(params), + Blake2Kind::Blake2s => HashObject::blake2s(params), + }; + if let Some(input) = input { + hash.update(input, &vm.heap.tracker)?; + } + Ok(hash.allocate(vm.heap)) +} + +/// Borrows a `bytes` argument with the `Py_buffer` converter's message, which +/// differs from the data argument's (see [`hash_input`]). +fn buffer<'a>(value: &'a Value, vm: &'a VM<'_>) -> RunResult<&'a [u8]> { + match value { + Value::InternBytes(id) => Ok(vm.interns.get_bytes(*id)), + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Bytes(bytes) => Ok(bytes.as_slice()), + _ => Err(not_bytes_like(value, vm)), + }, + _ => Err(not_bytes_like(value, vm)), + } +} + +/// `TypeError: a bytes-like object is required, not 'X'`. +fn not_bytes_like(value: &Value, vm: &VM<'_>) -> RunError { + ExcType::type_error(format!( + "a bytes-like object is required, not '{}'", + value.py_type_name(vm) + )) +} + +/// Argument Clinic's `int` converter: a C `int`, overflowing with +/// `PyLong_AsInt`'s message. +fn c_int(value: &Value, vm: &VM<'_>) -> RunResult { + match value { + Value::Bool(b) => Ok(i32::from(*b)), + Value::Int(i) => i32::try_from(*i).map_err(|_| overflow_error("Python int too large to convert to C int")), + _ if long_int(value, vm).is_some() => Err(overflow_error("Python int too large to convert to C int")), + _ => Err(ExcType::type_error_not_integer(&value.py_type_name(vm))), + } +} + +/// Argument Clinic's `long` converter: a C `long`, overflowing with +/// `PyLong_AsLong`'s message. +fn c_long(value: &Value, vm: &VM<'_>) -> RunResult { + match value { + Value::Bool(b) => Ok(i64::from(*b)), + Value::Int(i) => Ok(*i), + _ if long_int(value, vm).is_some() => Err(ExcType::overflow_c_long()), + _ => Err(ExcType::type_error_not_integer(&value.py_type_name(vm))), + } +} + +/// Argument Clinic's `unsigned_long` / `unsigned_long_long` converters, +/// which reject a negative int before checking the width named by `c_type`. +fn c_unsigned(value: &Value, c_type: &str, vm: &VM<'_>) -> RunResult { + match value { + Value::Bool(b) => Ok(u64::from(*b)), + Value::Int(i) => u64::try_from(*i).map_err(|_| ExcType::value_error_negative_int()), + _ => match long_int(value, vm) { + Some(big) if big.sign() == Sign::Minus => Err(ExcType::value_error_negative_int()), + Some(big) => big + .to_u64() + .ok_or_else(|| overflow_error(format!("Python int too large for C {c_type}"))), + None => Err(ExcType::type_error_not_integer(&value.py_type_name(vm))), + }, + } +} + +/// An `OverflowError` with a custom message. +fn overflow_error(msg: impl Display) -> RunError { + SimpleException::new_msg(ExcType::OverflowError, msg).into() +} + +// ============================================================================ +// pbkdf2_hmac +// ============================================================================ + +/// `pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None)`, a clinic +/// function whose `password`, `salt` and `iterations` convert in the body so +/// their errors come out in signature order. +#[derive(FromArgs)] +#[from_args(name = "pbkdf2_hmac", style = c_named, bad_arg_named, at_most_total)] +struct Pbkdf2HmacArgs { + hash_name: StrArg, + password: Value, + salt: Value, + iterations: Value, + #[from_args(default = Value::None)] + dklen: Value, +} + +/// `hashlib.pbkdf2_hmac()`: PBKDF2 (RFC 8018) over HMAC of the named +/// algorithm, checked in CPython's order — the algorithm, then `iterations`, +/// then `dklen`. +fn call_pbkdf2_hmac(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let Pbkdf2HmacArgs { + hash_name, + password, + salt, + iterations, + dklen, + } = Pbkdf2HmacArgs::from_args(args, vm)?; + defer_drop!(hash_name, vm); + defer_drop!(password, vm); + defer_drop!(salt, vm); + defer_drop!(iterations, vm); + defer_drop!(dklen, vm); + let password = buffer(password, vm)?; + let salt = buffer(salt, vm)?; + let iterations = c_long(iterations, vm)?; + let name = hash_name.as_str(vm); + let algorithm = HashAlgorithm::from_name(name).ok_or_else(|| unsupported_hash_type(name))?; + if iterations < 1 { + return Err(ExcType::value_error("iteration value must be greater than 0.")); + } + // OpenSSL takes both as C ints. + let iterations = i32::try_from(iterations).map_err(|_| overflow_error("iteration value is too great."))?; + let dklen = if matches!(dklen, Value::None) { + // A SHAKE's digest size is zero, which fails the same check an + // explicit zero does. + algorithm.digest_size() + } else { + let dklen = c_long(dklen, vm)?; + let dklen = i32::try_from(dklen.max(0)).map_err(|_| overflow_error("key length is too great."))?; + usize::try_from(dklen).expect("non-negative") + }; + if dklen == 0 { + return Err(ExcType::value_error("key length must be greater than 0.")); + } + if algorithm.is_xof() { + return Err(ExcType::value_error("[Provider routines] xof digests not allowed")); + } + vm.heap.tracker.check_allocation(dklen)?; + let key = pbkdf2(algorithm, password, salt, iterations, dklen, &vm.heap.tracker)?; + Ok(allocate_bytes(key, vm.heap)) +} + +/// PBKDF2 with HMAC-`algorithm` as the pseudorandom function. +/// +/// `iterations` is caller-chosen, so each HMAC round polls the deadline; the +/// salt is absorbed once rather than re-hashed for every output block. +fn pbkdf2( + algorithm: HashAlgorithm, + password: &[u8], + salt: &[u8], + iterations: i32, + dklen: usize, + tracker: &ResourceTracker, +) -> RunResult> { + let hmac = Hmac::new(algorithm, password, tracker)?; + // Every block's first message is `salt || INT(block_index)`. + let salted = hmac.with_prefix(salt, tracker)?; + let mut key = Vec::with_capacity(dklen); + let mut round = 0usize; + for block_index in 1u32.. { + let mut u = salted.sign(&block_index.to_be_bytes(), tracker)?; + let mut t = u; + for _ in 1..iterations { + tracker.check_time_every(round)?; + round = round.wrapping_add(1); + u = hmac.sign(&u, tracker)?; + for (acc, byte) in t.iter_mut().zip(u.iter()) { + *acc ^= byte; + } + } + key.extend(t.iter().take(dklen - key.len())); + if key.len() == dklen { + break; + } + tracker.check_time_every(round)?; + round = round.wrapping_add(1); + } + Ok(key) +} + +/// HMAC (RFC 2104) keyed once, so each message costs two cloned states and +/// no key preparation; with a stack digest, a SHA-2 round allocates nothing. +struct Hmac { + /// The hash with the inner padded key absorbed. + inner: HashObject, + /// The hash with the outer padded key absorbed. + outer: HashObject, +} + +impl Hmac { + fn new(algorithm: HashAlgorithm, key: &[u8], tracker: &ResourceTracker) -> RunResult { + let block_size = algorithm.block_size(); + let mut padded = vec![0u8; block_size]; + if key.len() > block_size { + let mut hashed = HashObject::new(algorithm); + hashed.update(key, tracker)?; + let digest = hashed.digest(); + padded[..digest.len()].copy_from_slice(&digest); + } else { + padded[..key.len()].copy_from_slice(key); + } + let keyed = |pad: u8| -> RunResult { + let mut hash = HashObject::new(algorithm); + let block: Vec = padded.iter().map(|byte| byte ^ pad).collect(); + hash.update(&block, tracker)?; + Ok(hash) + }; + Ok(Self { + inner: keyed(0x36)?, + outer: keyed(0x5c)?, + }) + } + + /// The same MAC with `prefix` already absorbed, for signing many + /// messages that share it. + fn with_prefix(&self, prefix: &[u8], tracker: &ResourceTracker) -> RunResult { + let mut inner = self.inner.clone(); + inner.update(prefix, tracker)?; + Ok(Self { + inner, + outer: self.outer.clone(), + }) + } + + /// The MAC of `message`. + fn sign(&self, message: &[u8], tracker: &ResourceTracker) -> RunResult { + let mut inner = self.inner.clone(); + inner.update(message, tracker)?; + let mut outer = self.outer.clone(); + outer.update(&inner.digest(), tracker)?; + Ok(outer.digest()) + } +} diff --git a/crates/bashkit-monty/src/modules/itertools.rs b/crates/bashkit-monty/src/modules/itertools.rs new file mode 100644 index 000000000..a26ac14ef --- /dev/null +++ b/crates/bashkit-monty/src/modules/itertools.rs @@ -0,0 +1,958 @@ +//! Implementation of Python's `itertools` module. +//! +//! A subset so far — see `limitations/itertools.md` for what is implemented and +//! what is not. Unimplemented names are absent from the namespace rather than +//! stubbed, so they raise `AttributeError` up front. See +//! [`crate::types::itertools`] for why the family shares one `HeapData` variant. + +use std::mem; + +use crate::{ + args::{ArgValues, FromArgs, LaxBool}, + builtins::Builtins, + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{DropGuard, DropWithContext, HEAP_ENTRY_SIZE, HeapData, HeapId}, + intern::StaticStrings, + modules::ModuleFunctions, + resource_checks::check_estimated_size, + types::{ + ItertoolsIter, Module, TupleVec, Type, allocate_tuple, + iter::collect_owned_iterable, + itertools::{ + Accumulate, Batched, Chain, Combinations, Compress, Count, Cycle, DropWhile, FilterFalse, GroupBy, Islice, + Pairwise, Permutations, Product, Repeat, StarMap, TakeWhile, ZipLongest, tee, + }, + }, + value::{VALUE_SIZE, Value}, +}; + +/// The `itertools` callables that are not type objects. +/// +/// CPython models all but one of this module's names as classes, and so does +/// Monty — `itertools.count` IS `Type::ItertoolsCount`, constructed through +/// [`construct`]. Only `tee` is a plain function there, and `from_iterable` is +/// reached through the `chain` type rather than the module. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum ItertoolsFunctions { + Tee, + /// `chain.from_iterable`, an attribute of the `chain` type rather than a + /// name in the module — resolved by `Value::py_getattr`. + #[strum(serialize = "from_iterable")] + ChainFromIterable, +} + +/// The module's type objects, by the name each is bound to. +const ITERTOOLS_TYPES: &[(StaticStrings, Type)] = &[ + (StaticStrings::Count, Type::ItertoolsCount), + (StaticStrings::Repeat, Type::ItertoolsRepeat), + (StaticStrings::Pairwise, Type::ItertoolsPairwise), + (StaticStrings::Compress, Type::ItertoolsCompress), + (StaticStrings::Islice, Type::ItertoolsIslice), + (StaticStrings::Chain, Type::ItertoolsChain), + (StaticStrings::Cycle, Type::ItertoolsCycle), + (StaticStrings::Takewhile, Type::ItertoolsTakeWhile), + (StaticStrings::Dropwhile, Type::ItertoolsDropWhile), + (StaticStrings::Filterfalse, Type::ItertoolsFilterFalse), + (StaticStrings::Starmap, Type::ItertoolsStarMap), + (StaticStrings::Accumulate, Type::ItertoolsAccumulate), + (StaticStrings::Batched, Type::ItertoolsBatched), + (StaticStrings::ZipLongest, Type::ItertoolsZipLongest), + (StaticStrings::Combinations, Type::ItertoolsCombinations), + ( + StaticStrings::CombinationsWithReplacement, + Type::ItertoolsCombinationsWithReplacement, + ), + (StaticStrings::Permutations, Type::ItertoolsPermutations), + (StaticStrings::Product, Type::ItertoolsProduct), + (StaticStrings::Groupby, Type::ItertoolsGroupBy), + (StaticStrings::Grouper, Type::ItertoolsGrouper), + (StaticStrings::TeeType, Type::ItertoolsTee), + (StaticStrings::TeeDataObject, Type::ItertoolsTeeDataObject), +]; + +/// Creates the `itertools` module on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Itertools, vm.interns); + + for (name, type_) in ITERTOOLS_TYPES { + module.set_attr(*name, Value::Builtin(Builtins::Type(*type_)), vm); + } + module.set_attr( + StaticStrings::Tee, + Value::ModuleFunction(ModuleFunctions::Itertools(ItertoolsFunctions::Tee)), + vm, + ); + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a call to one of the module's two plain functions. +pub(crate) fn call(vm: &mut VM<'_>, function: ItertoolsFunctions, args: ArgValues) -> RunResult { + match function { + ItertoolsFunctions::Tee => call_tee(vm, args), + ItertoolsFunctions::ChainFromIterable => call_chain_from_iterable(vm, args), + } +} + +/// Constructs one of the module's iterators, reached through [`Type::call`]. +/// +/// # Panics +/// Panics on a type this module does not own, which `Type::call` never passes. +pub(crate) fn construct(type_: Type, vm: &mut VM<'_>, args: ArgValues) -> RunResult { + match type_ { + Type::ItertoolsCount => call_count(vm, args), + Type::ItertoolsRepeat => call_repeat(vm, args), + Type::ItertoolsPairwise => call_pairwise(vm, args), + Type::ItertoolsCompress => call_compress(vm, args), + Type::ItertoolsIslice => call_islice(vm, args), + Type::ItertoolsChain => call_chain(vm, args), + Type::ItertoolsCycle => call_cycle(vm, args), + Type::ItertoolsTakeWhile => call_takewhile(vm, args), + Type::ItertoolsDropWhile => call_dropwhile(vm, args), + Type::ItertoolsFilterFalse => call_filterfalse(vm, args), + Type::ItertoolsStarMap => call_starmap(vm, args), + Type::ItertoolsAccumulate => call_accumulate(vm, args), + Type::ItertoolsBatched => call_batched(vm, args), + Type::ItertoolsZipLongest => call_zip_longest(vm, args), + Type::ItertoolsCombinations => call_combinations(vm, args), + Type::ItertoolsCombinationsWithReplacement => call_combinations_with_replacement(vm, args), + Type::ItertoolsPermutations => call_permutations(vm, args), + Type::ItertoolsProduct => call_product(vm, args), + Type::ItertoolsGroupBy => call_groupby(vm, args), + // Exposed under their CPython names so `type()` and `isinstance()` + // work, but not constructible here — CPython builds them from the + // arguments its internals use. See `limitations/itertools.md`. + Type::ItertoolsGrouper | Type::ItertoolsTee | Type::ItertoolsTeeDataObject => { + args.drop_with(vm); + Err(ExcType::type_error_not_callable(&type_.name(vm.heap, vm.interns))) + } + other => unreachable!("{other} is not an itertools type"), + } +} + +/// Argument shape for `count(start=0, step=1)`. +/// +/// CPython parses this with `"|OO:count"`, so errors carry the function name +/// (`style = c_named`) and arity counts positionals + keywords together +/// (`at_most_total`): `count(1, 2, step=3)` reports three arguments. +#[derive(FromArgs)] +#[from_args(name = "count", style = c_named, at_most_total)] +struct CountArgs { + #[from_args(default = Value::Int(0))] + start: Value, + #[from_args(default = Value::Int(1))] + step: Value, +} + +/// `itertools.count(start=0, step=1)` — an infinite arithmetic progression. +fn call_count(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let CountArgs { start, step } = CountArgs::from_args(args, vm)?; + // CPython's `count_new` runs one `PyNumber_Check` over both arguments after + // parsing, so a bad `start` and a bad `step` give the same single message. + // Rejecting here means `py_next` can add without a defined-ness check. + if is_number(&start, vm) && is_number(&step, vm) { + let iter = ItertoolsIter::Count(Count::new(normalize_bool(start), normalize_bool(step))); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) + } else { + start.drop_with(vm); + step.drop_with(vm); + Err(ExcType::type_error("a number is required")) + } +} + +/// Argument shape for `repeat(object, times=?)`. +/// +/// CPython parses this with `"O|n:repeat"` — see [`CountArgs`] for why that +/// means `c_named` + `at_most_total`. `times` stays a raw `Value` so the +/// `__index__` coercion (and its `OverflowError`) happens in the body. +#[derive(FromArgs)] +#[from_args(name = "repeat", style = c_named, at_most_total)] +struct RepeatArgs { + object: Value, + #[from_args(default)] + times: Option, +} + +/// `itertools.repeat(object, times=?)` — `object` forever, or `times` times. +fn call_repeat(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let RepeatArgs { object, times } = RepeatArgs::from_args(args, vm)?; + let remaining = match times { + None => None, + Some(times) => { + let count = repeat_times(×, vm); + times.drop_with(vm); + match count { + Ok(count) => Some(count), + Err(error) => { + object.drop_with(vm); + return Err(error); + } + } + } + }; + let iter = ItertoolsIter::Repeat(Repeat::new(object, remaining)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Whether `value` satisfies CPython's `PyNumber_Check` for `count()`. +/// +/// Monty's numeric types are exactly `int` (immediate, interned big, or heap +/// `LongInt` — all reported as [`Type::Int`]), `float`, `complex` and `bool`. +fn is_number(value: &Value, vm: &VM<'_>) -> bool { + matches!( + value.py_type_heap(vm.heap), + Type::Int | Type::Float | Type::Complex | Type::Bool + ) +} + +/// Widens a `bool` start/step to the `int` it stands for. +/// +/// CPython's `count_new` does the same — `repr(count(True))` is `count(1)`, not +/// `count(True)` — so this is parity rather than a shortcut. It also keeps +/// `py_next` off Monty's unsupported `bool + int` path. +fn normalize_bool(value: Value) -> Value { + match value { + Value::Bool(b) => Value::Int(i64::from(b)), + other => other, + } +} + +/// Coerces `repeat`'s `times` the way CPython's `n` format unit does. +/// +/// Negative counts clamp to zero (`repeat(x, -1)` is empty) and a `times` too +/// large for a machine integer raises `OverflowError`, matching the conversion +/// to `Py_ssize_t`. `bool` is accepted because it is an `int` subclass. +fn repeat_times(value: &Value, vm: &mut VM<'_>) -> RunResult { + let count = match value { + Value::Bool(b) => i64::from(*b), + other => other.as_int(vm)?, + }; + // Saturates rather than wrapping on a 32-bit host, where a `times` between + // `usize::MAX` and `i64::MAX` is still effectively infinite. + Ok(usize::try_from(count.max(0)).unwrap_or(usize::MAX)) +} + +/// Argument shape for `pairwise(iterable)`. +/// +/// CPython parses this with `PyArg_UnpackTuple`, so arity errors read +/// `pairwise expected 1 argument, got 2` and any keyword is rejected wholesale +/// with `pairwise() takes no keyword arguments`. +#[derive(FromArgs)] +#[from_args(name = "pairwise", style = unpack)] +struct PairwiseArgs { + #[from_args(pos_only)] + iterable: Value, +} + +/// `itertools.pairwise(iterable)` — successive overlapping pairs. +fn call_pairwise(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let PairwiseArgs { iterable } = PairwiseArgs::from_args(args, vm)?; + // Resolve to an iterator up front, as CPython does: a non-iterable raises + // here rather than on the first `next()`. + let source = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + let iter = ItertoolsIter::Pairwise(Pairwise::new(source)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Argument shape for `compress(data, selectors)`. +/// +/// CPython parses this with `PyArg_ParseTupleAndKeywords`, so both parameters +/// are also accepted by keyword and arity counts positionals + keywords +/// together: `compress([1], [1], data=[1])` reports three arguments. +#[derive(FromArgs)] +#[from_args(name = "compress", style = c_named, at_most_total)] +struct CompressArgs { + data: Value, + selectors: Value, +} + +/// `itertools.compress(data, selectors)` — data items with a truthy selector. +fn call_compress(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let CompressArgs { data, selectors } = CompressArgs::from_args(args, vm)?; + // `into_py_iter` consumes its receiver, so each conversion guards the other + // argument: whichever is not being converted is released if this one raises. + let mut guard = DropGuard::new(selectors, vm); + let data = data.into_py_iter(guard.ctx())?.require_synchronous(guard.ctx())?; + let (selectors, vm) = guard.into_parts(); + let mut guard = DropGuard::new(data, vm); + let selectors = selectors.into_py_iter(guard.ctx())?.require_synchronous(guard.ctx())?; + let (data, vm) = guard.into_parts(); + let iter = ItertoolsIter::Compress(Compress::new(data, selectors)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Argument shape for `islice(iterable, [start,] stop[, step])`. +/// +/// CPython uses `PyArg_UnpackTuple` with a 2..4 arity, so the trailing three +/// slots are read positionally and their *meaning* depends on how many were +/// given — resolved in the body by [`islice_bounds`], not by the binder. +#[derive(FromArgs)] +#[from_args(name = "islice", style = unpack)] +struct IsliceArgs { + #[from_args(pos_only)] + iterable: Value, + #[from_args(pos_only)] + first: Value, + #[from_args(pos_only, default)] + second: Option, + #[from_args(pos_only, default)] + third: Option, +} + +/// `itertools.islice(iterable, [start,] stop[, step])` — a slice of an iterator. +fn call_islice(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let IsliceArgs { + iterable, + first, + second, + third, + } = IsliceArgs::from_args(args, vm)?; + + // `iterable` is guarded across the bounds check so an invalid slot raises + // only after the three overloaded arguments have been released. + let mut guard = DropGuard::new(iterable, vm); + let vm = guard.ctx(); + let bounds = islice_bounds(&first, second.as_ref(), third.as_ref(), vm); + first.drop_with(vm); + second.drop_with(vm); + third.drop_with(vm); + let (start, stop, step) = bounds?; + let (iterable, vm) = guard.into_parts(); + + let source = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + let iter = ItertoolsIter::Islice(Islice::new(source, start, stop, step)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Resolves `islice`'s overloaded positional slots into `(start, stop, step)`. +/// +/// With two arguments the second is `stop`; with three or more it is `start`. +/// CPython words the two failures differently, so they are not interchangeable. +fn islice_bounds( + first: &Value, + second: Option<&Value>, + third: Option<&Value>, + vm: &mut VM<'_>, +) -> RunResult<(usize, Option, usize)> { + match second { + None => match islice_index(first, vm)? { + IsliceBound::Unbounded => Ok((0, None, 1)), + IsliceBound::Index(stop) => Ok((0, Some(stop), 1)), + IsliceBound::Invalid => Err(ExcType::islice_bad_stop()), + }, + Some(second) => { + // A `start` of `None` means "from the beginning", as in a slice. + let start = match islice_index(first, vm)? { + IsliceBound::Unbounded => 0, + IsliceBound::Index(start) => start, + IsliceBound::Invalid => return Err(ExcType::islice_bad_indices()), + }; + let stop = match islice_index(second, vm)? { + IsliceBound::Unbounded => None, + IsliceBound::Index(stop) => Some(stop), + IsliceBound::Invalid => return Err(ExcType::islice_bad_indices()), + }; + // A step of `None` is 1; zero and negatives are rejected outright. + let step = match third.map(|third| islice_index(third, vm)).transpose()? { + None | Some(IsliceBound::Unbounded) => 1, + Some(IsliceBound::Index(step)) if step > 0 => step, + Some(_) => return Err(ExcType::islice_bad_step()), + }; + Ok((start, stop, step)) + } + } +} + +/// One parsed `islice` bound. +/// +/// Three-way rather than `Option`: `stop` accepts an explicit `None` +/// where `step` does not, so the two rejections must stay distinguishable. +enum IsliceBound { + /// Python `None` — unbounded for `stop`, the default for `start`/`step`. + Unbounded, + /// An index in `0 ..= sys.maxsize`. + Index(usize), + /// Neither, so the caller raises. + Invalid, +} + +/// Reads one `islice` bound; whether `Unbounded` is allowed is the caller's +/// business, and differs per parameter. +fn islice_index(value: &Value, vm: &mut VM<'_>) -> RunResult { + let index = match value { + Value::None => return Ok(IsliceBound::Unbounded), + Value::Bool(b) => i64::from(*b), + // A raising `__index__` propagates; only a type mismatch is `Invalid`, + // which the caller words per parameter. + other => match other.as_int(vm) { + Ok(index) => index, + Err(RunError::Exc(_)) => return Ok(IsliceBound::Invalid), + Err(e) => return Err(e), + }, + }; + Ok(usize::try_from(index).map_or(IsliceBound::Invalid, IsliceBound::Index)) +} + +/// `itertools.chain(*iterables)` — each argument's items, back to back. +/// +/// Uses `into_pos_only` because the derive cannot express unbounded `*args` +/// with no keywords: `style = unpack` models a fixed `min..max` and rejects +/// `varargs`. +fn call_chain(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let iterables: Vec = args.into_pos_only("chain", vm.heap)?.collect(); + // Arguments are NOT resolved here: CPython calls `iter()` on each only as it + // reaches it, so `chain([1], 5)` constructs and raises mid-consumption. + let iter = ItertoolsIter::Chain(Chain::new(iterables)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Argument shape for `cycle(iterable)`. +/// +/// `PyArg_UnpackTuple` like `pairwise`, so arity reads `cycle expected 1 +/// argument, got 2` and keywords are rejected wholesale. +#[derive(FromArgs)] +#[from_args(name = "cycle", style = unpack)] +struct CycleArgs { + #[from_args(pos_only)] + iterable: Value, +} + +/// `itertools.cycle(iterable)` — the source's items, repeating forever. +fn call_cycle(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let CycleArgs { iterable } = CycleArgs::from_args(args, vm)?; + // Unlike `chain`, CPython resolves eagerly here, so `cycle(5)` raises now. + let source = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + let iter = ItertoolsIter::Cycle(Cycle::new(source)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Argument shape shared by `takewhile`, `dropwhile`, `filterfalse` and +/// `starmap`. +/// +/// All four are `PyArg_UnpackTuple(args, name, 2, 2, ...)` in CPython, so both +/// slots are positional-only, arity reads `takewhile expected 2 arguments, got +/// 1`, and keywords are rejected wholesale. The macro embeds the name, hence +/// one struct per callable rather than one shared struct. +macro_rules! callable_and_iterable_args { + ($struct_name:ident, $py_name:literal) => { + #[derive(FromArgs)] + #[from_args(name = $py_name, style = unpack)] + struct $struct_name { + #[from_args(pos_only)] + callable: Value, + #[from_args(pos_only)] + iterable: Value, + } + }; +} + +callable_and_iterable_args!(TakeWhileArgs, "takewhile"); +callable_and_iterable_args!(DropWhileArgs, "dropwhile"); +callable_and_iterable_args!(FilterFalseArgs, "filterfalse"); +callable_and_iterable_args!(StarMapArgs, "starmap"); + +/// `itertools.takewhile(predicate, iterable)` — the leading passing run. +fn call_takewhile(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let TakeWhileArgs { callable, iterable } = TakeWhileArgs::from_args(args, vm)?; + let (predicate, source) = resolve_source(callable, iterable, vm)?; + let iter = ItertoolsIter::TakeWhile(TakeWhile::new(predicate, source)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// `itertools.dropwhile(predicate, iterable)` — everything past that run. +fn call_dropwhile(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let DropWhileArgs { callable, iterable } = DropWhileArgs::from_args(args, vm)?; + let (predicate, source) = resolve_source(callable, iterable, vm)?; + let iter = ItertoolsIter::DropWhile(DropWhile::new(predicate, source)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// `itertools.filterfalse(predicate, iterable)` — the items it rejects. +fn call_filterfalse(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let FilterFalseArgs { callable, iterable } = FilterFalseArgs::from_args(args, vm)?; + let (predicate, source) = resolve_source(callable, iterable, vm)?; + let iter = ItertoolsIter::FilterFalse(FilterFalse::new(predicate, source)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// `itertools.starmap(function, iterable)` — each item spread as arguments. +fn call_starmap(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let StarMapArgs { callable, iterable } = StarMapArgs::from_args(args, vm)?; + let (function, source) = resolve_source(callable, iterable, vm)?; + let iter = ItertoolsIter::StarMap(StarMap::new(function, source)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Argument shape for `accumulate(iterable, func=None, *, initial=None)`. +/// +/// Argument Clinic, so both leading slots accept keywords +/// (`accumulate(iterable=[1])` works). Clinic shares `_PyArg_UnpackKeywords` +/// with the named C family, so `c_named` — not the default style, which is the +/// `_PyArg_CheckPositional` wording — gives the `takes at most 2 positional +/// arguments (3 given)` form, pivoting to a total count once kwargs push the +/// overflow past every slot. `func` is never type-checked here: CPython only +/// discovers a non-callable when the second item arrives. +#[derive(FromArgs)] +#[from_args(name = "accumulate", style = c_named)] +struct AccumulateArgs { + #[from_args(static_string = "IterableArg")] + iterable: Value, + #[from_args(default = Value::None)] + func: Value, + #[from_args(kw_only, default = Value::None)] + initial: Value, +} + +/// `itertools.accumulate(iterable, func=None, *, initial=None)` — running totals. +fn call_accumulate(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let AccumulateArgs { + iterable, + func, + initial, + } = AccumulateArgs::from_args(args, vm)?; + // `func` is held across the resolve so a non-iterable releases it too. + let (func, source) = match resolve_source(func, iterable, vm) { + Ok(resolved) => resolved, + Err(error) => { + initial.drop_with(vm); + return Err(error); + } + }; + // An explicit `initial=None` is no initial at all, as CPython's `!= Py_None` + // check makes it — so `accumulate([], initial=None)` yields nothing. + let initial = match initial { + Value::None => None, + initial => Some(initial), + }; + let iter = ItertoolsIter::Accumulate(Box::new(Accumulate::new(source, func, initial))); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Argument shape for `batched(iterable, n, *, strict=False)`. +/// +/// Argument Clinic, so `n` accepts a keyword and a missing one reports +/// `missing required argument 'n' (pos 2)` — see [`AccumulateArgs`] for why +/// that means `c_named`. Both positionals are required, so the overflow says +/// "exactly" where `accumulate`'s says "at most". `n` stays a raw `Value` because it +/// needs `as_int`'s message rather than the binder's, as `repeat`'s `times` +/// does; `strict` is a [`LaxBool`] so CPython's `bool()`-style truth test +/// happens in the binder, which releases the value on both paths. +#[derive(FromArgs)] +#[from_args(name = "batched", style = c_named)] +struct BatchedArgs { + #[from_args(static_string = "IterableArg")] + iterable: Value, + n: Value, + #[from_args(kw_only, default = LaxBool::new(false))] + strict: LaxBool, +} + +/// `itertools.batched(iterable, n, *, strict=False)` — consecutive n-tuples. +fn call_batched(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let BatchedArgs { iterable, n, strict } = BatchedArgs::from_args(args, vm)?; + let strict = strict.bool(); + // `n` is validated before the iterable is resolved, matching CPython's + // clinic converter, which runs over every argument before the body. + let size = batched_n(&n, vm); + n.drop_with(vm); + let size = match size { + Ok(size) => size, + Err(error) => { + iterable.drop_with(vm); + return Err(error); + } + }; + + let source = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + let iter = ItertoolsIter::Batched(Batched::new(source, size, strict)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Coerces `batched`'s `n` and enforces CPython's "at least one" floor. +fn batched_n(value: &Value, vm: &mut VM<'_>) -> RunResult { + let n = ssize_arg(value, vm)?; + if n < 1 { + Err(ExcType::batched_bad_n()) + } else { + Ok(n.cast_unsigned()) + } +} + +/// Coerces an argument the way CPython's `Py_ssize_t` converters do. +/// +/// Needs `&mut VM` because `as_int` dispatches `__index__`, re-entering the +/// interpreter; the caller's other arguments are owned, so that cannot +/// invalidate them. `as_int` raises `OverflowError` past `i64` as the +/// conversion does, and the bound below reports the same for the range between +/// `isize` and `i64` that only a 32-bit host (`wasm32-wasip1`) has — +/// `batched('AB', 2**40)` there. +fn ssize_arg(value: &Value, vm: &mut VM<'_>) -> RunResult { + let n = match value { + Value::Bool(b) => i64::from(*b), + other => other.as_int(vm)?, + }; + isize::try_from(n).map_err(|_| ExcType::overflow_c_ssize_t()) +} + +/// Argument shape for `zip_longest(*iterables, fillvalue=None)`. +/// +/// The only adaptor with both `*args` and a keyword. CPython hand-rolls the +/// parse rather than using a parser family, and its rejection names no +/// argument (`zip_longest() got an unexpected keyword argument`) — the derive +/// appends the offending name, which `limitations/itertools.md` records. +#[derive(FromArgs)] +#[from_args(name = "zip_longest")] +struct ZipLongestArgs { + #[from_args(varargs)] + iterables: Vec, + #[from_args(kw_only, default = Value::None)] + fillvalue: Value, +} + +/// `itertools.zip_longest(*iterables, fillvalue=None)` — zip to the longest. +fn call_zip_longest(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ZipLongestArgs { iterables, fillvalue } = ZipLongestArgs::from_args(args, vm)?; + // Every argument is resolved up front, unlike `chain`'s lazy ones, so a + // later non-iterable must release the arguments never reached as well. The + // `Value::None` swap leaves those in the guard's vec: draining it instead + // would hand the tail to a Rust `Drop`, which cannot `drop_with`. + defer_drop_mut!(iterables, vm); + let mut guard = DropGuard::new(Vec::with_capacity(iterables.len()), vm); + for slot in iterables.iter_mut() { + let iterable = mem::replace(slot, Value::None); + let (resolved, vm) = guard.as_parts_mut(); + match iterable.into_py_iter(vm).and_then(|call| call.require_synchronous(vm)) { + Ok(source) => resolved.push(source), + Err(error) => { + fillvalue.drop_with(vm); + return Err(error); + } + } + } + let (sources, vm) = guard.into_parts(); + let iter = ItertoolsIter::ZipLongest(ZipLongest::new(sources, fillvalue)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Argument shape for `combinations(iterable, r)` and its +/// `_with_replacement` twin. +/// +/// Argument Clinic with both parameters keyword-capable, so `c_named` (see +/// [`AccumulateArgs`]), and `at_most_total` because a stray keyword reports +/// `takes at most 2 arguments (3 given)`. `r` stays a raw `Value`: its +/// `Py_ssize_t` conversion runs in the body, ahead of the pool being collected +/// and before the sign check, as the clinic converter and body order them. +macro_rules! iterable_and_r_args { + ($struct_name:ident, $py_name:literal) => { + #[derive(FromArgs)] + #[from_args(name = $py_name, style = c_named, at_most_total)] + struct $struct_name { + #[from_args(static_string = "IterableArg")] + iterable: Value, + r: Value, + } + }; +} + +iterable_and_r_args!(CombinationsArgs, "combinations"); +iterable_and_r_args!(CombinationsWithReplacementArgs, "combinations_with_replacement"); + +/// `itertools.combinations(iterable, r)` — `r`-length subsequences. +fn call_combinations(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let CombinationsArgs { iterable, r } = CombinationsArgs::from_args(args, vm)?; + build_combinations(iterable, r, false, vm) +} + +/// `itertools.combinations_with_replacement(iterable, r)` — the same, with +/// each item allowed to repeat. +fn call_combinations_with_replacement(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let CombinationsWithReplacementArgs { iterable, r } = CombinationsWithReplacementArgs::from_args(args, vm)?; + build_combinations(iterable, r, true, vm) +} + +/// Collects the pool and builds either `combinations` flavour. +/// +/// `r` is converted before the pool is collected, but its sign is checked +/// after: `combinations(5, -1)` reports the non-iterable, `combinations(5, 'x')` +/// the bad `r`. +fn build_combinations(iterable: Value, r: Value, replacement: bool, vm: &mut VM<'_>) -> RunResult { + let converted = ssize_arg(&r, vm); + r.drop_with(vm); + let r = match converted { + Ok(r) => r, + Err(error) => { + iterable.drop_with(vm); + return Err(error); + } + }; + let pool: Vec = collect_owned_iterable(iterable, vm)?; + let mut pool_guard = DropGuard::new(pool, vm); + let (pool, vm) = pool_guard.as_parts_mut(); + let r = usize::try_from(r).map_err(|_| ExcType::combinatoric_negative_r())?; + // Without replacement `r` past the pool yields nothing and allocates + // nothing; with it `r` is unbounded, so the index vector and the result + // tuples it sizes are preflighted (`combinations_with_replacement('a', 10**9)`). + // An `r` whose vector no allocation could address is CPython's bare + // `MemoryError` rather than a limit refusal, and stops `Vec` panicking on + // a capacity that overflows. + if replacement && !pool.is_empty() { + let bytes = index_bytes(r).ok_or_else(ExcType::allocation_too_large)?; + check_estimated_size(bytes.saturating_add(r.saturating_mul(VALUE_SIZE)), &vm.heap.tracker)?; + } + let (pool, vm) = pool_guard.into_parts(); + let iter = ItertoolsIter::Combinations(Box::new(Combinations::new(pool, r, replacement))); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Argument shape for `permutations(iterable, r=None)`. +/// +/// Clinic and keyword-capable like [`CombinationsArgs`]. `r` is an `object` +/// to clinic, so the body inspects it — and only once the pool exists. +#[derive(FromArgs)] +#[from_args(name = "permutations", style = c_named, at_most_total)] +struct PermutationsArgs { + #[from_args(static_string = "IterableArg")] + iterable: Value, + #[from_args(default = Value::None)] + r: Value, +} + +/// `itertools.permutations(iterable, r=None)` — `r`-length orderings. +fn call_permutations(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let PermutationsArgs { iterable, r } = PermutationsArgs::from_args(args, vm)?; + let mut r_guard = DropGuard::new(r, vm); + let pool: Vec = collect_owned_iterable(iterable, r_guard.ctx())?; + let (r, vm) = r_guard.into_parts(); + let mut pool_guard = DropGuard::new(pool, vm); + let (pool, vm) = pool_guard.as_parts_mut(); + let r = permutations_r(r, pool.len(), vm)?; + let (pool, vm) = pool_guard.into_parts(); + let iter = ItertoolsIter::Permutations(Box::new(Permutations::new(pool, r))); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Resolves `permutations`' `r`: `None` means every item, and only a real +/// `int` is accepted. +/// +/// CPython checks the type rather than calling `__index__`, so `1.0` and an +/// `__index__` object are both `Expected int as r`; a `bool` passes as an +/// `int` subclass. +fn permutations_r(r: Value, n: usize, vm: &mut VM<'_>) -> RunResult { + defer_drop!(r, vm); + if matches!(r, Value::None) { + Ok(n) + } else if matches!(r.py_type_heap(vm.heap), Type::Int | Type::Bool) { + usize::try_from(ssize_arg(r, vm)?).map_err(|_| ExcType::combinatoric_negative_r()) + } else { + Err(ExcType::permutations_bad_r()) + } +} + +/// Argument shape for `product(*iterables, repeat=1)`. +/// +/// CPython hand-parses this: the positionals are taken as they come, and the +/// keywords alone go through `PyArg_ParseTupleAndKeywords`, whose one-slot +/// `kwlist` gives the derive's `got an unexpected keyword argument 'x'` +/// wording for a bad name. `repeat` stays a raw `Value` for the `Py_ssize_t` +/// conversion in the body. +#[derive(FromArgs)] +#[from_args(name = "product")] +struct ProductArgs { + #[from_args(varargs)] + iterables: Vec, + #[from_args(kw_only, default = Value::Int(1))] + repeat: Value, +} + +/// `itertools.product(*iterables, repeat=1)` — the cartesian product. +fn call_product(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ProductArgs { iterables, repeat } = ProductArgs::from_args(args, vm)?; + // Each argument is moved out of the vec as it is collected; the ones a + // `repeat` of zero never reaches stay in it and are released by the guard, + // as `zip_longest` does — see there for why not `drain`. + defer_drop_mut!(iterables, vm); + let converted = ssize_arg(&repeat, vm); + repeat.drop_with(vm); + let repeat = usize::try_from(converted?).map_err(|_| ExcType::product_negative_repeat())?; + + // `repeat=0` never touches the arguments: CPython skips collecting them, + // so `product(5, repeat=0)` is the single empty tuple, not a `TypeError`. + let width = if repeat == 0 { 0 } else { iterables.len() }; + let slots = product_slots(width, repeat)?; + + let mut pools_guard = DropGuard::new(Vec::with_capacity(width), vm); + for slot in iterables.iter_mut().take(width) { + let iterable = mem::replace(slot, Value::None); + let (pools, vm) = pools_guard.as_parts_mut(); + let pool: Vec = collect_owned_iterable(iterable, vm)?; + pools.push(pool); + } + // The index vector and every result tuple scale with `repeat` alone, so + // they are preflighted (`product('ab', repeat=10**9)`). An empty pool + // empties the product, and `Product::new` then allocates nothing at all — + // so `product([], repeat=10**9)` must not be refused for a cost it never + // pays. + let (pools, vm) = pools_guard.as_parts_mut(); + if pools.iter().all(|pool| !pool.is_empty()) { + check_estimated_size(slots.saturating_mul(size_of::() + VALUE_SIZE), &vm.heap.tracker)?; + } + let (pools, vm) = pools_guard.into_parts(); + let iter = ItertoolsIter::Product(Box::new(Product::new(pools, slots))); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// The number of slots `product` will step, rejecting a `repeat` that puts the +/// index vector beyond what a machine integer can address. +/// +/// CPython bounds `nargs * repeat * sizeof(Py_ssize_t)` by `PY_SSIZE_T_MAX` and +/// raises before it touches the arguments. The count this returns is the one +/// [`Product::new`] is given, so the multiplication happens once, here, where +/// it is checked. +fn product_slots(width: usize, repeat: usize) -> RunResult { + match width.checked_mul(repeat) { + Some(slots) if index_bytes(slots).is_some() => Ok(slots), + _ => Err(ExcType::product_repeat_too_large()), + } +} + +/// The byte size of an index vector of `slots` entries, or `None` when that is +/// more than any allocation could address. +fn index_bytes(slots: usize) -> Option { + slots + .checked_mul(size_of::()) + .filter(|bytes| *bytes <= isize::MAX.cast_unsigned()) +} + +/// Argument shape for `groupby(iterable, key=None)`. +/// +/// Clinic and keyword-capable like [`CombinationsArgs`]; `key` is never +/// type-checked, as CPython discovers a non-callable only when the first +/// item is keyed. +#[derive(FromArgs)] +#[from_args(name = "groupby", style = c_named, at_most_total)] +struct GroupbyArgs { + #[from_args(static_string = "IterableArg")] + iterable: Value, + #[from_args(default = Value::None)] + key: Value, +} + +/// `itertools.groupby(iterable, key=None)` — `(key, group)` per run of equal keys. +fn call_groupby(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let GroupbyArgs { iterable, key } = GroupbyArgs::from_args(args, vm)?; + let (key, source) = resolve_source(key, iterable, vm)?; + let iter = ItertoolsIter::GroupBy(Box::new(GroupBy::new(source, key))); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// `itertools.chain.from_iterable(iterable)` — the items of each of +/// `iterable`'s items, back to back. +/// +/// `METH_O` in CPython, so keywords are rejected wholesale and the arity +/// wording is `takes exactly one argument (N given)`. +fn call_chain_from_iterable(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let mut positional = args.into_pos_only("chain.from_iterable", vm.heap)?; + let count = positional.len(); + if count != 1 { + positional.drop_with(vm); + return Err(ExcType::type_error_arg_count("chain.from_iterable", 1, count)); + } + let iterable = positional.next().expect("exactly one positional argument"); + // The outer iterable is resolved now — `chain.from_iterable(5)` raises + // here — while its items are resolved one at a time, as `chain`'s + // arguments are. + let outer = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + let iter = ItertoolsIter::Chain(Chain::from_iterable(outer)); + Ok(Value::Ref(vm.heap.allocate(HeapData::Itertools(iter)))) +} + +/// Argument shape for `tee(iterable, n=2)`. +/// +/// `PyArg_UnpackTuple` with a 1..2 arity, so arity errors read `tee expected at +/// most 2 arguments, got 3`. The blanket keyword rejection is the one in this +/// module that names the function with its module (`itertools.tee()`), hence +/// the `kwarg_error_name`. `n` stays a raw `Value` for the `Py_ssize_t` +/// conversion in the body, as `batched`'s does. +#[derive(FromArgs)] +#[from_args(name = "tee", style = unpack, kwarg_error_name = "itertools.tee")] +struct TeeArgs { + #[from_args(pos_only)] + iterable: Value, + #[from_args(pos_only, default)] + n: Option, +} + +/// `itertools.tee(iterable, n=2)` — `n` iterators over one source. +fn call_tee(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let TeeArgs { iterable, n } = TeeArgs::from_args(args, vm)?; + let consumers = match n { + None => Ok(2), + Some(n) => { + let converted = tee_n(&n, vm); + n.drop_with(vm); + converted + } + }; + let consumers = match consumers { + Ok(consumers) => consumers, + Err(error) => { + iterable.drop_with(vm); + return Err(error); + } + }; + + // No consumers means nothing to read from, and CPython never looks at the + // iterable in that case: `tee(5, 0)` is the empty tuple, not a `TypeError`. + if consumers == 0 { + iterable.drop_with(vm); + return Ok(allocate_tuple(TupleVec::new(), vm.heap)); + } + + // Resolved first, then tested: CPython calls `iter()` before it reaches for + // `__copy__`, so an object whose `__iter__` hands back an existing `_tee` + // is copied too rather than being drained into a second buffer. + let source = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + // An existing `_tee` is copied rather than drained, so the copies replay + // from where it stands — CPython reaches for `__copy__` for the same + // reason. Anything else becomes the source of a fresh group. + let tees = if let Some(tees) = tee::fork_group(&source, consumers, vm) { + source.drop_with(vm); + tees + } else { + tee::new_group(source, consumers, vm) + }; + Ok(allocate_tuple(TupleVec::from_vec(tees), vm.heap)) +} + +/// Coerces `tee`'s `n` and enforces CPython's "not negative" floor. +/// +/// A group of `n` costs a heap entry and a buffer position per consumer, plus +/// the tuple slot each is returned in — all of it inside one builtin call, so +/// the whole group is charged before any of it is built. CPython reports an +/// `n` too large as a bare `MemoryError` when its own allocation fails. +fn tee_n(value: &Value, vm: &mut VM<'_>) -> RunResult { + let n = ssize_arg(value, vm)?; + let n = usize::try_from(n).map_err(|_| ExcType::tee_negative_n())?; + let per_consumer = HEAP_ENTRY_SIZE + size_of::() + VALUE_SIZE; + let bytes = n + .checked_mul(per_consumer) + .filter(|bytes| *bytes <= isize::MAX.cast_unsigned()) + .ok_or_else(ExcType::allocation_too_large)?; + check_estimated_size(bytes, &vm.heap.tracker)?; + Ok(n) +} + +/// Resolves the iterable while keeping the callable safe from the error path. +/// +/// CPython resolves eagerly for all four, so a non-iterable raises here rather +/// than on the first `next()`. The callable itself is never type-checked: a +/// non-callable is only discovered when the adaptor first applies it. +fn resolve_source(callable: Value, iterable: Value, vm: &mut VM<'_>) -> RunResult<(Value, Value)> { + let mut guard = DropGuard::new(callable, vm); + let source = iterable.into_py_iter(guard.ctx())?.require_synchronous(guard.ctx())?; + let (callable, _) = guard.into_parts(); + Ok((callable, source)) +} diff --git a/crates/bashkit-monty/src/modules/json/dump.rs b/crates/bashkit-monty/src/modules/json/dump.rs new file mode 100644 index 000000000..46e6816be --- /dev/null +++ b/crates/bashkit-monty/src/modules/json/dump.rs @@ -0,0 +1,1007 @@ +//! JSON serialization support for `json.dumps()` and `json.dump()`. +//! +//! This module owns encoder keyword parsing, CPython-compatible string/float +//! formatting, and recursive serialization of Monty values. `dump` encodes +//! the whole document first and hands it to the file object in one write +//! (see [`FileTarget`]). + +use std::fmt::Write; + +use super::fp::FileTarget; +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::{CallResult, ContainsVM, VM}, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{ContainsHeap, DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapRead}, + py_value::PyValue, + sorting::{apply_permutation, sort_indices}, + types::{Dict, PyTrait, Type, str::allocate_string}, + value::Value, +}; + +/// Serializer configuration derived from `json.dumps()` keyword arguments. +/// +/// The struct stores only the subset of encoder configuration that this module +/// actually uses while serializing. Unsupported or not-yet-implemented kwargs +/// still raise during parsing so call sites do not silently lose behavior. +struct JsonDumpsConfig { + indent: Option, + item_separator: String, + key_separator: String, + flags: u8, +} + +impl Default for JsonDumpsConfig { + /// Returns the CPython default `json.dumps()` configuration. + /// + /// Compact output uses `", "` between items and `": "` between keys and + /// values, ASCII escaping is enabled, NaN and infinity are emitted as + /// `NaN`/`Infinity`, and invalid dict keys raise immediately. + fn default() -> Self { + Self { + indent: None, + item_separator: ", ".to_owned(), + key_separator: ": ".to_owned(), + flags: Self::ENSURE_ASCII | Self::ALLOW_NAN, + } + } +} + +impl JsonDumpsConfig { + /// Bit flag storing the `sort_keys` option. + const SORT_KEYS: u8 = 1 << 0; + /// Bit flag storing the `ensure_ascii` option. + const ENSURE_ASCII: u8 = 1 << 1; + /// Bit flag storing the `allow_nan` option. + const ALLOW_NAN: u8 = 1 << 2; + /// Bit flag storing the `skipkeys` option. + const SKIPKEYS: u8 = 1 << 3; + + /// Returns whether `sort_keys=True` is enabled. + fn sort_keys(&self) -> bool { + self.flags & Self::SORT_KEYS != 0 + } + + /// Returns whether non-ASCII characters must be escaped. + fn ensure_ascii(&self) -> bool { + self.flags & Self::ENSURE_ASCII != 0 + } + + /// Returns whether NaN and infinity may be emitted as JSON tokens. + fn allow_nan(&self) -> bool { + self.flags & Self::ALLOW_NAN != 0 + } + + /// Returns whether unsupported dict keys should be skipped. + fn skipkeys(&self) -> bool { + self.flags & Self::SKIPKEYS != 0 + } + + /// Builds the encoder config from the bound keyword arguments. + /// + /// The `FromArgs` structs already bound the arguments and rejected unknown + /// keywords. This translates the raw values into encoder options, raising in + /// CPython's order: `separators` is unpacked by `JSONEncoder.__init__`, then + /// `' ' * indent` and the separator types are checked as the encoder is built; + /// `checks` says how much of that a call reaches. + fn from_kwargs(kwargs: &EncoderKwargs, checks: EncoderChecks, vm: &mut VM<'_>) -> RunResult { + let mut config = Self::default(); + + let separators_were_set = check_separators_shape(&kwargs.separators, vm)?; + if checks != EncoderChecks::Unpack { + config.indent = parse_indent_value(&kwargs.indent, vm)?; + } + // `separators=None` means the indent-aware defaults below. + if checks == EncoderChecks::All + && let Some((item, key)) = parse_separators_value(&kwargs.separators, vm)? + { + config.item_separator = item; + config.key_separator = key; + } + + config.flags = apply_bool_flag(config.flags, Self::SORT_KEYS, &kwargs.sort_keys, vm)?; + config.flags = apply_bool_flag(config.flags, Self::ENSURE_ASCII, &kwargs.ensure_ascii, vm)?; + config.flags = apply_bool_flag(config.flags, Self::ALLOW_NAN, &kwargs.allow_nan, vm)?; + config.flags = apply_bool_flag(config.flags, Self::SKIPKEYS, &kwargs.skipkeys, vm)?; + + if config.indent.is_some() && !separators_were_set { + ",".clone_into(&mut config.item_separator); + ": ".clone_into(&mut config.key_separator); + } + + Ok(config) + } +} + +/// How far a call gets through CPython's encoder setup before encoding, which +/// decides the keyword errors it can raise. +#[derive(Clone, Copy, PartialEq, Eq)] +enum EncoderChecks { + /// `json.dumps` of a `str` returns before building an encoder. + Unpack, + /// `json.dump` of a `str`: the pure-Python encoder builds `' ' * indent` + /// but never uses the separators. + Indent, + /// Every other call: the separators must be `str`. + All, +} + +impl EncoderChecks { + /// The checks `json.dumps` (`dump = false`) or `json.dump` makes for `obj`. + fn for_call(obj: &Value, dump: bool, vm: &VM<'_>) -> Self { + match (obj.is_str(vm.heap), dump) { + (false, _) => Self::All, + (true, false) => Self::Unpack, + (true, true) => Self::Indent, + } + } +} + +/// The encoder keyword arguments as bound by [`JsonDumpsArgs`] / [`JsonDumpArgs`], +/// before [`JsonDumpsConfig::from_kwargs`] coerces them. Callers hold it under +/// `defer_drop!` so a coercion error part-way through releases every field. +struct EncoderKwargs { + indent: Value, + sort_keys: Value, + ensure_ascii: Value, + allow_nan: Value, + separators: Value, + skipkeys: Value, +} + +impl DropWithContext for EncoderKwargs { + fn drop_with(self, ctx: &mut C) { + self.indent.drop_with(ctx); + self.sort_keys.drop_with(ctx); + self.ensure_ascii.drop_with(ctx); + self.allow_nan.drop_with(ctx); + self.separators.drop_with(ctx); + self.skipkeys.drop_with(ctx); + } +} + +/// Implements `json.dumps(obj, **kwargs)`. +/// +/// Only the first argument may be positional. Supported keyword arguments mirror +/// the high-value subset of CPython's encoder configuration: `indent`, +/// `sort_keys`, `ensure_ascii`, `allow_nan`, `separators`, and `skipkeys`. +/// +/// CPython kwargs `cls`, `default`, and `check_circular` are intentionally +/// unsupported and will raise `TypeError` if passed. +pub(super) fn call_dumps(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let JsonDumpsArgs { + obj, + indent, + sort_keys, + ensure_ascii, + allow_nan, + separators, + skipkeys, + } = JsonDumpsArgs::from_args(args, vm)?; + // `obj` outlives kwarg processing: an early error below must not leak it. + defer_drop!(obj, vm); + let kwargs = EncoderKwargs { + indent, + sort_keys, + ensure_ascii, + allow_nan, + separators, + skipkeys, + }; + defer_drop!(kwargs, vm); + let config = JsonDumpsConfig::from_kwargs(kwargs, EncoderChecks::for_call(obj, false, vm), vm)?; + let output = encode(obj, &config, vm)?; + Ok(allocate_string(output, vm.heap)) +} + +/// Implements `json.dump(obj, fp, **kwargs)` with the same keyword subset as +/// [`call_dumps`]: the document is encoded in full, then written to `fp` as +/// one `write()` call, and the function evaluates to `None`. +/// +/// An `open()` handle takes the one-shot host write (the call suspends like +/// `fp.write` would); any other object has its `write` attribute called +/// synchronously. CPython streams chunks instead, so it reaches `fp.write` +/// before a bad element deep in a container raises, but after a scalar that +/// cannot be encoded; the file object is checked first or last to match. +pub(super) fn call_dump(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let JsonDumpArgs { + obj, + fp, + indent, + sort_keys, + ensure_ascii, + allow_nan, + separators, + skipkeys, + } = JsonDumpArgs::from_args(args, vm)?; + defer_drop!(obj, vm); + defer_drop!(fp, vm); + let kwargs = EncoderKwargs { + indent, + sort_keys, + ensure_ascii, + allow_nan, + separators, + skipkeys, + }; + defer_drop!(kwargs, vm); + let config = JsonDumpsConfig::from_kwargs(kwargs, EncoderChecks::for_call(obj, true, vm), vm)?; + + let early_target = if is_container(obj, vm) { + Some(FileTarget::writer(fp, vm)?) + } else { + None + }; + // Released if encoding fails, otherwise taken back to write to. + let mut early_target = DropGuard::new(early_target, vm); + let output = encode(obj, &config, early_target.ctx())?; + let (early_target, vm) = early_target.into_parts(); + let target = match early_target { + Some(target) => target, + None => FileTarget::writer(fp, vm)?, + }; + target.write(output, vm) +} + +/// Serializes `obj` to JSON text under `config`. +fn encode(obj: &Value, config: &JsonDumpsConfig, vm: &mut VM<'_>) -> RunResult { + let mut output = String::new(); + let mut active_containers = Vec::new(); + let mut encoder = Encoder { + out: &mut output, + config, + active_containers: &mut active_containers, + vm, + }; + encoder.serialize_value(obj, 0)?; + Ok(output) +} + +/// Whether CPython's encoder would yield a chunk of `value` (its opening +/// bracket) before any of its elements could fail to encode. +fn is_container(value: &Value, vm: &VM<'_>) -> bool { + match value { + Value::Ref(heap_id) => matches!( + vm.heap.get(*heap_id), + HeapData::List(_) | HeapData::Tuple(_) | HeapData::Dict(_) + ), + _ => false, + } +} + +/// Argument shape for `json.dumps(obj, *, indent=None, sort_keys=False, +/// ensure_ascii=True, allow_nan=True, separators=None, skipkeys=False)`. +/// +/// Arity and missing-arg errors use the `dumps()` descriptor with `style = +/// def` wording (CPython's `json.dumps` is a pure-Python `def`), but the +/// unknown-kwarg error uses `JSONEncoder.__init__()` — CPython's `json.dumps` +/// forwards unknown kwargs straight to the encoder constructor, which is what +/// surfaces in the error. `kwarg_error_name` overrides the function name used +/// in the unexpected-keyword message without affecting other error paths. +/// Every field is a raw `Value` so the encoder can apply its own truth-test +/// (`py_bool`) or shape coercion (`parse_indent_value` / +/// `parse_separators_value`) on the way through. +#[derive(FromArgs)] +#[from_args(name = "dumps", style = def, kwarg_error_name = "JSONEncoder.__init__")] +struct JsonDumpsArgs { + obj: Value, + #[from_args(kw_only, default = Value::None)] + indent: Value, + #[from_args(kw_only, default = Value::Bool(false))] + sort_keys: Value, + #[from_args(kw_only, default = Value::Bool(true))] + ensure_ascii: Value, + #[from_args(kw_only, default = Value::Bool(true))] + allow_nan: Value, + #[from_args(kw_only, default = Value::None)] + separators: Value, + #[from_args(kw_only, default = Value::Bool(false))] + skipkeys: Value, +} + +/// Argument shape for `json.dump(obj, fp, *, …)`: [`JsonDumpsArgs`] with the +/// file object as second positional, under the `dump()` descriptor. +#[derive(FromArgs)] +#[from_args(name = "dump", style = def, kwarg_error_name = "JSONEncoder.__init__")] +struct JsonDumpArgs { + obj: Value, + fp: Value, + #[from_args(kw_only, default = Value::None)] + indent: Value, + #[from_args(kw_only, default = Value::Bool(false))] + sort_keys: Value, + #[from_args(kw_only, default = Value::Bool(true))] + ensure_ascii: Value, + #[from_args(kw_only, default = Value::Bool(true))] + allow_nan: Value, + #[from_args(kw_only, default = Value::None)] + separators: Value, + #[from_args(kw_only, default = Value::Bool(false))] + skipkeys: Value, +} + +/// Sets `bit` in `flags` when `value` is truthy, clearing it otherwise. Used by the json.dumps kwarg pipeline so each +/// boolean-style flag is handled with a single line. +fn apply_bool_flag(flags: u8, bit: u8, value: &Value, vm: &mut VM<'_>) -> RunResult { + if value.py_bool(vm)? { + Ok(flags | bit) + } else { + Ok(flags & !bit) + } +} + +/// Parses the `indent=` value for `json.dumps()`. +/// +/// `None` keeps compact mode, a string is repeated once per depth level, and +/// any other value becomes CPython's `' ' * indent`: integers give that many +/// spaces (none when zero or negative) and other types raise its `TypeError`. +fn parse_indent_value(value: &Value, vm: &mut VM<'_>) -> RunResult> { + match value.py_value(vm) { + PyValue::None => Ok(None), + PyValue::Bool(value) => spaces_from_indent_count(i64::from(value)), + PyValue::Int(integer) => { + spaces_from_indent_count(integer.to_i64(vm).ok_or_else(ExcType::overflow_index_sized_int)?) + } + PyValue::Str(value) => Ok(Some(value.as_str(vm).to_owned())), + _ => Err(ExcType::type_error_sequence_repeat(value.py_type_name(vm))), + } +} + +/// Builds the `' ' * count` indent string. +fn spaces_from_indent_count(count: i64) -> RunResult> { + // CPython repeats a negative count to the empty string. + let count = if count < 0 { + 0 + } else { + usize::try_from(count).map_err(|_| ExcType::overflow_index_sized_int())? + }; + Ok(Some(" ".repeat(count))) +} + +/// Raises the unpacking errors `JSONEncoder.__init__` gives `separators`, +/// returning whether a pair was passed. +fn check_separators_shape(value: &Value, vm: &VM<'_>) -> RunResult { + let len = match value { + Value::None => return Ok(false), + Value::Ref(heap_id) => match vm.heap.get(*heap_id) { + HeapData::Tuple(tuple) => tuple.as_slice().len(), + HeapData::List(list) => list.as_slice().len(), + _ => return Err(separators_not_iterable(value, vm)), + }, + _ => return Err(separators_not_iterable(value, vm)), + }; + check_separators_length(len)?; + Ok(true) +} + +/// CPython's error unpacking a non-iterable `separators` value. +fn separators_not_iterable(value: &Value, vm: &VM<'_>) -> RunError { + ExcType::type_error(format!("cannot unpack non-iterable {} object", value.py_type_name(vm))) +} + +/// Converts the `separators=` pair for the encoder, after +/// [`check_separators_shape`] has accepted it; `None` keeps the defaults. +fn parse_separators_value(value: &Value, vm: &VM<'_>) -> RunResult> { + let Value::Ref(heap_id) = value else { + return Ok(None); + }; + let items = match vm.heap.get(*heap_id) { + HeapData::Tuple(tuple) => tuple.as_slice(), + HeapData::List(list) => list.as_slice(), + _ => return Ok(None), + }; + Ok(Some(( + json_separator_to_string(&items[0], "item_separator", vm)?, + json_separator_to_string(&items[1], "key_separator", vm)?, + ))) +} + +/// Validates that the separators sequence has exactly two elements. +/// +/// Raises `ValueError` with the same unpacking-style message as CPython when +/// the length does not match the expected two elements. +fn check_separators_length(len: usize) -> RunResult<()> { + if len == 2 { + Ok(()) + } else { + Err(ExcType::unpack_size_error(2, len)) + } +} + +/// Converts a Monty value to a string for use as a JSON separator. +/// +/// CPython's C encoder validates separators as strings and refers to them by +/// their positional argument index in `make_encoder()`. The `role` parameter +/// selects the matching CPython argument number (6 for `item_separator`, +/// 5 for `key_separator`) so the error message matches CPython exactly. +fn json_separator_to_string(value: &Value, role: &str, vm: &VM<'_>) -> RunResult { + let arg_num = if role == "item_separator" { 6 } else { 5 }; + match value { + Value::InternString(string_id) => Ok(vm.interns.get_str(*string_id).to_owned()), + Value::Ref(heap_id) => match vm.heap.get(*heap_id) { + HeapData::Str(string) => Ok(string.as_str().to_owned()), + _ => Err(ExcType::type_error(format!( + "make_encoder() argument {arg_num} must be str, not {}", + value.py_type_name(vm) + ))), + }, + _ => Err(ExcType::type_error(format!( + "make_encoder() argument {arg_num} must be str, not {}", + value.py_type_name(vm) + ))), + } +} + +/// Mutable serialization context shared across the recursive `serialize_*` +/// methods. +/// +/// Groups the four pieces of per-call state that every recursive level needs +/// — the JSON output buffer, the encoder configuration, the cycle-detection +/// stack, and the VM (heap + interns) — so the recursive methods can be +/// invoked as `encoder.serialize_value(value, depth)` rather than threading +/// five separate parameters through every signature. +/// +/// `depth` is intentionally **not** a field of this struct: every recursive +/// call needs to bump it by one for the descent and restore it on return, +/// which is exactly what a stack-passed parameter does for free. +struct Encoder<'a, 'h> { + out: &'a mut String, + config: &'a JsonDumpsConfig, + active_containers: &'a mut Vec, + vm: &'a mut VM<'h>, +} + +/// Lets the encoder participate in the `DropGuard` / [`defer_drop_mut!`] +/// pattern: passing the encoder as the "heap" argument re-borrows the whole +/// encoder (including its `vm`) into the guard, which is exactly what we need +/// so the rebound iter and the rebound encoder share a lifetime. +impl ContainsHeap for Encoder<'_, '_> { + fn heap(&self) -> &Heap { + self.vm.heap() + } + + fn heap_mut(&mut self) -> &mut Heap { + self.vm.heap_mut() + } +} + +/// Lets a [`RecursionToken`](crate::bytecode::RecursionToken) (and the container +/// iterators that hold one) be released through the encoder via `defer_drop!`, +/// reaching the VM-side recursion counter while the encoder itself stays borrowable. +impl<'h> ContainsVM<'h> for Encoder<'_, 'h> { + fn vm(&mut self) -> &mut VM<'h> { + self.vm + } +} + +impl<'h> Encoder<'_, 'h> { + /// Serializes a Monty value into JSON text. + /// + /// Handles immediate primitives directly and delegates to type-specific + /// helpers for strings, long integers, lists, tuples, and dicts. + fn serialize_value(&mut self, value: &Value, depth: usize) -> RunResult<()> { + let view = value.py_value(self.vm); + // Strings size their own check, and containers check per item. + if matches!( + view, + PyValue::None | PyValue::Bool(_) | PyValue::Int(_) | PyValue::Float(_) + ) { + self.check_output_growth(0)?; + } + match view { + PyValue::None => { + self.out.push_str("null"); + Ok(()) + } + PyValue::Bool(true) => { + self.out.push_str("true"); + Ok(()) + } + PyValue::Bool(false) => { + self.out.push_str("false"); + Ok(()) + } + PyValue::Int(integer) => integer.write_decimal(self.out, self.vm), + PyValue::Float(value) => serialize_float(value, self.out, self.config), + PyValue::Str(string) => { + self.check_output_growth(string.as_str(self.vm).len())?; + write_json_string(string.as_str(self.vm), self.out, self.config.ensure_ascii()); + Ok(()) + } + PyValue::List(list) => self.with_entered_container(list.id(), |enc| { + let iter = list.iter(enc.vm)?; + defer_drop_mut!(iter, enc); + enc.serialize_array(depth, |enc, depth| { + if let Some(item) = iter.next(enc.vm)? { + enc.serialize_value(item, depth)?; + Ok(true) + } else { + Ok(false) + } + }) + }), + PyValue::Tuple(tuple) => self.with_entered_container(tuple.id(), |enc| { + let iter = tuple.iter(enc.vm)?; + defer_drop_mut!(iter, enc); + enc.serialize_array(depth, |enc, depth| { + if let Some(item) = iter.next(enc.vm)? { + enc.serialize_value(item, depth)?; + Ok(true) + } else { + Ok(false) + } + }) + }), + PyValue::Dict(dict) => { + // Dict pre-materializes entries because `sort_keys` and + // `skipkeys` need to mutate the entries vector before output. + let entries = self.collect_dict_entries(&dict); + let this = self; + defer_drop_mut!(entries, this); + // Need to explicitly acquire a recursion token for the dict as we don't go + // via the default dict iterator. + let token = this.vm.recursion_token()?; + defer_drop!(token, this); + this.with_entered_container(dict.id(), |enc| enc.serialize_dict(entries, depth)) + } + _ => { + // CPython names the class by `__name__`: `Decimal`, not `decimal.Decimal`. + // A user class's name is its `__name__` already, dots and all. + let type_name = value.py_type_name(self.vm); + let bare = if matches!(value.py_type(self.vm), Type::Instance(_)) { + &*type_name + } else { + type_name.rsplit_once('.').map_or(&*type_name, |(_, bare)| bare) + }; + Err(ExcType::json_not_serializable_error(bare)) + } + } + } + + /// Streams items from a list or tuple into a JSON array, formatting + /// separators and indentation between calls to `write_next`. + /// + /// `write_next` is invoked once per item slot and should write the JSON + /// for the next item, returning `Ok(true)` if it wrote one or `Ok(false)` + /// when the underlying iterator is exhausted. This shape lets the caller + /// plug in either a [`ListIter`](crate::types::list::ListIter) or a + /// [`TupleIter`](crate::types::tuple::TupleIter) without having to unify + /// their lending-iterator types. + /// + /// Circular-reference tracking still happens at the container level (via + /// [`with_entered_container`](Self::with_entered_container)) before this + /// helper is called; the recursion-depth bound is enforced by the + /// iterator's `RecursionToken`. + fn serialize_array( + &mut self, + depth: usize, + mut write_next: impl FnMut(&mut Self, usize) -> RunResult, + ) -> RunResult<()> { + self.out.push('['); + let pretty = self.config.indent.is_some(); + let mut wrote_any = false; + loop { + // Write the separator + indent BEFORE we know whether the next + // item exists; if `write_next` reports exhaustion we roll the + // cursor back. + let prefix_start = self.out.len(); + if wrote_any { + self.out.push_str(&self.config.item_separator); + } + if pretty { + self.out.push('\n'); + write_indent(self.out, self.config, depth + 1); + } + let body_start = self.out.len(); + if !write_next(self, depth + 1)? { + self.out.truncate(prefix_start); + break; + } + debug_assert!( + self.out.len() > body_start, + "write_next reported true but wrote nothing" + ); + wrote_any = true; + } + if pretty && wrote_any { + self.out.push('\n'); + write_indent(self.out, self.config, depth); + } + self.out.push(']'); + Ok(()) + } + + /// Copies a dict's `(key, value)` pairs into an owned `Vec` via + /// [`DictIter`](crate::types::dict::DictIter), so subsequent passes + /// (`skipkeys`, `sort_keys`) can mutate the buffer in place. The + /// `DictIter`'s recursion token is acquired and released during the + /// copy, bounding the depth of the *enclosing* `serialize_value` call. + fn collect_dict_entries(&mut self, dict: &HeapRead<'h, Dict>) -> Vec<(Value, Value)> { + dict.get(self.vm.heap) + .iter() + .map(|(k, v)| (k.clone_with_heap(self.vm.heap), v.clone_with_heap(self.vm.heap))) + .collect::>() + } + + /// Serializes a dict as a JSON object. + /// + /// Dict keys are validated and optionally skipped before serialization. + /// When `sort_keys=True`, entries are sorted using Python comparison + /// semantics on the original keys so mixed incomparable key types raise + /// the same style of `TypeError` as CPython. + fn serialize_dict(&mut self, entries: &mut Vec<(Value, Value)>, depth: usize) -> RunResult<()> { + if self.config.skipkeys() { + skip_disallowed_dict_keys(entries, self.vm); + } else if let Some((key, _)) = entries.iter().find(|(key, _)| !is_json_key_allowed(key, self.vm)) { + return Err(ExcType::json_invalid_key_error(&key.py_type_name(self.vm))); + } + + if self.config.sort_keys() { + sort_dict_entries(entries, self.vm)?; + } + + self.out.push('{'); + + let pretty = self.config.indent.is_some(); + for (index, (key, value)) in entries.iter().enumerate() { + if index != 0 { + self.out.push_str(&self.config.item_separator); + } + if pretty { + self.out.push('\n'); + write_indent(self.out, self.config, depth + 1); + } + write_json_key(key, self.out, self.config, self.vm)?; + self.out.push_str(&self.config.key_separator); + self.serialize_value(value, depth + 1)?; + } + if pretty && !entries.is_empty() { + self.out.push('\n'); + write_indent(self.out, self.config, depth); + } + self.out.push('}'); + Ok(()) + } + + /// Preflights the output buffer's next doubling before writing a value of + /// about `value_len` bytes, so serializing a large document raises + /// `MemoryError` instead of reallocating past the limit's headroom. + /// Escaping that outgrows the margin is left to the allocator's hard limit. + fn check_output_growth(&mut self, value_len: usize) -> RunResult<()> { + const MARGIN: usize = 64; + let (len, capacity) = (self.out.len(), self.out.capacity()); + let needed = len.saturating_add(value_len).saturating_add(MARGIN); + if needed > capacity { + // `String::reserve` grows to at least double the capacity. + let target = needed.max(capacity.saturating_mul(2)); + self.vm.heap.tracker.check_allocation(target - capacity)?; + self.out.reserve(needed - len); + } + Ok(()) + } + + /// Runs `f` while `heap_id` is marked active for cycle detection. + /// + /// Centralizes the push/pop bookkeeping so every serialization path pops + /// the container again regardless of whether recursive serialization + /// succeeds or returns early with an error. + fn with_entered_container( + &mut self, + heap_id: HeapId, + f: impl FnOnce(&mut Self) -> RunResult, + ) -> RunResult { + if self.active_containers.contains(&heap_id) { + return Err(ExcType::json_circular_reference_error()); + } + self.active_containers.push(heap_id); + let result = f(self); + self.active_containers + .pop() + .expect("entered container missing from JSON serialization stack"); + result + } +} + +/// Sorts dict entries in-place using Python comparison semantics on the keys. +/// +/// The implementation mirrors the error style used by `sorted()` and +/// `list.sort()`: when two keys are not orderable, it raises +/// `TypeError: '<' not supported between instances of ...`. +fn sort_dict_entries(entries: &mut Vec<(Value, Value)>, vm: &mut VM<'_>) -> RunResult<()> { + let mut indices: Vec = (0..entries.len()).collect(); + let compare_values: Vec = entries.iter().map(|(key, _)| key.clone_with_heap(vm)).collect(); + defer_drop!(compare_values, vm); + sort_indices(&mut indices, compare_values.as_slice(), false, vm)?; + apply_permutation(entries.as_mut_slice(), &mut indices); + Ok(()) +} + +/// Removes dict entries whose keys are not JSON-serializable, preserving order. +fn skip_disallowed_dict_keys(entries: &mut Vec<(Value, Value)>, vm: &mut VM<'_>) { + // Use two pointers to preserve relative order + let mut write = 0; + for read in 0..entries.len() { + if is_json_key_allowed(&entries[read].0, vm) { + if write != read { + entries.swap(write, read); + } + write += 1; + } + } + + // Drain the disallowed entries + entries.drain(write..).drop_with(vm); +} + +/// Returns whether a value is an allowed JSON object key type. +/// +/// CPython accepts strings, integers, floats, booleans, and `None`, then +/// coerces the non-string cases to JSON strings during output. +fn is_json_key_allowed(value: &Value, vm: &VM<'_>) -> bool { + matches!( + value.py_value(vm), + PyValue::None | PyValue::Bool(_) | PyValue::Int(_) | PyValue::Float(_) | PyValue::Str(_) + ) +} + +/// Serializes a dict key by applying CPython's JSON key coercions. +/// +/// Non-string supported key types are rendered to their JSON string form first, +/// then escaped as a JSON string token. +fn write_json_key(key: &Value, out: &mut String, config: &JsonDumpsConfig, vm: &VM<'_>) -> RunResult<()> { + let ensure_ascii = config.ensure_ascii(); + match key.py_value(vm) { + PyValue::None => write_json_ascii_key("null", out), + PyValue::Bool(true) => write_json_ascii_key("true", out), + PyValue::Bool(false) => write_json_ascii_key("false", out), + PyValue::Int(integer) => { + out.push('"'); + integer.write_decimal(out, vm)?; + out.push('"'); + } + PyValue::Float(value) => serialize_float_key(value, out, config)?, + PyValue::Str(value) => write_json_string(value.as_str(vm), out, ensure_ascii), + _ => return Err(ExcType::json_invalid_key_error(&key.py_type_name(vm))), + } + Ok(()) +} + +/// Writes an already-ASCII JSON object key without going through the string +/// escaper. +/// +/// Coerced keys such as `None`, booleans, and numeric reprs are always ASCII +/// and require no escaping, so this avoids building intermediate `String` +/// values on the dict-key hot path. +fn write_json_ascii_key(value: &str, out: &mut String) { + out.push('"'); + out.push_str(value); + out.push('"'); +} + +/// Serializes a float value as a quoted JSON object key, respecting `allow_nan`. +/// +/// Non-finite values (NaN, +/-Infinity) are emitted as their Python repr +/// (`NaN`, `Infinity`, `-Infinity`) when `allow_nan` is enabled. When disabled, +/// the same `ValueError` raised for non-finite float *values* applies to keys +/// too, matching CPython's behavior. +fn serialize_float_key(value: f64, out: &mut String, config: &JsonDumpsConfig) -> RunResult<()> { + out.push('"'); + if value.is_nan() { + if !config.allow_nan() { + return Err(ExcType::json_nan_error("nan")); + } + out.push_str("NaN"); + } else if value == f64::INFINITY { + if !config.allow_nan() { + return Err(ExcType::json_nan_error("inf")); + } + out.push_str("Infinity"); + } else if value == f64::NEG_INFINITY { + if !config.allow_nan() { + return Err(ExcType::json_nan_error("-inf")); + } + out.push_str("-Infinity"); + } else { + write_json_float_text(value, out); + } + out.push('"'); + Ok(()) +} + +/// Serializes a float using JSON's number and NaN rules. +/// +/// Finite floats use CPython-compatible `json` float formatting, including the +/// switch to exponent notation for very small or very large magnitudes while +/// still preserving a decimal point for whole-valued non-exponent outputs. +fn serialize_float(value: f64, out: &mut String, config: &JsonDumpsConfig) -> RunResult<()> { + if value.is_nan() { + if config.allow_nan() { + out.push_str("NaN"); + Ok(()) + } else { + Err(ExcType::json_nan_error("nan")) + } + } else if value == f64::INFINITY { + if config.allow_nan() { + out.push_str("Infinity"); + Ok(()) + } else { + Err(ExcType::json_nan_error("inf")) + } + } else if value == f64::NEG_INFINITY { + if config.allow_nan() { + out.push_str("-Infinity"); + Ok(()) + } else { + Err(ExcType::json_nan_error("-inf")) + } + } else { + write_json_float_text(value, out); + Ok(()) + } +} + +/// Writes a finite float using CPython-compatible JSON float repr rules. +/// +/// Python switches to scientific notation when the magnitude is `>= 1e16` or +/// `< 1e-4` (and non-zero). We decide notation by comparing the absolute value +/// directly against these thresholds rather than using `log10().floor()`, which +/// has precision errors at boundary values (e.g. `9999999999999998.0` whose +/// `log10` rounds up to `16.0`). Direct comparison is exact because `1e16` is +/// exactly representable as f64 and `1e-4` as an f64 constant aligns with +/// Python's notation boundary. +/// +/// Each path formats the float exactly once: the scientific path writes via +/// `{:e}` and post-processes the exponent to Python style (`e+XX` / `e-XX`), +/// while the fixed path uses `Display` with a `.0` suffix for whole numbers. +fn write_json_float_text(value: f64, out: &mut String) { + let abs = value.abs(); + if abs != 0.0 && !(1e-4..1e16).contains(&abs) { + // Python-style scientific notation: format via `{:e}`, then rewrite the + // exponent from Rust's bare `e` to Python's `e+XX` / `e-XX`. + let start = out.len(); + write!(out, "{value:e}").expect("writing to String cannot fail"); + let e_pos = out[start..].find('e').expect("scientific format must contain 'e'") + start; + let exponent: i32 = out[e_pos + 1..].parse().expect("exponent must be a valid integer"); + out.truncate(e_pos); + let exp_sign = if exponent >= 0 { '+' } else { '-' }; + write!(out, "e{exp_sign}{:02}", exponent.unsigned_abs()).expect("writing to String cannot fail"); + } else { + // Fixed notation: single `Display` write, appending `.0` for whole numbers. + let start = out.len(); + write!(out, "{value}").expect("writing to String cannot fail"); + if !out[start..].contains('.') { + out.push_str(".0"); + } + } +} + +/// Writes indentation for pretty-printed JSON output. +/// +/// The `indent` string is repeated once for each nesting level, matching +/// CPython's behavior for both numeric and string indentation. +fn write_indent(out: &mut String, config: &JsonDumpsConfig, depth: usize) { + if let Some(indent) = &config.indent { + for _ in 0..depth { + out.push_str(indent); + } + } +} + +/// Writes a Rust string as a JSON string token. +/// +/// Uses a byte-oriented batch strategy inspired by serde_json: a 256-entry +/// lookup table classifies each byte in O(1), and contiguous runs of safe bytes +/// are flushed with a single `push_str` rather than character-by-character. +/// +/// When `ensure_ascii` is enabled, non-ASCII code points (bytes >= 0x80) are +/// emitted as `\uXXXX` escapes using surrogate pairs for supplementary-plane +/// characters. +fn write_json_string(value: &str, out: &mut String, ensure_ascii: bool) { + out.push('"'); + let bytes = value.as_bytes(); + let mut start = 0; + let mut i = 0; + + while i < bytes.len() { + let byte = bytes[i]; + + if ensure_ascii && byte >= 0x7F { + // Flush the safe ASCII run accumulated so far. + out.push_str(&value[start..i]); + if byte == 0x7F { + // DEL (0x7F) is a control character that CPython escapes. + out.push_str("\\u007f"); + i += 1; + } else { + // Decode the full character at this position and emit \uXXXX escapes. + let ch = value[i..].chars().next().expect("valid UTF-8"); + write_json_escape_for_non_ascii(ch, out); + i += ch.len_utf8(); + } + start = i; + continue; + } + + let escape = ESCAPE_TABLE[byte as usize]; + if escape == 0 { + // Safe byte — keep scanning. + i += 1; + continue; + } + + // Flush the safe run before this byte. + out.push_str(&value[start..i]); + + // Write the escape sequence. + match escape { + b'b' => out.push_str("\\b"), + b't' => out.push_str("\\t"), + b'n' => out.push_str("\\n"), + b'f' => out.push_str("\\f"), + b'r' => out.push_str("\\r"), + b'"' => out.push_str("\\\""), + b'\\' => out.push_str("\\\\"), + b'u' => { + write!(out, "\\u{:04x}", u32::from(byte)).expect("writing to String cannot fail"); + } + _ => unreachable!(), + } + + i += 1; + start = i; + } + + // Flush the final safe run. + out.push_str(&value[start..]); + out.push('"'); +} + +/// Byte lookup table for JSON string escaping. +/// +/// Each entry is either 0 (byte is safe, no escaping needed) or a shorthand +/// character that indicates which escape to emit: +/// - `b'"'` → `\"` +/// - `b'\\'` → `\\` +/// - `b'b'` → `\b` (backspace, 0x08) +/// - `b't'` → `\t` (tab, 0x09) +/// - `b'n'` → `\n` (newline, 0x0A) +/// - `b'f'` → `\f` (form feed, 0x0C) +/// - `b'r'` → `\r` (carriage return, 0x0D) +/// - `b'u'` → `\u00XX` (other control characters, 0x00–0x1F) +#[rustfmt::skip] +static ESCAPE_TABLE: [u8; 256] = { + let mut table = [0u8; 256]; + // Control characters 0x00–0x1F default to \u00XX escapes. + let mut i = 0; + while i < 0x20 { + table[i] = b'u'; + i += 1; + } + // Override the named escapes. + table[0x08] = b'b'; // backspace + table[0x09] = b't'; // tab + table[0x0A] = b'n'; // newline + table[0x0C] = b'f'; // form feed + table[0x0D] = b'r'; // carriage return + table[0x22] = b'"'; // quote + table[0x5C] = b'\\'; // backslash + table +}; + +/// Writes a non-ASCII character using JSON `\uXXXX` escapes. +/// +/// Code points above `U+FFFF` are encoded as UTF-16 surrogate pairs to match +/// CPython's `ensure_ascii=True` behavior. +fn write_json_escape_for_non_ascii(ch: char, out: &mut String) { + let code = ch as u32; + if code <= 0xFFFF { + write!(out, "\\u{code:04x}").expect("writing to String cannot fail"); + } else { + let code = code - 0x1_0000; + let high = 0xD800 + (code >> 10); + let low = 0xDC00 + (code & 0x3FF); + write!(out, "\\u{high:04x}\\u{low:04x}").expect("writing to String cannot fail"); + } +} diff --git a/crates/bashkit-monty/src/modules/json/fp.rs b/crates/bashkit-monty/src/modules/json/fp.rs new file mode 100644 index 000000000..e87df0b1f --- /dev/null +++ b/crates/bashkit-monty/src/modules/json/fp.rs @@ -0,0 +1,105 @@ +//! The file-object side of `json.load()` and `json.dump()`. +//! +//! An `open()` handle is read and written through its own buffered-read and +//! one-shot-write machinery, so `json.load` on an unread file suspends to the +//! host exactly as `fp.read()` would. Any other object is used through its +//! `read` / `write` attribute, called synchronously (see `limitations/json.md`). + +use crate::{ + args::ArgValues, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult, SimpleException}, + heap::{ContainsHeap, DropWithContext, HeapId, HeapReadOutput}, + intern::StaticStrings, + types::str::allocate_string, + value::{EitherStr, Value}, +}; + +/// Where `json.load` reads from or `json.dump` writes to. +pub(super) enum FileTarget { + /// An `open()` handle; the id is borrowed from the caller's `fp` value. + OpenFile(HeapId), + /// `fp.read` / `fp.write` of any other object, owned until called. + Method(Value), +} + +impl FileTarget { + /// Resolves `fp` for `json.load`. + pub(super) fn reader(fp: &Value, vm: &mut VM<'_>) -> RunResult { + Self::resolve(fp, StaticStrings::Read, vm) + } + + /// Resolves `fp` for `json.dump`, running the checks `fp.write(str)` makes + /// before reaching the host (text mode, open, writable; a callable `write` + /// otherwise) so they are raised before the document is encoded, as + /// CPython's first chunk would. + pub(super) fn writer(fp: &Value, vm: &mut VM<'_>) -> RunResult { + match Self::resolve(fp, StaticStrings::Write, vm)? { + Self::OpenFile(file_id) => { + if let HeapReadOutput::OpenFile(file) = vm.heap.read(file_id) { + file.check_text_write(vm)?; + } + Ok(Self::OpenFile(file_id)) + } + Self::Method(write) if write.is_callable(vm) => Ok(Self::Method(write)), + Self::Method(write) => { + defer_drop!(write, vm); + Err(ExcType::type_error_not_callable_object(&write.py_type_name(vm))) + } + } + } + + /// `fp.write(text)` for `json.dump`: the host write for an `open()` handle + /// (answering `None`), or a synchronous call of the `write` method. + pub(super) fn write(self, text: String, vm: &mut VM<'_>) -> RunResult { + match self { + Self::OpenFile(file_id) => { + let HeapReadOutput::OpenFile(mut file) = vm.heap.read(file_id) else { + unreachable!("FileTarget::OpenFile points to an OpenFile") + }; + file.write_text_discarding_count(vm, text) + } + Self::Method(write) => { + defer_drop!(write, vm); + let chunk = allocate_string(text, vm.heap); + let returned = vm.evaluate_function(write, ArgValues::One(chunk))?; + returned.drop_with(vm); + Ok(CallResult::Value(Value::None)) + } + } + } + + /// `fp` as an `open()` handle, else its `method` attribute: CPython's + /// `AttributeError` names the type when it is missing. + fn resolve(fp: &Value, method: StaticStrings, vm: &mut VM<'_>) -> RunResult { + if let Value::Ref(id) = fp + && matches!(vm.heap.read(*id), HeapReadOutput::OpenFile(_)) + { + Ok(Self::OpenFile(*id)) + } else { + let attr = EitherStr::Interned(vm.interns.intern_static(method)); + match fp.py_getattr(&attr, vm)? { + CallResult::Value(callable) => Ok(Self::Method(callable)), + // A host object's attribute would need a round trip the module + // function cannot wait for. + suspended => { + suspended.drop_with(vm); + Err(SimpleException::new_msg( + ExcType::NotImplementedError, + format!("json: `{}` of a host object is not supported", attr.as_str(vm.interns)), + ) + .into()) + } + } + } + } +} + +impl DropWithContext for FileTarget { + fn drop_with(self, heap: &mut C) { + if let Self::Method(callable) = self { + callable.drop_with(heap); + } + } +} diff --git a/crates/bashkit-monty/src/modules/json/load.rs b/crates/bashkit-monty/src/modules/json/load.rs new file mode 100644 index 000000000..7f233062c --- /dev/null +++ b/crates/bashkit-monty/src/modules/json/load.rs @@ -0,0 +1,643 @@ +//! JSON parsing support for `json.loads()` and `json.load()`. +//! +//! This module owns conversion from JSON bytes into Monty runtime values, +//! including CPython-compatible `JSONDecodeError` construction. `load` reads +//! the file object (see [`FileTarget`]) and parses what it returns. + +use std::{borrow::Cow, mem}; + +use jiter::{Jiter, JiterError, JiterErrorType, JsonErrorType, NumberAny, NumberInt, Peek}; + +use super::{JsonStringCache, fp::FileTarget}; +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::{CallResult, VM}, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{ContainsHeap, DropGuard, HeapData, HeapId, HeapReadOutput, HeapReader}, + os_dispatch::PostConversionEffect, + types::{ + Dict, List, LongInt, + file::apply_buffer_store, + long_int::{check_decimal_digit_count, decimal_digit_count_ascii}, + str::allocate_string, + }, + value::{VALUE_SIZE, Value}, +}; + +/// Internal error used while building Monty values from streamed JSON. +/// +/// JSON syntax failures remain as raw `JiterError` values until +/// `parse_json_bytes()`, while ordinary VM/runtime failures still propagate +/// immediately without being misreported as `JSONDecodeError`. +enum JsonLoadError { + Parse(JiterError), + Run(RunError), +} + +impl From for JsonLoadError { + fn from(error: JiterError) -> Self { + Self::Parse(error) + } +} + +impl From for JsonLoadError { + fn from(error: RunError) -> Self { + Self::Run(error) + } +} + +/// Result type used internally while streaming JSON from `jiter`. +type ParseResult = Result; + +/// Maximum JSON nesting depth accepted by `json.loads()`. +/// +/// This mirrors the default recursion limit used by `jiter`'s `JsonValue` +/// parser so the lower-level iterator path preserves the same safety boundary. +const JSON_RECURSION_LIMIT: usize = 200; + +/// Implements `json.loads(s)`. +/// +/// The function accepts exactly one positional argument. Input may be `str` or +/// `bytes`; parsed JSON values are converted recursively into Monty `Value`s. +/// Unlike CPython, `NaN`, `Infinity`, and `-Infinity` are always accepted +/// (there is no `parse_constant` parameter). +/// +/// `parse_float` and `parse_int` are called with each number's source text, as in +/// CPython (`json.loads(s, parse_float=Decimal)`). The kwargs `cls`, `object_hook`, +/// `parse_constant`, and `object_pairs_hook` are unsupported and raise `TypeError`. +pub(super) fn call_loads(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let JsonLoadsArgs { + s, + parse_float, + parse_int, + } = JsonLoadsArgs::from_args(args, vm)?; + let hooks = [parse_float, parse_int]; + defer_drop!(hooks, vm); + defer_drop_mut!(s, vm); + let [parse_float, parse_int] = hooks; + let hooks = NumberHooks { + parse_float: (!matches!(parse_float, Value::None)).then_some(parse_float), + parse_int: (!matches!(parse_int, Value::None)).then_some(parse_int), + }; + parse_json_input(s, &hooks, vm) +} + +/// The `parse_float` / `parse_int` callables `json.loads` converts number tokens with, +/// in place of `float()` / `int()`. +#[derive(Default)] +struct NumberHooks<'a> { + parse_float: Option<&'a Value>, + parse_int: Option<&'a Value>, +} + +/// Argument shape for `json.loads(s)`. +/// +/// CPython's `loads` is a pure-Python `def loads(s, *, cls=None, …)`, so `s` +/// is positional-or-keyword (`json.loads(s='1')` works) and signature errors +/// use `style = def` wording. The additional CPython kwargs (`cls`, `object_hook`, +/// …) are intentionally not implemented; leaving them off this struct means +/// the macro emits the "unexpected keyword" error for them, naming +/// `JSONDecoder.__init__` as CPython does for a keyword the decoder rejects. +#[derive(FromArgs)] +#[from_args(name = "loads", style = def, kwarg_error_name = "JSONDecoder.__init__")] +struct JsonLoadsArgs { + s: Value, + #[from_args(kw_only, default = Value::None)] + parse_float: Value, + #[from_args(kw_only, default = Value::None)] + parse_int: Value, +} + +/// Implements `json.load(fp)`: `fp.read()`, then [`call_loads`] on the result. +/// +/// An unread `open()` handle suspends for the host's full-file read with +/// [`PostConversionEffect::JsonLoad`] armed, so the parse runs on resume; a +/// loaded one parses the rest of its buffer at once. Any other object has +/// its `read` attribute called synchronously. +pub(super) fn call_load(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let JsonLoadArgs { fp } = JsonLoadArgs::from_args(args, vm)?; + defer_drop!(fp, vm); + match FileTarget::reader(fp, vm)? { + FileTarget::OpenFile(file_id) => { + let HeapReadOutput::OpenFile(mut file) = vm.heap.read(file_id) else { + unreachable!("FileTarget::OpenFile points to an OpenFile") + }; + match file.read_all_with(vm, |file_id| PostConversionEffect::JsonLoad { file_id })? { + CallResult::Value(text) => parse_owned(text, vm).map(CallResult::Value), + suspended => Ok(suspended), + } + } + FileTarget::Method(read) => { + defer_drop!(read, vm); + let text = vm.evaluate_function(read, ArgValues::Empty)?; + parse_owned(text, vm).map(CallResult::Value) + } + } +} + +/// `JsonLoad` resume: installs the host's content as the file buffer, exactly +/// as `fp.read()` would, then parses it. +pub(crate) fn apply_json_load(file_id: HeapId, result: Value, vm: &mut VM<'_>) -> RunResult { + let text = apply_buffer_store(file_id, result, vm)?; + parse_owned(text, vm) +} + +/// Parses what `fp.read()` returned, releasing it afterwards. +fn parse_owned(text: Value, vm: &mut VM<'_>) -> RunResult { + defer_drop!(text, vm); + parse_json_input(text, &NumberHooks::default(), vm) +} + +/// Argument shape for `json.load(fp)`, a pure-Python `def` like [`JsonLoadsArgs`] +/// with the same keyword policy. +#[derive(FromArgs)] +#[from_args(name = "load", style = def, kwarg_error_name = "JSONDecoder.__init__")] +struct JsonLoadArgs { + fp: Value, +} + +/// Parses a `json.loads()` input value and converts it into a Monty value. +/// +/// The parser works directly on the underlying byte slice. Decoded strings from +/// `jiter` are copied into Monty's heap immediately before any further parser +/// movement so borrowed tape-backed data never escapes. +fn parse_json_input(value: &Value, hooks: &NumberHooks<'_>, vm: &mut VM<'_>) -> RunResult { + let (bytes, is_str): (Cow<'_, [u8]>, bool) = match value { + Value::InternString(string_id) => (Cow::Borrowed(vm.interns.get_str(*string_id).as_bytes()), true), + Value::InternBytes(bytes_id) => (Cow::Borrowed(vm.interns.get_bytes(*bytes_id)), false), + Value::Ref(heap_id) => match vm.heap.get(*heap_id) { + HeapData::Str(s) => (Cow::Owned(s.as_str().as_bytes().to_vec()), true), + HeapData::Bytes(b) => (Cow::Owned(b.as_slice().to_vec()), false), + _ => return Err(ExcType::json_loads_type_error(&value.py_type_name(vm))), + }, + _ => return Err(ExcType::json_loads_type_error(&value.py_type_name(vm))), + }; + match bytes.strip_prefix(UTF8_BOM) { + // CPython rejects a BOM in `str` input, and decodes `bytes` input as `utf-8-sig`. + Some(_) if is_str => Err(ExcType::json_decode_error( + "Unexpected UTF-8 BOM (decode using utf-8-sig)", + &bytes, + 1, + 1, + 0, + )), + Some(rest) => parse_json_bytes(rest, hooks, vm), + None => parse_json_bytes(&bytes, hooks, vm), + } +} + +/// The UTF-8 encoding of U+FEFF, the byte order mark. +const UTF8_BOM: &[u8] = b"\xef\xbb\xbf"; + +/// Parses raw JSON bytes using `jiter` and converts the result to a Monty value. +/// +/// The VM's per-run string cache is temporarily extracted so that it can be +/// passed alongside the VM through the recursive parse functions without +/// borrow conflicts. It is always restored before returning. +/// +/// Syntax errors are wrapped in `json.JSONDecodeError` using the same +/// line/column/character suffix as CPython. +fn parse_json_bytes(bytes: &[u8], hooks: &NumberHooks<'_>, vm: &mut VM<'_>) -> RunResult { + let mut jiter = Jiter::new(bytes).with_allow_inf_nan(); + // Take the cache out of the VM so we can pass it alongside &mut VM + // without conflicting borrows. `mem::take` leaves `Default` in its place. + let mut cache = mem::take(&mut vm.json_string_cache); + let result = parse_json_value(&mut jiter, 0, &mut cache, hooks, vm); + // Always restore the cache before returning, regardless of success/failure. + vm.json_string_cache = cache; + let value = result.map_err(|error| match error { + JsonLoadError::Parse(error) => json_number_out_of_range_to_run_error(&error, bytes) + .unwrap_or_else(|| json_error_to_run_error(&error, bytes)), + JsonLoadError::Run(error) => error, + })?; + // The successfully parsed `value` must be dropped via `drop_with` if + // `finish()` detects trailing data — a plain `?` would leak its refcount. + if let Err(error) = jiter.finish() { + value.drop_with(vm); + return Err(json_error_to_run_error(&error, bytes)); + } + Ok(value) +} + +/// Parses the next JSON value from a `Jiter` and converts it into a Monty value. +/// +/// Strings are allocated immediately because `jiter` may reuse its internal +/// tape buffer on the next parser step. +fn parse_json_value( + jiter: &mut Jiter<'_>, + depth: usize, + cache: &mut JsonStringCache, + hooks: &NumberHooks<'_>, + vm: &mut VM<'_>, +) -> ParseResult { + let peek = jiter.peek()?; + parse_json_value_from_peek(peek, jiter, depth, cache, hooks, vm) +} + +/// Converts a peeked JSON token into a Monty value. +/// +/// The caller provides the `Peek` so container iteration can avoid reparsing +/// the next token after `array_step()`. +fn parse_json_value_from_peek( + peek: Peek, + jiter: &mut Jiter<'_>, + depth: usize, + cache: &mut JsonStringCache, + hooks: &NumberHooks<'_>, + vm: &mut VM<'_>, +) -> ParseResult { + match peek { + Peek::Null => { + jiter.known_null()?; + Ok(Value::None) + } + Peek::True | Peek::False => jiter.known_bool(peek).map(Value::Bool).map_err(Into::into), + Peek::String => Ok(allocate_cached_string(parse_json_string(jiter)?, cache, vm.heap)), + Peek::Array => parse_json_array(jiter, depth, cache, hooks, vm), + Peek::Object => parse_json_object(jiter, depth, cache, hooks, vm), + _ if peek.is_num() => parse_json_number(peek, jiter, hooks, vm), + _ => Err(JsonLoadError::Parse(JiterError { + error_type: JiterErrorType::JsonError(JsonErrorType::ExpectedSomeValue), + index: jiter.current_index(), + })), + } +} + +/// Allocates a string using the cache when eligible, falling back to direct +/// allocation for empty/single-char strings (already interned by +/// `allocate_string`). +fn allocate_cached_string(s: String, cache: &mut JsonStringCache, heap: &HeapReader<'_>) -> Value { + if s.len() < 2 { + // Empty and single-char strings are interned by allocate_string. + allocate_string(s, heap.heap()) + } else { + cache.get_or_allocate(s, heap) + } +} + +/// Parses a JSON number into the corresponding Monty numeric value. +/// +/// Oversized integers that exceed Monty's digit limit are rejected with a `ValueError`. +/// A `parse_float` / `parse_int` hook receives the token text instead; the +/// constants `NaN` and `Infinity` always become floats. +fn parse_json_number( + peek: Peek, + jiter: &mut Jiter<'_>, + hooks: &NumberHooks<'_>, + vm: &mut VM<'_>, +) -> ParseResult { + let start = jiter.current_index(); + // Parse to bytes so that we can check the digit count before any BigInt allocation occurs. + let token = jiter.known_number_bytes(peek)?; + let is_integer = is_json_integer_token(token); + let is_constant = matches!(token.first(), Some(b'N' | b'I')) || token.starts_with(b"-I"); + let hook = if is_integer { hooks.parse_int } else { hooks.parse_float }; + if let Some(hook) = hook.filter(|_| !is_constant) { + let text = String::from_utf8_lossy(token).into_owned(); + let text = allocate_string(text, vm.heap); + return Ok(vm.evaluate_function(hook, ArgValues::One(text))?); + } + if is_integer { + let digit_count = decimal_digit_count_ascii(token); + check_decimal_digit_count(digit_count).map_err(JsonLoadError::Run)?; + } + // `known_number_bytes` already validated the token, so `NumberAny::from_bytes` + // only re-parses the same byte range. Errors here are mapped back into the + // outer document's coordinate space so `json_error_to_run_error` reports + // the correct line/column. + let number = NumberAny::from_bytes(token, true).map_err(|error| { + JsonLoadError::Parse(JiterError { + error_type: JiterErrorType::JsonError(error.error_type), + index: start + error.index, + }) + })?; + match number { + NumberAny::Int(NumberInt::Int(value)) => Ok(Value::Int(value)), + NumberAny::Int(NumberInt::BigInt(value)) => Ok(LongInt::new(value).into_value(vm.heap)), + NumberAny::Float(value) => Ok(Value::Float(value)), + } +} + +/// Parses a JSON array and allocates the resulting Monty list directly. +/// +/// Elements are converted one by one as the iterator advances, avoiding any +/// intermediate `JsonValue` tree. +fn parse_json_array( + jiter: &mut Jiter<'_>, + depth: usize, + cache: &mut JsonStringCache, + hooks: &NumberHooks<'_>, + vm: &mut VM<'_>, +) -> ParseResult { + check_json_recursion_limit(jiter, depth)?; + + let Some(mut next) = jiter.known_array()? else { + let list_id = vm.heap.allocate(HeapData::List(List::new(Vec::new()))); + return Ok(Value::Ref(list_id)); + }; + + let values = Vec::new(); + let mut values_guard = DropGuard::new(values, vm); + loop { + let (values, vm) = values_guard.as_parts_mut(); + // The buffer check below cannot see what the elements themselves cost: + // `[{},{},...]` turns every three source bytes into a heap entry. + vm.heap + .tracker + .check_memory_time_every(values.len()) + .map_err(RunError::from)?; + let value = parse_json_value_from_peek(next, jiter, depth + 1, cache, hooks, vm)?; + // The whole parse runs inside one native call, so this doubling is the only + // thing between a graceful `MemoryError` and an allocation past the allocator's + // hard-limit headroom. Checked behind the element so it is weighed against + // usage that counts the element, with the guard releasing it on a refusal. + let mut value_guard = DropGuard::new(value, vm); + value_guard + .ctx() + .heap + .tracker + .check_growth(values.len(), values.capacity(), VALUE_SIZE) + .map_err(RunError::from)?; + values.push(value_guard.into_inner()); + let Some(array_peek) = jiter.array_step()? else { + break; + }; + next = array_peek; + } + + let values = values_guard.into_inner(); + let list_id = vm.heap.allocate(HeapData::List(List::new(values))); + Ok(Value::Ref(list_id)) +} + +/// Parses a JSON string and immediately copies it into an owned `String`. +/// +/// `Jiter` may reuse its internal tape for the next decoded string, so callers +/// must not hold onto the borrowed `&str` beyond the current parser step. +fn parse_json_string(jiter: &mut Jiter<'_>) -> ParseResult { + Ok(jiter.known_str().map(ToOwned::to_owned)?) +} + +/// Parses a JSON object and allocates the resulting Monty dict directly. +/// +/// Keys are allocated before parsing their values because `jiter` may reuse its +/// temporary string storage on the next parser step. +fn parse_json_object( + jiter: &mut Jiter<'_>, + depth: usize, + cache: &mut JsonStringCache, + hooks: &NumberHooks<'_>, + vm: &mut VM<'_>, +) -> ParseResult { + check_json_recursion_limit(jiter, depth)?; + + let Some(mut key) = parse_first_object_key(jiter)? else { + let dict_id = vm.heap.allocate(HeapData::Dict(Dict::new())); + return Ok(Value::Ref(dict_id)); + }; + + let mut dict_guard = DropGuard::new(Dict::new(), vm); + { + let (dict, vm) = dict_guard.as_parts_mut(); + loop { + let mut key_guard = DropGuard::new(allocate_cached_string(key, cache, vm.heap), &mut *vm); + let value = parse_json_value(jiter, depth + 1, cache, hooks, key_guard.ctx())?; + let (key_value, vm) = key_guard.into_parts(); + if let Some(old_value) = dict.set_json_string_key(key_value, value, vm)? { + old_value.drop_with(vm); + } + + let Some(next_key) = parse_next_object_key(jiter)? else { + break; + }; + key = next_key; + } + } + + let dict = dict_guard.into_inner(); + let dict_id = vm.heap.allocate(HeapData::Dict(dict)); + Ok(Value::Ref(dict_id)) +} + +/// Parses the first key of a JSON object and copies it into owned storage. +/// +/// Returning `None` indicates an empty object. +fn parse_first_object_key(jiter: &mut Jiter<'_>) -> ParseResult> { + Ok(jiter.known_object().map(|key| key.map(ToOwned::to_owned))?) +} + +/// Parses the next key of a JSON object and copies it into owned storage. +/// +/// Returning `None` indicates that the object has no more items. +fn parse_next_object_key(jiter: &mut Jiter<'_>) -> ParseResult> { + Ok(jiter.next_key().map(|key| key.map(ToOwned::to_owned))?) +} + +/// Rejects JSON that nests arrays/objects more deeply than Monty supports. +/// +/// The limit matches `jiter`'s `JsonValue` parser so this lower-level iterator +/// implementation preserves the same stack-safety boundary. +fn check_json_recursion_limit(jiter: &Jiter<'_>, depth: usize) -> ParseResult<()> { + if depth >= JSON_RECURSION_LIMIT { + return Err(JsonLoadError::Parse(JiterError { + error_type: JiterErrorType::JsonError(JsonErrorType::RecursionLimitExceeded), + index: jiter.current_index(), + })); + } + Ok(()) +} + +/// Converts `jiter`'s oversized-integer parse error into CPython's digit-limit +/// `ValueError` when the offending token is a decimal integer literal. +fn json_number_out_of_range_to_run_error(error: &JiterError, bytes: &[u8]) -> Option { + if error.error_type != JiterErrorType::JsonError(JsonErrorType::NumberOutOfRange) { + return None; + } + + let token = slice_json_number_around(bytes, error.index); + if !is_json_integer_token(token) { + return None; + } + + let digit_count = decimal_digit_count_ascii(token); + check_decimal_digit_count(digit_count).err() +} + +/// Returns whether a raw JSON number token is an integer literal rather than a +/// float or exponent form. +fn is_json_integer_token(token: &[u8]) -> bool { + !token.is_empty() && !token.contains(&b'.') && !token.contains(&b'e') && !token.contains(&b'E') +} + +/// Returns the JSON number token that surrounds `index`. +/// +/// `jiter` reports `NumberOutOfRange` at or just after the failing position, so +/// this scans outward to recover the original token for CPython-compatible +/// integer digit-limit handling. +fn slice_json_number_around(bytes: &[u8], index: usize) -> &[u8] { + let mut start = index.min(bytes.len()); + while start > 0 && is_json_number_byte(bytes[start - 1]) { + start -= 1; + } + + let mut end = index.min(bytes.len()); + while end < bytes.len() && is_json_number_byte(bytes[end]) { + end += 1; + } + + &bytes[start..end] +} + +/// Returns whether `byte` can appear in a JSON number token. +fn is_json_number_byte(byte: u8) -> bool { + matches!(byte, b'0'..=b'9' | b'+' | b'-' | b'.' | b'e' | b'E') +} + +/// Converts a `jiter` parse error into `json.JSONDecodeError`. +/// +/// `jiter` exposes the error byte index; [`error_coordinates`] converts it to +/// the character-based `pos`/`lineno`/`colno` CPython reports. +fn json_error_to_run_error(error: &JiterError, bytes: &[u8]) -> RunError { + let (message, index) = match &error.error_type { + JiterErrorType::JsonError(JsonErrorType::KeyMustBeAString) => ( + "Expecting property name enclosed in double quotes".to_owned(), + error.index, + ), + JiterErrorType::JsonError(JsonErrorType::TrailingComma) => { + let comma_index = find_trailing_comma_index(bytes, error.index).unwrap_or(error.index); + let message = match bytes + .get(comma_index.saturating_add(1)..) + .and_then(|rest| rest.iter().copied().find(|byte| !byte.is_ascii_whitespace())) + { + Some(b'}') => "Illegal trailing comma before end of object", + Some(b']') => "Illegal trailing comma before end of array", + _ => "trailing comma", + }; + (message.to_owned(), comma_index) + } + JiterErrorType::JsonError(JsonErrorType::EofWhileParsingString) => ( + "Unterminated string starting at".to_owned(), + find_unterminated_string_start(bytes, error.index).unwrap_or(error.index), + ), + JiterErrorType::JsonError(JsonErrorType::EofWhileParsingValue | JsonErrorType::ExpectedSomeValue) => { + ("Expecting value".to_owned(), error.index) + } + JiterErrorType::JsonError(JsonErrorType::ExpectedColon) => ("Expecting ':' delimiter".to_owned(), error.index), + JiterErrorType::JsonError( + JsonErrorType::ExpectedListCommaOrEnd + | JsonErrorType::ExpectedObjectCommaOrEnd + | JsonErrorType::EofWhileParsingList + | JsonErrorType::EofWhileParsingObject, + ) => ("Expecting ',' delimiter".to_owned(), error.index), + JiterErrorType::JsonError(JsonErrorType::InvalidEscape) => { + let escape_index = find_string_escape_start(bytes, error.index).unwrap_or(error.index); + let is_unicode_escape = bytes.get(escape_index.saturating_add(1)) == Some(&b'u'); + let message = if is_unicode_escape { + "Invalid \\uXXXX escape" + } else { + "Invalid \\escape" + }; + let index = if is_unicode_escape { + escape_index.saturating_add(1) + } else { + escape_index + }; + (message.to_owned(), index) + } + JiterErrorType::JsonError(JsonErrorType::TrailingCharacters) => ("Extra data".to_owned(), error.index), + JiterErrorType::JsonError(error_type) => (error_type.to_string(), error.index), + JiterErrorType::WrongType { .. } => (error.error_type.to_string(), error.index), + }; + let (pos, line, column) = error_coordinates(bytes, index); + ExcType::json_decode_error(&message, bytes, line, column, pos) +} + +/// CPython-style error coordinates `(pos, lineno, colno)` for a byte offset +/// into `bytes`: `pos` counts characters (UTF-8 sequence starts, not bytes), +/// and `colno` is characters since the last newline + 1 — locked to `pos` +/// exactly as `json.JSONDecodeError.__init__` derives them from `doc`. +/// +/// This deliberately replaces `jiter`'s `error_position`, which counts bytes +/// (wrong for multibyte documents) and clamps at end of input (wrong column +/// for EOF errors). +fn error_coordinates(bytes: &[u8], byte_index: usize) -> (usize, usize, usize) { + let prefix = &bytes[..byte_index.min(bytes.len())]; + let mut pos = 0; + let mut lineno = 1; + let mut column_chars = 0; + for &byte in prefix { + // a character starts at every byte that is not a UTF-8 continuation byte + if !matches!(byte, 0x80..=0xBF) { + pos += 1; + column_chars += 1; + } + if byte == b'\n' { + lineno += 1; + column_chars = 0; + } + } + (pos, lineno, column_chars + 1) +} + +/// Finds the opening quote for an unterminated JSON string. +/// +/// `jiter` reports the error at the EOF position, but CPython formats this +/// specific error using the location of the starting quote instead. +fn find_unterminated_string_start(bytes: &[u8], end_index: usize) -> Option { + let mut in_string = false; + let mut escaped = false; + let mut string_start = None; + + for (index, byte) in bytes.iter().copied().enumerate().take(end_index) { + if !in_string { + if byte == b'"' { + in_string = true; + string_start = Some(index); + } + continue; + } + + if escaped { + escaped = false; + continue; + } + + match byte { + b'\\' => escaped = true, + b'"' => { + in_string = false; + string_start = None; + } + _ => {} + } + } + + if in_string { string_start } else { None } +} + +/// Finds the comma that triggered a trailing-comma error. +/// +/// `jiter` reports the error at the closing delimiter after any intervening +/// whitespace, while CPython points at the comma itself. +fn find_trailing_comma_index(bytes: &[u8], end_index: usize) -> Option { + bytes + .get(..end_index)? + .iter() + .rposition(|byte| !byte.is_ascii_whitespace()) + .filter(|&index| bytes[index] == b',') +} + +/// Finds the start of the current JSON escape sequence. +/// +/// CPython reports invalid escape errors at the `\` for generic escapes and at +/// the `u` for malformed `\uXXXX` escapes. +fn find_string_escape_start(bytes: &[u8], end_index: usize) -> Option { + find_unterminated_string_start(bytes, end_index).and_then(|string_start| { + bytes + .get(string_start.saturating_add(1)..end_index)? + .iter() + .rposition(|byte| *byte == b'\\') + .map(|relative_index| string_start + 1 + relative_index) + }) +} diff --git a/crates/bashkit-monty/src/modules/json/mod.rs b/crates/bashkit-monty/src/modules/json/mod.rs new file mode 100644 index 000000000..80819f501 --- /dev/null +++ b/crates/bashkit-monty/src/modules/json/mod.rs @@ -0,0 +1,86 @@ +//! Implementation of Python's `json` module. +//! +//! This module implements the four entry points used by most programs: +//! - `json.loads()` / `json.load()` for parsing JSON text into Monty values +//! - `json.dumps()` / `json.dump()` for serializing Monty values to JSON text +//! +//! The implementation is split by direction so parsing and serialization logic +//! stay isolated: +//! - [`load`] handles JSON text -> Monty values +//! - [`dump`] handles Monty values -> JSON text +//! - [`fp`] reaches the file object the `load` / `dump` variants take + +mod dump; +mod fp; +mod load; +mod string_cache; + +pub(crate) use load::apply_json_load; +pub(crate) use string_cache::JsonStringCache; + +use super::ModuleFunctions; +use crate::{ + args::ArgValues, + builtins::Builtins, + bytecode::{CallResult, VM}, + exception_private::{ExcType, RunResult}, + heap::{HeapData, HeapId}, + intern::StaticStrings, + types::Module, + value::Value, +}; + +/// Functions exposed by the `json` module. +/// +/// Each variant corresponds to a module-level callable stored in the module's +/// attribute dictionary. The display form matches the Python-visible function +/// name so reprs look like normal builtins. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "lowercase")] +pub(crate) enum JsonFunctions { + /// `json.loads()` parses JSON text into Monty values. + Loads, + /// `json.dumps()` serializes Monty values into JSON text. + Dumps, + /// `json.load()` parses the rest of a file object as JSON. + Load, + /// `json.dump()` serializes a Monty value into a file object. + Dump, +} + +/// Creates the `json` module and allocates it on the heap. +/// +/// The module exposes `loads`, `dumps`, `load`, `dump` and `JSONDecodeError`. +/// These are the most widely used parts of CPython's `json` module and are +/// sufficient for common data interchange and round-tripping use cases inside +/// the sandbox. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Json, vm.interns); + for (name, function) in [ + (StaticStrings::Loads, JsonFunctions::Loads), + (StaticStrings::Dumps, JsonFunctions::Dumps), + (StaticStrings::Load, JsonFunctions::Load), + (StaticStrings::Dump, JsonFunctions::Dump), + ] { + module.set_attr(name, Value::ModuleFunction(ModuleFunctions::Json(function)), vm); + } + module.set_attr( + StaticStrings::JsonDecodeError, + Value::Builtin(Builtins::ExcType(ExcType::JsonDecodeError)), + vm, + ); + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a `json` module function call. +/// +/// `loads` and `dumps` are pure computations; `load` and `dump` on an unread +/// or written `open()` handle suspend to the host like `fp.read()` / `fp.write()`. +pub(super) fn call(vm: &mut VM<'_>, function: JsonFunctions, args: ArgValues) -> RunResult { + match function { + JsonFunctions::Loads => load::call_loads(vm, args).map(CallResult::Value), + JsonFunctions::Dumps => dump::call_dumps(vm, args).map(CallResult::Value), + JsonFunctions::Load => load::call_load(vm, args), + JsonFunctions::Dump => dump::call_dump(vm, args), + } +} diff --git a/crates/bashkit-monty/src/modules/json/string_cache.rs b/crates/bashkit-monty/src/modules/json/string_cache.rs new file mode 100644 index 000000000..b349b2b2b --- /dev/null +++ b/crates/bashkit-monty/src/modules/json/string_cache.rs @@ -0,0 +1,163 @@ +//! Per-run string cache for `json.loads()`. +//! +//! Repeated JSON parsing within a single execution often encounters the same +//! strings — especially dict keys like `"id"`, `"name"`, `"type"` — across +//! multiple `json.loads()` calls. This cache deduplicates heap allocations for +//! those strings by hashing incoming bytes and returning a `clone_with_heap` of +//! a previously allocated `Value` on cache hits. +//! +//! The design is modelled on jiter's `PyStringCache`: a fixed-capacity +//! fully-associative cache with linear probing and no eviction (when all probe +//! slots are occupied, the string is allocated without caching). The cache is +//! lazily initialized so programs that never call `json.loads()` pay zero cost. +//! +//! The cache lives on the [`VM`] and is scoped to a single execution run. It +//! is cleaned up when the VM is dropped; cached values stay alive across cycle +//! collections because each `Value::Ref` keeps the entry's refcount above zero, +//! and trial deletion treats non-zero refcount as proof of liveness. + +use std::iter; + +use ahash::RandomState; + +use crate::{ + heap::{ContainsHeap, HeapReader}, + types::str::{allocate_string, allocate_string_no_interning}, + value::Value, +}; + +/// Number of slots in the cache. +/// +/// Must be a power of two so the compiler can convert modulo to a bitwise AND. +const CAPACITY: usize = 16_384; + +/// Minimum string length eligible for caching. +/// +/// Empty strings and single-ASCII-character strings are already interned by +/// `allocate_string`, so caching them would be redundant. +const MIN_LEN: usize = 2; + +/// Maximum string length eligible for caching. +/// +/// Very long strings rarely repeat and would waste cache space. +const MAX_LEN: usize = 64; + +/// Entry in the string cache: `(hash, raw string, allocated Value)`. +type CacheEntry = Option<(u64, Box, Value)>; + +/// Lazily-initialized string cache for `json.loads()`. +/// +/// Wraps an `Option` so the backing array is only allocated on the +/// first eligible string, and programs that never parse JSON pay nothing. +/// +/// # Lifecycle +/// +/// - Created as empty (`None`) when the VM starts. +/// - Backing storage allocated on the first `get_or_allocate` call with an +/// eligible string (2–64 bytes). +/// - Persists across multiple `json.loads()` calls within the same run. +/// - Cleaned up when the VM is dropped via [`drop_all`](Self::drop_all). +/// - Cached values keep themselves alive via the refcount on each cached +/// `Value::Ref`; the trial-deletion cycle collector treats any non-zero +/// refcount as proof of liveness, so no explicit root walk is required. +#[derive(Default)] +pub(crate) struct JsonStringCache { + inner: Option, +} + +/// Backing storage: a fixed-size array of cache entries plus a hash builder. +struct CacheInner { + entries: Box<[CacheEntry; CAPACITY]>, + hash_builder: RandomState, +} + +impl JsonStringCache { + /// Looks up `s` in the cache. On hit, returns a cloned `Value` (with its + /// refcount incremented). On miss, allocates the string on the heap, stores + /// a clone in the cache, and returns the original. + /// + /// Strings shorter than [`MIN_LEN`] or longer than [`MAX_LEN`] bypass the + /// cache entirely and are allocated directly. + /// + /// The backing array is allocated lazily on the first eligible string. + pub fn get_or_allocate(&mut self, s: String, heap: &HeapReader<'_>) -> Value { + let len = s.len(); + if !(MIN_LEN..=MAX_LEN).contains(&len) { + return allocate_string(s, heap.heap()); + } + + let inner = self.inner.get_or_insert_with(CacheInner::new); + inner.get_or_allocate(s, heap) + } + + /// Drops all cached values, decrementing their refcounts. + /// + /// Called during `VM::drop()` before the heap is torn down. + pub fn drop_all(&mut self, heap: &mut impl ContainsHeap) { + if let Some(inner) = &mut self.inner { + for entry in &mut *inner.entries { + if let Some((_, _, value)) = entry.take() { + value.drop_with(heap); + } + } + } + } +} + +impl CacheInner { + /// Creates a new cache with zeroed entries. + /// + /// Uses `iter::repeat_with().collect()` to avoid allocating the large array + /// on the stack (see jiter PR #239). + fn new() -> Self { + Self { + entries: iter::repeat_with(|| None) + .take(CAPACITY) + .collect::>() + .into_boxed_slice() + .try_into() + .expect("Vec length equals CAPACITY"), + hash_builder: RandomState::default(), + } + } + + /// Looks up `s` in the cache. On hit, returns a cloned `Value`. On miss, + /// allocates on the heap and inserts into the cache. + fn get_or_allocate(&mut self, s: String, heap: &HeapReader<'_>) -> Value { + let hash = self.hash_builder.hash_one(s.as_str()); + // Truncation is intentional — we only need the low bits for indexing. + #[expect(clippy::cast_possible_truncation)] + let primary = hash as usize & (CAPACITY - 1); + + // Linear probe up to 5 contiguous slots, wrapping around the table end. + for offset in 0..5 { + let index = (primary + offset) & (CAPACITY - 1); + let entry = &mut self.entries[index]; + match entry { + Some((entry_hash, cached_str, cached_value)) => { + if *entry_hash == hash && **cached_str == *s { + return cached_value.clone_with_heap(heap); + } + } + None => { + // Empty slot — allocate and insert. + return self.insert_at(index, hash, s, heap); + } + } + } + // All 5 probe slots occupied — allocate without caching. + // Length is in [MIN_LEN..=MAX_LEN] here so interning would never apply. + allocate_string_no_interning(s, heap.heap()) + } + + /// Allocates `s` on the heap, stores a clone in `entries[index]`, and + /// returns the original `Value`. + fn insert_at(&mut self, index: usize, hash: u64, s: String, heap: &HeapReader<'_>) -> Value { + let key = s.clone().into_boxed_str(); + // Length is in [MIN_LEN..=MAX_LEN] here so interning would never apply. + let value = allocate_string_no_interning(s, heap.heap()); + let cached = value.clone_with_heap(heap); + self.entries[index] = Some((hash, key, cached)); + value + } +} diff --git a/crates/bashkit-monty/src/modules/math.rs b/crates/bashkit-monty/src/modules/math.rs new file mode 100644 index 000000000..3593ab426 --- /dev/null +++ b/crates/bashkit-monty/src/modules/math.rs @@ -0,0 +1,1442 @@ +//! Implementation of Python's `math` module. +//! +//! Provides mathematical functions and constants matching CPython 3.14 behavior +//! and error messages. All functions are pure computations that don't require +//! host involvement, so they return `Value` directly rather than `CallResult`. +//! +//! ## Implemented functions +//! +//! **Rounding**: `floor`, `ceil`, `trunc` +//! **Roots & powers**: `sqrt`, `isqrt`, `cbrt`, `pow`, `exp`, `exp2`, `expm1` +//! **Logarithms**: `log`, `log2`, `log10`, `log1p` +//! **Trigonometric**: `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2` +//! **Hyperbolic**: `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh` +//! **Angular**: `degrees`, `radians` +//! **Float properties**: `fabs`, `isnan`, `isinf`, `isfinite`, `copysign`, `isclose`, +//! `nextafter`, `ulp` +//! **Integer math**: `factorial`, `gcd`, `lcm`, `comb`, `perm` +//! **Modular**: `fmod`, `remainder`, `modf`, `frexp`, `ldexp` +//! **Special**: `gamma`, `lgamma`, `erf`, `erfc` +//! **Summation & products**: `hypot`, `dist`, `fsum`, `prod`, `sumprod`, `fma` +//! +//! ## Constants +//! +//! `pi`, `e`, `tau`, `inf`, `nan` + +use std::f64::consts; + +use monty_types::ResourceTracker; +use num_bigint::BigInt; +use num_integer::Integer; +use num_traits::{One, Signed, ToPrimitive, Zero}; +use smallvec::smallvec; + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{HeapData, HeapId}, + intern::StaticStrings, + modules::ModuleFunctions, + resource_checks::{check_mult_size, check_product_size}, + types::{LongInt, Module, PyTrait, allocate_tuple, decimal, long_int::bigint_to_f64_checked}, + value::Value, +}; + +mod aggregate; + +// ========================== +// Shared constants and error helpers +// ========================== + +/// Returns a `ValueError` with the standard CPython "math domain error" message. +fn math_domain_error() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "math domain error").into() +} + +/// Returns an `OverflowError` with the standard CPython "math range error" message. +fn math_range_error() -> RunError { + ExcType::overflow_math_range() +} + +/// Checks whether a computation overflowed (finite input produced infinite result). +/// +/// Returns `Err(OverflowError("math range error"))` if `result` is infinite +/// but `input` was finite. +fn check_range_error(result: f64, input: f64) -> RunResult<()> { + if result.is_infinite() && input.is_finite() { + Err(math_range_error()) + } else { + Ok(()) + } +} + +/// Checks that a value is in the `[-1, 1]` range, raising `ValueError` if not. +/// +/// NaN passes through (it will propagate through the subsequent math operation). +/// Used by `math.asin` and `math.acos`. +fn require_unit_range(f: f64) -> RunResult<()> { + if !f.is_nan() && !(-1.0..=1.0).contains(&f) { + Err(SimpleException::new_msg( + ExcType::ValueError, + format!("expected a number in range from -1 up to 1, got {f:?}"), + ) + .into()) + } else { + Ok(()) + } +} + +/// Checks for non-positive integer arguments (poles of the Gamma function). +/// +/// These are the finite non-positive integers where Gamma diverges to ±∞. +/// Does NOT reject `-inf` — callers that need to reject it (like `math.gamma`) +/// must do so separately, since `lgamma(-inf)` is valid and returns `inf`. +#[expect( + clippy::float_cmp, + reason = "exact comparison detects integer poles of gamma function" +)] +fn check_gamma_pole(f: f64) -> RunResult<()> { + if f <= 0.0 && f == f.floor() && f.is_finite() { + Err(SimpleException::new_msg( + ExcType::ValueError, + format!("expected a noninteger or positive integer, got {f:?}"), + ) + .into()) + } else { + Ok(()) + } +} + +/// Math module functions — each variant corresponds to a Python-visible function. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "lowercase")] +pub(crate) enum MathFunctions { + // Rounding + Floor, + Ceil, + Trunc, + // Roots & powers + Sqrt, + Isqrt, + Cbrt, + Pow, + Exp, + Exp2, + Expm1, + // Logarithms + Log, + Log1p, + Log2, + Log10, + // Float properties + Fabs, + Isnan, + Isinf, + Isfinite, + Copysign, + Isclose, + Nextafter, + Ulp, + // Trigonometric + Sin, + Cos, + Tan, + Asin, + Acos, + Atan, + Atan2, + // Hyperbolic + Sinh, + Cosh, + Tanh, + Asinh, + Acosh, + Atanh, + // Angular conversion + Degrees, + Radians, + // Integer math + Factorial, + Gcd, + Lcm, + Comb, + Perm, + // Modular / decomposition + Fmod, + Remainder, + Modf, + Frexp, + Ldexp, + // Special functions + Gamma, + Lgamma, + Erf, + Erfc, + // Summation and products (append to preserve serialized variant indices). + Hypot, + Dist, + Fsum, + Prod, + Sumprod, + Fma, +} + +/// Creates the `math` module and allocates it on the heap. +/// +/// Registers all math functions and constants (`pi`, `e`, `tau`, `inf`, `nan`) +/// matching CPython's `math` module. Functions are registered as +/// `ModuleFunctions::Math` variants. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Math, vm.interns); + + // Register all math functions + for (name, func) in MATH_FUNCTIONS { + module.set_attr(*name, Value::ModuleFunction(ModuleFunctions::Math(*func)), vm); + } + + // Constants + module.set_attr(StaticStrings::Pi, Value::Float(consts::PI), vm); + module.set_attr(StaticStrings::AsciiLowerE, Value::Float(consts::E), vm); + module.set_attr(StaticStrings::Tau, Value::Float(consts::TAU), vm); + module.set_attr(StaticStrings::MathInf, Value::Float(f64::INFINITY), vm); + module.set_attr(StaticStrings::MathNan, Value::Float(f64::NAN), vm); + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Static mapping of attribute names to math functions for module creation. +const MATH_FUNCTIONS: &[(StaticStrings, MathFunctions)] = &[ + // Rounding + (StaticStrings::Floor, MathFunctions::Floor), + (StaticStrings::Ceil, MathFunctions::Ceil), + (StaticStrings::Trunc, MathFunctions::Trunc), + // Roots & powers + (StaticStrings::Sqrt, MathFunctions::Sqrt), + (StaticStrings::Isqrt, MathFunctions::Isqrt), + (StaticStrings::Cbrt, MathFunctions::Cbrt), + (StaticStrings::Pow, MathFunctions::Pow), + (StaticStrings::Exp, MathFunctions::Exp), + (StaticStrings::Exp2, MathFunctions::Exp2), + (StaticStrings::Expm1, MathFunctions::Expm1), + // Logarithms + (StaticStrings::Log, MathFunctions::Log), + (StaticStrings::Log1p, MathFunctions::Log1p), + (StaticStrings::Log2, MathFunctions::Log2), + (StaticStrings::Log10, MathFunctions::Log10), + // Float properties + (StaticStrings::Fabs, MathFunctions::Fabs), + (StaticStrings::Isnan, MathFunctions::Isnan), + (StaticStrings::Isinf, MathFunctions::Isinf), + (StaticStrings::Isfinite, MathFunctions::Isfinite), + (StaticStrings::Copysign, MathFunctions::Copysign), + (StaticStrings::Isclose, MathFunctions::Isclose), + (StaticStrings::Nextafter, MathFunctions::Nextafter), + (StaticStrings::Ulp, MathFunctions::Ulp), + // Trigonometric + (StaticStrings::Sin, MathFunctions::Sin), + (StaticStrings::Cos, MathFunctions::Cos), + (StaticStrings::Tan, MathFunctions::Tan), + (StaticStrings::Asin, MathFunctions::Asin), + (StaticStrings::Acos, MathFunctions::Acos), + (StaticStrings::Atan, MathFunctions::Atan), + (StaticStrings::Atan2, MathFunctions::Atan2), + // Hyperbolic + (StaticStrings::Sinh, MathFunctions::Sinh), + (StaticStrings::Cosh, MathFunctions::Cosh), + (StaticStrings::Tanh, MathFunctions::Tanh), + (StaticStrings::Asinh, MathFunctions::Asinh), + (StaticStrings::Acosh, MathFunctions::Acosh), + (StaticStrings::Atanh, MathFunctions::Atanh), + // Angular conversion + (StaticStrings::Degrees, MathFunctions::Degrees), + (StaticStrings::Radians, MathFunctions::Radians), + // Integer math + (StaticStrings::Factorial, MathFunctions::Factorial), + (StaticStrings::Gcd, MathFunctions::Gcd), + (StaticStrings::Lcm, MathFunctions::Lcm), + (StaticStrings::Comb, MathFunctions::Comb), + (StaticStrings::Perm, MathFunctions::Perm), + // Modular / decomposition + (StaticStrings::Fmod, MathFunctions::Fmod), + (StaticStrings::Remainder, MathFunctions::Remainder), + (StaticStrings::Modf, MathFunctions::Modf), + (StaticStrings::Frexp, MathFunctions::Frexp), + (StaticStrings::Ldexp, MathFunctions::Ldexp), + // Special functions + (StaticStrings::Gamma, MathFunctions::Gamma), + (StaticStrings::Lgamma, MathFunctions::Lgamma), + (StaticStrings::Erf, MathFunctions::Erf), + (StaticStrings::Erfc, MathFunctions::Erfc), + // Summation and products + (StaticStrings::Hypot, MathFunctions::Hypot), + (StaticStrings::Dist, MathFunctions::Dist), + (StaticStrings::Fsum, MathFunctions::Fsum), + (StaticStrings::Prod, MathFunctions::Prod), + (StaticStrings::Sumprod, MathFunctions::Sumprod), + (StaticStrings::Fma, MathFunctions::Fma), +]; + +/// Dispatches a call to a math module function. +/// +/// All math functions are pure computations and return `Value` directly. +pub(super) fn call(vm: &mut VM<'_>, function: MathFunctions, args: ArgValues) -> RunResult { + match function { + // Rounding + MathFunctions::Floor => math_floor(vm, args), + MathFunctions::Ceil => math_ceil(vm, args), + MathFunctions::Trunc => math_trunc(vm, args), + // Roots & powers + MathFunctions::Sqrt => math_sqrt(vm, args), + MathFunctions::Isqrt => math_isqrt(vm, args), + MathFunctions::Cbrt => math_cbrt(vm, args), + MathFunctions::Pow => math_pow(vm, args), + MathFunctions::Exp => math_exp(vm, args), + MathFunctions::Exp2 => math_exp2(vm, args), + MathFunctions::Expm1 => math_expm1(vm, args), + // Logarithms + MathFunctions::Log => math_log(vm, args), + MathFunctions::Log1p => math_log1p(vm, args), + MathFunctions::Log2 => math_log2(vm, args), + MathFunctions::Log10 => math_log10(vm, args), + // Float properties + MathFunctions::Fabs => math_fabs(vm, args), + MathFunctions::Isnan => math_isnan(vm, args), + MathFunctions::Isinf => math_isinf(vm, args), + MathFunctions::Isfinite => math_isfinite(vm, args), + MathFunctions::Copysign => math_copysign(vm, args), + MathFunctions::Isclose => math_isclose(vm, args), + MathFunctions::Nextafter => math_nextafter(vm, args), + MathFunctions::Ulp => math_ulp(vm, args), + // Trigonometric + MathFunctions::Sin => math_sin(vm, args), + MathFunctions::Cos => math_cos(vm, args), + MathFunctions::Tan => math_tan(vm, args), + MathFunctions::Asin => math_asin(vm, args), + MathFunctions::Acos => math_acos(vm, args), + MathFunctions::Atan => math_atan(vm, args), + MathFunctions::Atan2 => math_atan2(vm, args), + // Hyperbolic + MathFunctions::Sinh => math_sinh(vm, args), + MathFunctions::Cosh => math_cosh(vm, args), + MathFunctions::Tanh => math_tanh(vm, args), + MathFunctions::Asinh => math_asinh(vm, args), + MathFunctions::Acosh => math_acosh(vm, args), + MathFunctions::Atanh => math_atanh(vm, args), + // Angular conversion + MathFunctions::Degrees => math_degrees(vm, args), + MathFunctions::Radians => math_radians(vm, args), + // Integer math + MathFunctions::Factorial => math_factorial(vm, args), + MathFunctions::Gcd => math_gcd(vm, args), + MathFunctions::Lcm => math_lcm(vm, args), + MathFunctions::Comb => math_comb(vm, args), + MathFunctions::Perm => math_perm(vm, args), + // Modular / decomposition + MathFunctions::Fmod => math_fmod(vm, args), + MathFunctions::Remainder => math_remainder(vm, args), + MathFunctions::Modf => math_modf(vm, args), + MathFunctions::Frexp => math_frexp(vm, args), + MathFunctions::Ldexp => math_ldexp(vm, args), + // Special functions + MathFunctions::Gamma => math_gamma(vm, args), + MathFunctions::Lgamma => math_lgamma(vm, args), + MathFunctions::Erf => math_erf(vm, args), + MathFunctions::Erfc => math_erfc(vm, args), + MathFunctions::Hypot => aggregate::hypot(vm, args), + MathFunctions::Dist => aggregate::dist(vm, args), + MathFunctions::Fsum => aggregate::fsum(vm, args), + MathFunctions::Prod => aggregate::prod(vm, args), + MathFunctions::Sumprod => aggregate::sumprod(vm, args), + MathFunctions::Fma => aggregate::fma(vm, args), + } +} + +// ========================== +// Rounding functions +// ========================== + +/// `math.floor(x)` — returns the largest integer less than or equal to x. +/// +/// Uses `__floor__`, falling back to numeric float conversion. +/// Raises `OverflowError` for infinity, `ValueError` for NaN. +fn math_floor(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.floor", vm.heap)?; + defer_drop!(value, vm); + + if let Some(result) = value.py_floor_impl(vm)? { + Ok(result) + } else { + let number = rounding_float(value, vm)?; + LongInt::value_from_f64(number.floor(), vm.heap) + } +} + +/// `math.ceil(x)` — returns the smallest integer greater than or equal to x. +/// +/// Uses `__ceil__`, falling back to numeric float conversion. +/// Raises `OverflowError` for infinity, `ValueError` for NaN. +fn math_ceil(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.ceil", vm.heap)?; + defer_drop!(value, vm); + + if let Some(result) = value.py_ceil_impl(vm)? { + Ok(result) + } else { + let number = rounding_float(value, vm)?; + LongInt::value_from_f64(number.ceil(), vm.heap) + } +} + +/// `math.trunc(x)` — truncates x to the nearest integer toward zero. +/// +/// Uses `__trunc__` without falling back to integer or float conversion. +fn math_trunc(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.trunc", vm.heap)?; + defer_drop!(value, vm); + + value + .py_trunc_impl(vm)? + .ok_or_else(|| ExcType::type_error_missing_numeric_dunder(&value.py_type_name(vm), "__trunc__")) +} + +/// Float fallback for floor and ceil, excluding the string parsing of `float()`. +fn rounding_float(value: &Value, vm: &mut VM<'_>) -> RunResult { + value + .py_float(vm)? + .ok_or_else(|| ExcType::type_error_not_real_number(&value.py_type_name(vm))) +} + +// ========================== +// Roots & powers +// ========================== + +/// `math.sqrt(x)` — returns the square root of x. +/// +/// Always returns a float. Raises `ValueError` for negative inputs with a +/// descriptive message matching CPython 3.14: "expected a nonnegative input, got ". +fn math_sqrt(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.sqrt", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + if f < 0.0 { + Err(SimpleException::new_msg(ExcType::ValueError, format!("expected a nonnegative input, got {f:?}")).into()) + } else { + Ok(Value::Float(f.sqrt())) + } +} + +/// `math.isqrt(n)` — returns the integer square root of a non-negative integer. +/// +/// Returns the largest integer `r` such that `r * r <= n`. +/// Only accepts non-negative integers (and bools). +fn math_isqrt(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.isqrt", vm.heap)?; + defer_drop!(value, vm); + + let n = value_to_bigint(value, vm)?; + if n.is_negative() { + Err(SimpleException::new_msg(ExcType::ValueError, "isqrt() argument must be nonnegative").into()) + } else if let Some(n) = n.to_i64() { + Ok(Value::Int(isqrt_i64(n))) + } else { + Ok(LongInt::new(BigInt::from(n.magnitude().sqrt())).into_value(vm.heap)) + } +} + +/// Integer square root of a non-negative machine integer. +fn isqrt_i64(n: i64) -> i64 { + if n == 0 { + return 0; + } + // Integer square root via f64 estimate + correction. + // For i64 inputs, f64 sqrt is accurate to within ±1, so we need to + // correct both overshoot and undershoot. The cast truncates toward zero, + // so undershoot is possible for perfect squares near f64 precision limits. + #[expect( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + reason = "initial estimate doesn't need to be exact, correction refines it" + )] + let mut x = (n as f64).sqrt() as i64; + // Correct overshoot: use `x > n / x` instead of `x * x > n` to avoid i64 overflow. + while x > n / x { + x -= 1; + } + // Correct undershoot: check if (x+1)² ≤ n using division to avoid overflow. + while x < n / (x + 1) { + x += 1; + } + x +} + +/// `math.cbrt(x)` — returns the cube root of x. +/// +/// Always returns a float. Unlike `sqrt`, works for negative inputs. +fn math_cbrt(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.cbrt", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Float(f.cbrt())) +} + +/// `math.pow(x, y)` — returns x raised to the power y. +/// +/// Always returns a float. Unlike the builtin `pow()`, does not support +/// three-argument modular exponentiation. Raises `ValueError` for +/// negative base with non-integer exponent. +fn math_pow(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (x_val, y_val) = args.get_two_args("math.pow", vm.heap)?; + defer_drop!(x_val, vm); + defer_drop!(y_val, vm); + + let x = value_to_float(x_val, vm)?; + let y = value_to_float(y_val, vm)?; + let result = x.powf(y); + // CPython raises ValueError for domain errors: 0**negative, negative**non-integer + if result.is_nan() && !x.is_nan() && !y.is_nan() { + return Err(math_domain_error()); + } + if result.is_infinite() && x.is_finite() && y.is_finite() { + // 0**negative is a domain error (ValueError), not overflow + if x == 0.0 && y < 0.0 { + return Err(math_domain_error()); + } + return Err(math_range_error()); + } + Ok(Value::Float(result)) +} + +/// `math.exp(x)` — returns e raised to the power x. +fn math_exp(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.exp", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + let result = f.exp(); + check_range_error(result, f)?; + Ok(Value::Float(result)) +} + +/// `math.exp2(x)` — returns 2 raised to the power x. +fn math_exp2(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.exp2", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + let result = f.exp2(); + check_range_error(result, f)?; + Ok(Value::Float(result)) +} + +/// `math.expm1(x)` — returns e**x - 1. +/// +/// More accurate than `exp(x) - 1` for small values of x. +fn math_expm1(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.expm1", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + let result = f.exp_m1(); + check_range_error(result, f)?; + Ok(Value::Float(result)) +} + +// ========================== +// Logarithms +// ========================== + +/// `math.log(x[, base])` — returns the logarithm of x. +/// +/// With one argument, returns the natural logarithm (base e). +/// With two arguments, returns `log(x) / log(base)`. +fn math_log(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + // CPython's arity errors name the bare function: `log expected at most 2 arguments, got 3`. + let (x_val, base_val) = args.get_one_two_args("log", vm.heap)?; + defer_drop!(x_val, vm); + defer_drop!(base_val, vm); + + let numerator = log_arg(x_val, f64::ln, vm)?; + match base_val { + Some(base_v) => { + // `log(1) == 0.0`, so a base of 1 divides by zero as in CPython. + let denominator = log_arg(base_v, f64::ln, vm)?; + if denominator == 0.0 { + Err(ExcType::zero_division().into()) + } else { + Ok(Value::Float(numerator / denominator)) + } + } + None => Ok(Value::Float(numerator)), + } +} + +/// Applies a logarithm to a `math` argument, after CPython's `loghelper`. +/// +/// An int beyond the float range is split as `m * 2**e` with `m` in `[0.5, 1)`, so +/// `math.log(10**400)` works where `float(10**400)` overflows. Non-positive inputs +/// raise `ValueError`; only the float message names the offending value. +#[expect(clippy::cast_precision_loss, reason = "the exponent is a bit count, far below 2**53")] +fn log_arg(value: &Value, log: fn(f64) -> f64, vm: &VM<'_>) -> RunResult { + let positive_input_error = || SimpleException::new_msg(ExcType::ValueError, "expected a positive input").into(); + match value { + Value::Int(n) if *n <= 0 => Err(positive_input_error()), + Value::Int(n) => Ok(log(*n as f64)), + Value::Bool(true) => Ok(log(1.0)), + Value::Bool(false) => Err(positive_input_error()), + _ => match value.as_long_int(vm) { + // A long int is never zero. + Some(n) if n.is_negative() => Err(positive_input_error()), + Some(n) => Ok(if let Some(x) = n.to_f64().filter(|x| x.is_finite()) { + log(x) + } else { + let (mantissa, exponent) = bigint_frexp(n); + log(mantissa) + log(2.0) * exponent as f64 + }), + None => { + let x = value_to_float(value, vm)?; + if x <= 0.0 { + Err( + SimpleException::new_msg(ExcType::ValueError, format!("expected a positive input, got {x:?}")) + .into(), + ) + } else { + Ok(log(x)) + } + } + }, + } +} + +/// Splits a positive integer into `m * 2**e` with `m` in `[0.5, 1)`, after `_PyLong_Frexp`. +/// +/// `m` carries the integer's top bits correctly rounded to a float (a sticky bit stands in +/// for everything below the top 64), so it is exact where `to_f64` would overflow. +#[expect( + clippy::cast_precision_loss, + reason = "rounding the top 64 bits to a float is the point" +)] +fn bigint_frexp(n: &BigInt) -> (f64, i64) { + let bits = n.bits(); + let shift = bits.saturating_sub(64); + let mut top = (n.magnitude() >> shift).to_u64().unwrap_or(u64::MAX); + // Any set bit below the top 64 breaks a rounding tie upward, as the full value would. + if n.trailing_zeros().unwrap_or(0) < shift { + top |= 1; + } + let mantissa = libm::ldexp(top as f64, -64); + let exponent = i64::try_from(bits).unwrap_or(i64::MAX); + // Rounding can carry the mantissa up to 1.0; renormalise as CPython does. + if mantissa >= 1.0 { + (0.5, exponent + 1) + } else { + (mantissa, exponent) + } +} + +/// `math.log1p(x)` — returns the natural logarithm of 1 + x. +/// +/// More accurate than `log(1 + x)` for small values of x. +/// CPython 3.14 raises ValueError with "expected argument value > -1, got ". +fn math_log1p(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.log1p", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + if f <= -1.0 { + return Err( + SimpleException::new_msg(ExcType::ValueError, format!("expected argument value > -1, got {f:?}")).into(), + ); + } + Ok(Value::Float(f.ln_1p())) +} + +/// `math.log2(x)` — returns the base-2 logarithm of x. +/// +/// Returns `inf` for positive infinity, `nan` for NaN. +/// Raises `ValueError` for non-positive finite inputs. +fn math_log2(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.log2", vm.heap)?; + defer_drop!(value, vm); + + Ok(Value::Float(log_arg(value, f64::log2, vm)?)) +} + +/// `math.log10(x)` — returns the base-10 logarithm of x. +/// +/// Returns `inf` for positive infinity, `nan` for NaN. +/// Raises `ValueError` for non-positive finite inputs. +fn math_log10(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.log10", vm.heap)?; + defer_drop!(value, vm); + + Ok(Value::Float(log_arg(value, f64::log10, vm)?)) +} + +// ========================== +// Float properties +// ========================== + +/// `math.fabs(x)` — returns the absolute value as a float. +/// +/// Unlike the builtin `abs()`, always returns a float. +fn math_fabs(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.fabs", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Float(f.abs())) +} + +/// `math.isnan(x)` — returns True if x is NaN. +fn math_isnan(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.isnan", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Bool(f.is_nan())) +} + +/// `math.isinf(x)` — returns True if x is positive or negative infinity. +fn math_isinf(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.isinf", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Bool(f.is_infinite())) +} + +/// `math.isfinite(x)` — returns True if x is neither infinity nor NaN. +fn math_isfinite(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.isfinite", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Bool(f.is_finite())) +} + +/// `math.copysign(x, y)` — returns x with the sign of y. +/// +/// Always returns a float. +fn math_copysign(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (x_val, y_val) = args.get_two_args("math.copysign", vm.heap)?; + defer_drop!(x_val, vm); + defer_drop!(y_val, vm); + + let x = value_to_float(x_val, vm)?; + let y = value_to_float(y_val, vm)?; + Ok(Value::Float(x.copysign(y))) +} + +/// `math.isclose(a, b, *, rel_tol=1e-9, abs_tol=0.0)` — returns True if a and b are close. +/// +/// Supports keyword-only `rel_tol` and `abs_tol` parameters matching CPython. +/// Raises `ValueError` if either tolerance is negative. +fn math_isclose(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let IscloseArgs { a, b, rel_tol, abs_tol } = IscloseArgs::from_args(args, vm)?; + defer_drop!(a, vm); + defer_drop!(b, vm); + defer_drop!(rel_tol, vm); + defer_drop!(abs_tol, vm); + + let a = value_to_float(a, vm)?; + let b = value_to_float(b, vm)?; + let rel_tol = value_to_float(rel_tol, vm)?; + let abs_tol = value_to_float(abs_tol, vm)?; + + if rel_tol < 0.0 || abs_tol < 0.0 { + return Err(SimpleException::new_msg(ExcType::ValueError, "tolerances must be non-negative").into()); + } + + // Exact equality check matches CPython's isclose() behavior — two identical + // values (including infinities) are always considered close. + #[expect( + clippy::float_cmp, + reason = "exact equality check matches CPython's isclose() semantics" + )] + if a == b { + return Ok(Value::Bool(true)); + } + if a.is_infinite() || b.is_infinite() { + return Ok(Value::Bool(false)); + } + if a.is_nan() || b.is_nan() { + return Ok(Value::Bool(false)); + } + + let diff = (a - b).abs(); + let result = diff <= (rel_tol * a.abs().max(b.abs())).max(abs_tol); + Ok(Value::Bool(result)) +} + +/// Argument shape for `math.isclose(a, b, *, rel_tol=1e-9, abs_tol=0.0)`. +/// +/// `a`/`b` are positional-or-keyword (matching CPython); `rel_tol`/`abs_tol` +/// are keyword-only. All four are held as raw `Value` so the function body can +/// run `value_to_float` for the math-specific Int/Float coercion (which +/// `bool::from_value` and `i64::from_value` don't cover). +#[derive(FromArgs)] +#[from_args(name = "isclose")] +struct IscloseArgs { + a: Value, + b: Value, + #[from_args(kw_only, default = Value::Float(1e-9))] + rel_tol: Value, + #[from_args(kw_only, default = Value::Float(0.0))] + abs_tol: Value, +} + +/// `math.nextafter(x, y)` — returns the next float after x towards y. +fn math_nextafter(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (x_val, y_val) = args.get_two_args("math.nextafter", vm.heap)?; + defer_drop!(x_val, vm); + defer_drop!(y_val, vm); + + let x = value_to_float(x_val, vm)?; + let y = value_to_float(y_val, vm)?; + + Ok(Value::Float(libm::nextafter(x, y))) +} + +/// `math.ulp(x)` — returns the value of the least significant bit of x. +/// +/// For finite non-zero x, returns the smallest float `u` such that `x + u != x`. +/// Special cases: `ulp(nan)` returns nan, `ulp(inf)` returns inf. +fn math_ulp(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.ulp", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + if f.is_nan() { + return Ok(Value::Float(f64::NAN)); + } + if f.is_infinite() { + return Ok(Value::Float(f64::INFINITY)); + } + let f = f.abs(); + if f == 0.0 { + // CPython returns the smallest positive subnormal: 5e-324 + return Ok(Value::Float(f64::from_bits(1))); + } + // ULP = nextafter(f, inf) - f + let next = libm::nextafter(f, f64::INFINITY); + Ok(Value::Float(next - f)) +} + +// ========================== +// Trigonometric functions +// ========================== + +/// `math.sin(x)` — returns the sine of x (in radians). +/// +/// CPython 3.14 raises ValueError for infinity: "expected a finite input, got inf". +fn math_sin(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.sin", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + require_finite(f)?; + Ok(Value::Float(f.sin())) +} + +/// `math.cos(x)` — returns the cosine of x (in radians). +fn math_cos(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.cos", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + require_finite(f)?; + Ok(Value::Float(f.cos())) +} + +/// `math.tan(x)` — returns the tangent of x (in radians). +fn math_tan(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.tan", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + require_finite(f)?; + Ok(Value::Float(f.tan())) +} + +/// `math.asin(x)` — returns the arc sine of x (in radians). +/// +/// CPython 3.14: "expected a number in range from -1 up to 1, got ". +fn math_asin(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.asin", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + require_unit_range(f)?; + Ok(Value::Float(f.asin())) +} + +/// `math.acos(x)` — returns the arc cosine of x (in radians). +/// +/// CPython 3.14: "expected a number in range from -1 up to 1, got ". +fn math_acos(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.acos", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + require_unit_range(f)?; + Ok(Value::Float(f.acos())) +} + +/// `math.atan(x)` — returns the arc tangent of x (in radians). +fn math_atan(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.atan", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Float(f.atan())) +} + +/// `math.atan2(y, x)` — returns atan(y/x) in radians, using the signs of both +/// to determine the correct quadrant. +fn math_atan2(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (y_val, x_val) = args.get_two_args("math.atan2", vm.heap)?; + defer_drop!(y_val, vm); + defer_drop!(x_val, vm); + + let y = value_to_float(y_val, vm)?; + let x = value_to_float(x_val, vm)?; + Ok(Value::Float(y.atan2(x))) +} + +// ========================== +// Hyperbolic functions +// ========================== + +/// `math.sinh(x)` — returns the hyperbolic sine of x. +fn math_sinh(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.sinh", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + let result = f.sinh(); + check_range_error(result, f)?; + Ok(Value::Float(result)) +} + +/// `math.cosh(x)` — returns the hyperbolic cosine of x. +fn math_cosh(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.cosh", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + let result = f.cosh(); + check_range_error(result, f)?; + Ok(Value::Float(result)) +} + +/// `math.tanh(x)` — returns the hyperbolic tangent of x. +fn math_tanh(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.tanh", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Float(f.tanh())) +} + +/// `math.asinh(x)` — returns the inverse hyperbolic sine of x. +fn math_asinh(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.asinh", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Float(f.asinh())) +} + +/// `math.acosh(x)` — returns the inverse hyperbolic cosine of x. +/// +/// CPython 3.14: "expected argument value not less than 1, got ". +fn math_acosh(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.acosh", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + if f < 1.0 { + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("expected argument value not less than 1, got {f:?}"), + ) + .into()); + } + Ok(Value::Float(f.acosh())) +} + +/// `math.atanh(x)` — returns the inverse hyperbolic tangent of x. +/// +/// CPython 3.14: "expected a number between -1 and 1, got ". +fn math_atanh(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.atanh", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + if f <= -1.0 || f >= 1.0 { + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("expected a number between -1 and 1, got {f:?}"), + ) + .into()); + } + Ok(Value::Float(f.atanh())) +} + +// ========================== +// Angular conversion +// ========================== + +/// `math.degrees(x)` — converts angle x from radians to degrees. +fn math_degrees(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.degrees", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Float(f.to_degrees())) +} + +/// `math.radians(x)` — converts angle x from degrees to radians. +fn math_radians(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.radians", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Float(f.to_radians())) +} + +// ========================== +// Integer math +// ========================== + +/// `math.factorial(n)` — returns n factorial. +/// +/// Only accepts non-negative integers (and bools). Raises `ValueError` for +/// negative values, `TypeError` for non-integer types. +fn math_factorial(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.factorial", vm.heap)?; + defer_drop!(value, vm); + + let n = value_to_bigint(value, vm)?; + Ok(LongInt::new(factorial(&n, &vm.heap.tracker)?).into_value(vm.heap)) +} + +/// `n!` with CPython's argument errors, shared by `factorial` and one-argument `perm`. +fn factorial(n: &BigInt, tracker: &ResourceTracker) -> RunResult { + if n.is_negative() { + return Err( + SimpleException::new_msg(ExcType::ValueError, "factorial() not defined for negative values").into(), + ); + } + let Some(n) = n.to_i64() else { + return Err(SimpleException::new_msg( + ExcType::OverflowError, + "factorial() argument should not exceed 9223372036854775807", + ) + .into()); + }; + let n = n.unsigned_abs(); + // `n!` has fewer than `n * bits(n)` bits. + check_product_size(n.saturating_mul(u64::from(u64::BITS - n.leading_zeros())), tracker)?; + product_range(2, n, &mut 0, tracker) +} + +/// Multiplies `lo..=hi` by binary splitting, so a big factorial combines factors of +/// similar size rather than one at a time against a growing product. +fn product_range(lo: u64, hi: u64, polls: &mut usize, tracker: &ResourceTracker) -> RunResult { + if lo > hi { + Ok(BigInt::one()) + } else if hi - lo < 32 { + // Nothing here returns to the VM's dispatch checkpoint, so the loop polls the clock itself. + tracker.check_time_every(*polls)?; + *polls += 1; + Ok((lo..=hi).fold(BigInt::one(), |product, i| product * i)) + } else { + let mid = lo + (hi - lo) / 2; + let (low, high) = ( + product_range(lo, mid, polls, tracker)?, + product_range(mid + 1, hi, polls, tracker)?, + ); + // Combining two halves is where the expensive multiplications are, so each one polls. + tracker.check_time()?; + Ok(low * high) + } +} + +/// `math.gcd(*integers)` — returns the greatest common divisor of the arguments. +/// +/// Supports 0 or more arguments, matching CPython 3.9+. `gcd()` returns 0, +/// `gcd(n)` returns `abs(n)`, and for multiple args reduces pairwise. +/// The result is always non-negative. +fn math_gcd(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let positional = args.into_pos_only("math.gcd", vm.heap)?; + defer_drop_mut!(positional, vm); + + let mut result = BigInt::ZERO; + for arg in positional.by_ref() { + defer_drop!(arg, vm); + result = result.gcd(&value_to_bigint(arg, vm)?); + } + Ok(LongInt::new(result).into_value(vm.heap)) +} + +/// `math.lcm(*integers)` — returns the least common multiple of the arguments. +/// +/// Supports 0 or more arguments, matching CPython 3.9+. `lcm()` returns 1, +/// `lcm(n)` returns `abs(n)`, and for multiple args reduces pairwise. +/// The result is always non-negative. Returns 0 if any argument is 0. +fn math_lcm(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let positional = args.into_pos_only("math.lcm", vm.heap)?; + defer_drop_mut!(positional, vm); + + let mut result = BigInt::one(); + for arg in positional.by_ref() { + defer_drop!(arg, vm); + let n = value_to_bigint(arg, vm)?; + // A zero anywhere makes the result zero, but every argument is still type-checked. + if !result.is_zero() && !n.is_zero() { + // `lcm` divides out the gcd, holding a quotient up to `result`'s size, then + // multiplies: preflight both like `*`. + check_mult_size(result.bits().saturating_mul(2), n.bits(), &vm.heap.tracker)?; + result = result.lcm(&n); + } else { + result = BigInt::ZERO; + } + } + Ok(LongInt::new(result).into_value(vm.heap)) +} + +/// `math.comb(n, k)` — returns the number of ways to choose k items from n. +/// +/// Both arguments must be non-negative integers. +fn math_comb(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (n_val, k_val) = args.get_two_args("math.comb", vm.heap)?; + defer_drop!(n_val, vm); + defer_drop!(k_val, vm); + + let n = value_to_bigint(n_val, vm)?; + let k = value_to_bigint(k_val, vm)?; + + if n.is_negative() { + return Err(SimpleException::new_msg(ExcType::ValueError, "n must be a non-negative integer").into()); + } + if k.is_negative() { + return Err(SimpleException::new_msg(ExcType::ValueError, "k must be a non-negative integer").into()); + } + if k > n { + return Ok(Value::Int(0)); + } + + // C(n, k) == C(n, n - k): take the shorter product. + let n_minus_k = &n - &k; + let k = k.min(n_minus_k); + let Some(k) = k.to_i64() else { + return Err(SimpleException::new_msg( + ExcType::OverflowError, + "min(n - k, k) must not exceed 9223372036854775807", + ) + .into()); + }; + let result = falling_product(&n, k.unsigned_abs(), true, &vm.heap.tracker)?; + Ok(LongInt::new(result).into_value(vm.heap)) +} + +/// `n * (n - 1) * ... * (n - k + 1)`, the `k`-permutation count; with `binomial` each +/// step also divides by `i + 1`, so every partial product is the exact `C(n, i + 1)`. +fn falling_product(n: &BigInt, k: u64, binomial: bool, tracker: &ResourceTracker) -> RunResult { + // The product has fewer than `k * bits(n)` bits; a binomial is also below `2**n`. + let mut result_bits = k.saturating_mul(n.bits()); + if binomial && let Some(n) = n.to_u64() { + result_bits = result_bits.min(n); + } + check_product_size(result_bits, tracker)?; + let mut result = BigInt::one(); + for (polls, i) in (0..k).enumerate() { + // Nothing here returns to the VM's dispatch checkpoint, so the loop polls the clock itself. + tracker.check_time_every(polls)?; + result *= n - i; + if binomial { + result /= i + 1; + } + } + Ok(result) +} + +/// `math.perm(n, k=None)` — returns the number of k-length permutations from n items. +/// +/// Both arguments must be non-negative integers. When `k` is omitted, defaults to `n` +/// (i.e., `perm(n)` returns `n!`), matching CPython behavior. +fn math_perm(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + // CPython's arity errors name the bare function: `perm expected at most 2 arguments, got 3`. + let (n_val, k_val) = args.get_one_two_args("perm", vm.heap)?; + defer_drop!(n_val, vm); + + let n = value_to_bigint(n_val, vm)?; + // `perm(n)` is `n!`, argument errors included. + let Some(k_val) = k_val else { + return Ok(LongInt::new(factorial(&n, &vm.heap.tracker)?).into_value(vm.heap)); + }; + defer_drop!(k_val, vm); + let k = value_to_bigint(k_val, vm)?; + + if n.is_negative() { + return Err(SimpleException::new_msg(ExcType::ValueError, "n must be a non-negative integer").into()); + } + if k.is_negative() { + return Err(SimpleException::new_msg(ExcType::ValueError, "k must be a non-negative integer").into()); + } + if k > n { + return Ok(Value::Int(0)); + } + let Some(k) = k.to_i64() else { + return Err(SimpleException::new_msg(ExcType::OverflowError, "k must not exceed 9223372036854775807").into()); + }; + let result = falling_product(&n, k.unsigned_abs(), false, &vm.heap.tracker)?; + Ok(LongInt::new(result).into_value(vm.heap)) +} + +// ========================== +// Modular / decomposition +// ========================== + +/// `math.fmod(x, y)` — returns x modulo y as a float. +/// +/// Unlike `x % y`, the result has the same sign as x. Raises `ValueError` +/// when y is zero (CPython: "math domain error"). +fn math_fmod(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (x_val, y_val) = args.get_two_args("math.fmod", vm.heap)?; + defer_drop!(x_val, vm); + defer_drop!(y_val, vm); + + let x = value_to_float(x_val, vm)?; + let y = value_to_float(y_val, vm)?; + + if y == 0.0 || x.is_infinite() { + // CPython raises for both fmod(x, 0) and fmod(inf, y) + // but NaN inputs propagate + if !x.is_nan() && !y.is_nan() { + return Err(math_domain_error()); + } + } + Ok(Value::Float(x % y)) +} + +/// `math.remainder(x, y)` — IEEE 754 remainder of x with respect to y. +/// +/// The result is `x - n*y` where n is the closest integer to `x/y`. +fn math_remainder(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (x_val, y_val) = args.get_two_args("math.remainder", vm.heap)?; + defer_drop!(x_val, vm); + defer_drop!(y_val, vm); + + let x = value_to_float(x_val, vm)?; + let y = value_to_float(y_val, vm)?; + + // NaN propagates + if x.is_nan() || y.is_nan() { + return Ok(Value::Float(f64::NAN)); + } + if y == 0.0 { + return Err(math_domain_error()); + } + if x.is_infinite() { + return Err(math_domain_error()); + } + if y.is_infinite() { + return Ok(Value::Float(x)); + } + + Ok(Value::Float(libm::remainder(x, y))) +} + +/// `math.modf(x)` — returns the fractional and integer parts of x as a tuple. +/// +/// Both values carry the sign of x. Returns `(fractional, integer)`. +fn math_modf(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.modf", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + let (fractional, integer) = libm::modf(f); + let tuple = allocate_tuple(smallvec![Value::Float(fractional), Value::Float(integer)], vm.heap); + Ok(tuple) +} + +/// `math.frexp(x)` — returns (mantissa, exponent) such that `x == mantissa * 2**exponent`. +/// +/// The mantissa is always in the range [0.5, 1.0) or zero. +/// Returns a tuple `(float, int)`. +fn math_frexp(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.frexp", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + let (m, exp) = libm::frexp(f); + let tuple = allocate_tuple(smallvec![Value::Float(m), Value::Int(i64::from(exp))], vm.heap); + Ok(tuple) +} + +/// `math.ldexp(x, i)` — returns `x * 2**i`, the inverse of `frexp`. +/// +/// Clamps the exponent to `i32` range before calling `libm::ldexp`, which is safe +/// because IEEE 754 double exponents only span -1074 to +1023 — any `i64` outside +/// `i32` range would trivially overflow or underflow anyway. +fn math_ldexp(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (x_val, i_val) = args.get_two_args("math.ldexp", vm.heap)?; + defer_drop!(x_val, vm); + defer_drop!(i_val, vm); + + let x = value_to_float(x_val, vm)?; + // An exponent beyond `i64` saturates: the result overflows or underflows either way. + let i = match i_val { + Value::Int(i) => *i, + Value::Bool(b) => i64::from(*b), + _ => i_val + .long_int_to_i64_saturating(vm) + .ok_or_else(|| not_an_integer_error(i_val, vm))?, + }; + + // Special cases: inf/nan/zero pass through regardless of exponent + if x.is_nan() || x.is_infinite() || x == 0.0 { + return Ok(Value::Float(x)); + } + + // Clamp i64 to i32 range — exponents beyond ±2 billion trivially overflow/underflow + #[expect(clippy::cast_possible_truncation, reason = "clamped to i32 range first")] + let exp = i.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32; + let result = libm::ldexp(x, exp); + + // If the result overflowed to infinity, CPython raises OverflowError + if result.is_infinite() { + return Err(math_range_error()); + } + + Ok(Value::Float(result)) +} + +// ========================== +// Special functions +// ========================== + +/// `math.gamma(x)` — returns the Gamma function at x. +/// +/// CPython 3.14 raises ValueError for non-positive integers: +/// "expected a noninteger or positive integer, got ". +fn math_gamma(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.gamma", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + // CPython also rejects -inf for gamma (but not lgamma, where lgamma(-inf) = inf) + if f == f64::NEG_INFINITY { + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("expected a noninteger or positive integer, got {f:?}"), + ) + .into()); + } + check_gamma_pole(f)?; + + let result = libm::tgamma(f); + check_range_error(result, f)?; + Ok(Value::Float(result)) +} + +/// `math.lgamma(x)` — returns the natural log of the absolute value of Gamma(x). +fn math_lgamma(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.lgamma", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + check_gamma_pole(f)?; + + let result = libm::lgamma(f); + check_range_error(result, f)?; + Ok(Value::Float(result)) +} + +/// `math.erf(x)` — returns the error function at x. +fn math_erf(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.erf", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Float(libm::erf(f))) +} + +/// `math.erfc(x)` — returns the complementary error function at x (1 - erf(x)). +/// +/// More accurate than `1 - erf(x)` for large x. +fn math_erfc(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("math.erfc", vm.heap)?; + defer_drop!(value, vm); + + let f = value_to_float(value, vm)?; + Ok(Value::Float(libm::erfc(f))) +} + +// ========================== +// Helper functions +// ========================== + +/// Converts a `Value` to `f64`, raising `TypeError` if the value is not numeric. +/// +/// Accepts `Float`, `Int`, `Bool`, long ints and `Decimal`, which convert like `float()`, +/// so long ints raise `OverflowError` beyond the float range. Other types raise a +/// `TypeError` with a message matching CPython's format: "must be real number, not ". +#[expect( + clippy::cast_precision_loss, + reason = "i64-to-f64 can lose precision for large integers (beyond 2^53), but this matches CPython's conversion semantics" +)] +fn value_to_float(value: &Value, vm: &VM<'_>) -> RunResult { + match value { + Value::Float(f) => Ok(*f), + Value::Int(n) => Ok(*n as f64), + Value::Bool(b) => Ok(if *b { 1.0 } else { 0.0 }), + _ => match value.as_long_int(vm) { + Some(n) => bigint_to_f64_checked(n), + // `Decimal.__float__`, as `PyFloat_AsDouble` calls it. + None => match decimal::py::as_decimal(value, vm) { + Some(d) => d.to_f64(), + None => Err(ExcType::type_error_not_real_number(&value.py_type_name(vm))), + }, + }, + } +} + +/// Converts a `Value` to an arbitrary-precision integer, raising `TypeError` otherwise. +/// +/// Accepts `Int`, `Bool` and long ints; the message matches CPython's `__index__` failure. +fn value_to_bigint(value: &Value, vm: &VM<'_>) -> RunResult { + match value { + Value::Int(n) => Ok(BigInt::from(*n)), + Value::Bool(b) => Ok(BigInt::from(*b)), + _ => value + .as_long_int(vm) + .cloned() + .ok_or_else(|| not_an_integer_error(value, vm)), + } +} + +/// The `TypeError` CPython raises when `__index__` is missing on a `math` argument. +fn not_an_integer_error(value: &Value, vm: &VM<'_>) -> RunError { + ExcType::type_error(format!( + "'{}' object cannot be interpreted as an integer", + value.py_type_name(vm) + )) +} + +/// Requires that a float is finite, raising ValueError if it's inf or nan. +/// +/// CPython 3.14 uses "expected a finite input, got inf" for trig functions. +fn require_finite(f: f64) -> RunResult<()> { + if f.is_infinite() { + Err(SimpleException::new_msg(ExcType::ValueError, format!("expected a finite input, got {f:?}")).into()) + } else { + Ok(()) + } +} diff --git a/crates/bashkit-monty/src/modules/math/aggregate.rs b/crates/bashkit-monty/src/modules/math/aggregate.rs new file mode 100644 index 000000000..6444f2d7a --- /dev/null +++ b/crates/bashkit-monty/src/modules/math/aggregate.rs @@ -0,0 +1,414 @@ +//! Norms, accurate sums, and products for `math`. +//! +//! The numerical algorithms are broadly based on CPython's `Modules/mathmodule.c`: +//! Shewchuk's partials for `fsum`, a scaled compensated sum for `hypot`/`dist`, +//! and Neumaier's dot product for `sumprod`. + +use std::mem; + +use smallvec::SmallVec; + +use super::value_to_float; +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::VM, + defer_drop, + exception_private::{ExcType, RunResult, SimpleException}, + heap::DropGuard, + types::{PyTrait, Type, iter::collect_iterable}, + value::Value, +}; + +/// Coordinates remain owned until all conversions have succeeded. +#[derive(FromArgs)] +#[from_args(name = "hypot")] +struct HypotArgs { + #[from_args(varargs)] + coordinates: Vec, +} + +/// Computes a norm without overflowing intermediate squares. +pub(super) fn hypot(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let args = args.reject_kwargs("math.hypot", vm.heap)?; + let HypotArgs { coordinates } = HypotArgs::from_args(args, vm)?; + defer_drop!(coordinates, vm); + let mut values = coordinates + .iter() + .map(|value| value_to_float(value, vm).map(f64::abs)) + .collect::>>()?; + Ok(Value::Float(vector_norm(&mut values))) +} + +/// Positional-only points; CPython qualifies only the keyword error. +#[derive(FromArgs)] +#[from_args(name = "dist", style = unpack, kwarg_error_name = "math.dist")] +struct DistArgs { + #[from_args(pos_only)] + p: Value, + #[from_args(pos_only)] + q: Value, +} + +/// Collects both points before checking dimensions and converting coordinates. +pub(super) fn dist(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let DistArgs { p, q } = DistArgs::from_args(args, vm)?; + defer_drop!(p, vm); + defer_drop!(q, vm); + let p = collect_iterable(p, vm)?; + defer_drop!(p, vm); + let q = collect_iterable(q, vm)?; + defer_drop!(q, vm); + if p.len() != q.len() { + return Err(SimpleException::new_msg( + ExcType::ValueError, + "both points must have the same number of dimensions", + ) + .into()); + } + let mut differences = p + .iter() + .zip(q.iter()) + .map(|(p, q)| Ok((value_to_float(p, vm)? - value_to_float(q, vm)?).abs())) + .collect::>>()?; + Ok(Value::Float(vector_norm(&mut differences))) +} + +/// Scales by powers of two, compensates squares and sums, then corrects the square root. +/// Inputs are magnitudes; the subnormal branch rescales them in place once. +fn vector_norm(values: &mut [f64]) -> f64 { + let max = values.iter().copied().fold(0.0, f64::max); + if max.is_infinite() { + max + } else if values.iter().any(|x| x.is_nan()) { + f64::NAN + } else if max == 0.0 || values.len() <= 1 { + max + } else { + let (_, exponent) = libm::frexp(max); + if exponent < -1023 { + for value in values.iter_mut() { + *value /= f64::MIN_POSITIVE; + } + f64::MIN_POSITIVE * vector_norm(values) + } else { + let scale = libm::ldexp(1.0, -exponent); + // Starting at one makes the first operand dominate every square. + let mut sum = 1.0; + let mut square_errors = 0.0; + let mut sum_errors = 0.0; + for value in values { + let x = *value * scale; + let (square, error) = two_product(x, x); + let (next, residual) = fast_two_sum(sum, square); + sum = next; + square_errors += error; + sum_errors += residual; + } + let mut root = (sum - 1.0 + (square_errors + sum_errors)).sqrt(); + let (square, error) = two_product(-root, root); + let (sum, residual) = fast_two_sum(sum, square); + square_errors += error; + sum_errors += residual; + let correction = sum - 1.0 + (square_errors + sum_errors); + root += correction / (2.0 * root); + root / scale + } + } +} + +/// Returns the rounded sum and its residual when `|a| >= |b|`. +fn fast_two_sum(a: f64, b: f64) -> (f64, f64) { + let sum = a + b; + (sum, (a - sum) + b) +} + +/// Returns a sum and its residual without requiring ordered magnitudes. +fn two_sum(a: f64, b: f64) -> (f64, f64) { + let sum = a + b; + let recovered_b = sum - a; + (sum, (a - (sum - recovered_b)) + (b - recovered_b)) +} + +/// Retains the product's rounding error with fused multiply-add. +fn two_product(a: f64, b: f64) -> (f64, f64) { + let product = a * b; + (product, a.mul_add(b, -product)) +} + +/// Sums non-overlapping partials, preserving cancellation and half-even rounding. +pub(super) fn fsum(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let args = args.reject_kwargs("math.fsum", vm.heap)?; + let iterable = args.get_one_arg("math.fsum", vm.heap)?; + let iterator = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iterator, vm); + let mut iterator = iterator.read(vm); + let mut partials = SmallVec::<[f64; 32]>::new(); + let mut special_sum = 0.0; + let mut inf_sum = 0.0; + while let Some(item) = iterator.py_next(vm)? { + defer_drop!(item, vm); + let original = value_to_float(item, vm)?; + let mut x = original; + let mut retained = 0; + for index in 0..partials.len() { + let mut y = partials[index]; + if x.abs() < y.abs() { + mem::swap(&mut x, &mut y); + } + let hi = x + y; + let lo = y - (hi - x); + if lo != 0.0 { + partials[retained] = lo; + retained += 1; + } + x = hi; + } + partials.truncate(retained); + if x != 0.0 { + if x.is_finite() { + partials.push(x); + } else { + if original.is_finite() { + return Err( + SimpleException::new_msg(ExcType::OverflowError, "intermediate overflow in fsum").into(), + ); + } + if original.is_infinite() { + inf_sum += original; + } + special_sum += original; + partials.clear(); + } + } + } + if special_sum == 0.0 { + Ok(Value::Float(round_partials(&mut partials))) + } else if inf_sum.is_nan() { + Err(SimpleException::new_msg(ExcType::ValueError, "-inf + inf in fsum").into()) + } else { + Ok(Value::Float(special_sum)) + } +} + +/// Combines partials largest-first, using the remaining tail to resolve rounding ties. +#[expect( + clippy::float_cmp, + reason = "exact comparison detects a representable rounding correction" +)] +fn round_partials(partials: &mut SmallVec<[f64; 32]>) -> f64 { + let mut hi = partials.pop().unwrap_or(0.0); + let mut lo = 0.0; + while let Some(y) = partials.pop() { + let x = hi; + hi = x + y; + lo = y - (hi - x); + if lo != 0.0 { + break; + } + } + if let Some(tail) = partials.last() + && ((lo < 0.0 && *tail < 0.0) || (lo > 0.0 && *tail > 0.0)) + { + let correction = lo * 2.0; + let rounded = hi + correction; + if correction == rounded - hi { + hi = rounded; + } + } + hi +} + +/// `start` is keyword-only and is returned unchanged for an empty iterable. +#[derive(FromArgs)] +#[from_args(name = "prod", style = c_named, at_most_total)] +struct ProdArgs { + #[from_args(pos_only)] + iterable: Value, + #[from_args(kw_only, default = Value::Int(1))] + start: Value, +} + +/// Multiplies through Python's numeric protocol, retaining arbitrary-size integer results. +pub(super) fn prod(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ProdArgs { iterable, start } = ProdArgs::from_args(args, vm)?; + let mut result = DropGuard::new(start, vm); + { + let (total, vm) = result.as_parts_mut(); + let iterator = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iterator, vm); + let mut iterator = iterator.read(vm); + while let Some(item) = iterator.py_next(vm)? { + defer_drop!(item, vm); + let next = multiply(total, item, vm)?; + mem::replace(total, next).drop_with(vm); + } + } + Ok(result.into_inner()) +} + +/// Dot-product compensation keeps three floating-point components. +#[derive(Clone, Copy, Default)] +struct Triple { + /// Leading rounded sum. + hi: f64, + /// Residual from the leading sum and product. + lo: f64, + /// Accumulated residuals from combining the low components. + tiny: f64, +} + +impl Triple { + /// Adds a product with the three-component algorithm used by CPython's `sumprod`. + fn add_product(self, a: f64, b: f64) -> Self { + let (product, product_lo) = two_product(a, b); + let (hi, sum_lo) = two_sum(self.hi, product); + let (low_sum, low_error) = two_sum(self.lo, product_lo); + let (lo, tiny) = two_sum(low_sum, sum_lo); + Self { + hi, + lo, + tiny: self.tiny + low_error + tiny, + } + } + + /// Rounds the low components into the leading sum. + fn to_float(self) -> f64 { + let (hi, lo) = two_sum(self.lo, self.hi); + self.tiny + lo + hi + } +} + +/// Dot-product inputs are advanced in pairs, with strict length checking. +#[derive(FromArgs)] +#[from_args(name = "sumprod", style = unpack, kwarg_error_name = "math.sumprod")] +struct SumprodArgs { + #[from_args(pos_only)] + p: Value, + #[from_args(pos_only)] + q: Value, +} + +/// Uses exact integer arithmetic and compensated float products before generic arithmetic. +pub(super) fn sumprod(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let SumprodArgs { p, q } = SumprodArgs::from_args(args, vm)?; + defer_drop!(p, vm); + defer_drop!(q, vm); + let p = p.py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(p, vm); + let q = q.py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(q, vm); + let mut p = p.read(vm); + let mut q = q.read(vm); + let mut result = DropGuard::new(Value::Int(0), vm); + let (total, vm) = result.as_parts_mut(); + let mut integer_total = Some(0_i64); + let mut float_total = Some(Triple::default()); + let mut float_used = false; + loop { + let a = p.py_next(vm)?; + defer_drop!(a, vm); + let b = q.py_next(vm)?; + defer_drop!(b, vm); + if a.is_some() != b.is_some() { + return Err(SimpleException::new_msg(ExcType::ValueError, "Inputs are not the same length").into()); + } + let pair = a.as_ref().zip(b.as_ref()); + if let Some(accumulator) = integer_total { + if let Some((Value::Int(a), Value::Int(b))) = pair + && let Some(next) = a.checked_mul(*b).and_then(|product| accumulator.checked_add(product)) + { + integer_total = Some(next); + continue; + } + integer_total = None; + let next = add(total, &Value::Int(accumulator), vm)?; + mem::replace(total, next).drop_with(vm); + } + if let Some(accumulator) = float_total { + if let Some((a, b)) = pair + && let Ok(Some((a, b))) = float_pair(a, b, vm) + { + let next = accumulator.add_product(a, b); + if next.hi.is_finite() { + float_total = Some(next); + float_used = true; + continue; + } + } + float_total = None; + if float_used { + let next = add(total, &Value::Float(accumulator.to_float()), vm)?; + mem::replace(total, next).drop_with(vm); + } + } + if let Some((a, b)) = pair { + let product = multiply(a, b, vm)?; + defer_drop!(product, vm); + let next = add(total, product, vm)?; + mem::replace(total, next).drop_with(vm); + } else { + break; + } + } + Ok(result.into_inner()) +} + +/// The compensated path accepts float/float and float/int pairs, including booleans. +fn float_pair(a: &Value, b: &Value, vm: &VM<'_>) -> RunResult> { + if (matches!(a, Value::Float(_)) && matches!(b.py_type(vm), Type::Float | Type::Int | Type::Bool)) + || (matches!(b, Value::Float(_)) && matches!(a.py_type(vm), Type::Float | Type::Int | Type::Bool)) + { + Ok(Some((value_to_float(a, vm)?, value_to_float(b, vm)?))) + } else { + Ok(None) + } +} + +/// Checks mixed float/integer conversion before multiplication; generic arithmetic permits infinity. +fn multiply(a: &Value, b: &Value, vm: &mut VM<'_>) -> RunResult { + if let Some((a, b)) = float_pair(a, b, vm)? { + Ok(Value::Float(a * b)) + } else { + a.py_mul(b, vm) + } +} + +/// Checks mixed float/integer conversion when flushing a dot-product accumulator. +fn add(a: &Value, b: &Value, vm: &mut VM<'_>) -> RunResult { + if let Some((a, b)) = float_pair(a, b, vm)? { + Ok(Value::Float(a + b)) + } else { + a.py_add(b, vm) + } +} + +/// Three positional real numbers, converted in declaration order. +#[derive(FromArgs)] +#[from_args(name = "fma", style = unpack, kwarg_error_name = "math.fma")] +struct FmaArgs { + #[from_args(pos_only)] + x: Value, + #[from_args(pos_only)] + y: Value, + #[from_args(pos_only)] + z: Value, +} + +/// Performs one rounding and raises CPython's errors for invalid operations and overflow. +pub(super) fn fma(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let FmaArgs { x, y, z } = FmaArgs::from_args(args, vm)?; + defer_drop!(x, vm); + defer_drop!(y, vm); + defer_drop!(z, vm); + let x = value_to_float(x, vm)?; + let y = value_to_float(y, vm)?; + let z = value_to_float(z, vm)?; + let result = x.mul_add(y, z); + if result.is_nan() && !x.is_nan() && !y.is_nan() && !z.is_nan() { + Err(SimpleException::new_msg(ExcType::ValueError, "invalid operation in fma").into()) + } else if result.is_infinite() && x.is_finite() && y.is_finite() && z.is_finite() { + Err(SimpleException::new_msg(ExcType::OverflowError, "overflow in fma").into()) + } else { + Ok(Value::Float(result)) + } +} diff --git a/crates/bashkit-monty/src/modules/mod.rs b/crates/bashkit-monty/src/modules/mod.rs new file mode 100644 index 000000000..ac570f66d --- /dev/null +++ b/crates/bashkit-monty/src/modules/mod.rs @@ -0,0 +1,303 @@ +//! Built-in module implementations. +//! +//! This module provides implementations for Python built-in modules like `sys`, `typing`, +//! and `asyncio`. These are created on-demand when import statements are executed. + +use std::fmt::{self, Write}; + +use crate::{ + args::ArgValues, + bytecode::{CallResult, VM}, + exception_private::RunResult, + frozen::{self, FrozenFunctions}, + heap::HeapId, + intern::StaticStrings, +}; + +pub(crate) mod asyncio; +pub(crate) mod base64; +pub(crate) mod binascii; +pub(crate) mod bisect; +pub(crate) mod collections; +pub(crate) mod copy; +pub(crate) mod csv; +pub(crate) mod dataclasses; +pub(crate) mod datetime; +pub(crate) mod decimal; +pub(crate) mod functools; +#[cfg(feature = "test-hooks")] +pub(crate) mod gc; +pub(crate) mod hashlib; +pub(crate) mod itertools; +pub(crate) mod json; +pub(crate) mod math; +pub(crate) mod os; +pub(crate) mod os_path; +pub(crate) mod pathlib; +pub(crate) mod random; +pub(crate) mod re; +pub(crate) mod sys; +pub(crate) mod time; +pub(crate) mod tomllib; +pub(crate) mod typing; +pub(crate) mod unicodedata; + +/// Built-in modules that can be imported. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum StandardLib { + /// The `sys` module providing system-specific parameters and functions. + Sys, + /// The `typing` module providing type hints support. + Typing, + /// The `asyncio` module providing async/await support (only `run()` and `gather()` implemented). + Asyncio, + /// The `pathlib` module providing object-oriented filesystem paths. + Pathlib, + /// The `os` module: environment access, host-mediated filesystem calls and `os.path`. + Os, + /// The `os.path` module (CPython's `posixpath`), also reached as `import posixpath`. + OsPath, + /// The `math` module providing mathematical functions and constants. + Math, + /// The `json` module providing JSON parsing and serialization. + Json, + /// The `re` module providing regular expression matching. + Re, + /// The `datetime` module providing date and time types. + Datetime, + /// The `unicodedata` module providing Unicode Character Database access. + Unicodedata, + /// The `itertools` module providing lazy iterators — every name CPython + /// exports, the private ones included. + Itertools, + /// The `dataclasses` module providing `@dataclass` and helpers. + Dataclasses, + /// The `collections` module providing container datatypes: `deque`, + /// `namedtuple`, `defaultdict`, and `Counter`. + Collections, + /// The `functools` module providing reduction, partial application, and caching. + Functools, + /// The `base64` module providing the base64/base32/base16 codecs. + Base64, + /// The `binascii` module providing binary-to-ASCII conversions, CRC32, + /// and the `Error` class used by `base64`. + Binascii, + /// The `random` module: CPython's Mersenne Twister generator and the + /// distributions built on it. + Random, + /// The `copy` module providing `copy()` and `deepcopy()`. + Copy, + /// The `time` module providing `time()` and `sleep()`, both of which the + /// host serves. + Time, + /// The `hashlib` module: the guaranteed algorithms, `new()` and `pbkdf2_hmac()`. + Hashlib, + /// Binary search and sorted insertion. + Bisect, + /// The `csv` module: readers, writers, `DictReader` / `DictWriter` and the + /// built-in dialects. + Csv, + /// The `tomllib` module: `loads()`, `load()` and `TOMLDecodeError`. + Tomllib, + /// The `decimal` module: `Decimal`, `Context` and the signals. + Decimal, + /// The `gc` module exposing a single `collect()` for tests. Only present + /// under the `test-hooks` feature so production sandboxes never see it. + /// + #[cfg(feature = "test-hooks")] + Gc, +} + +impl StandardLib { + /// Resolves a module name without depending on enum discriminant order. + pub fn from_static(name: StaticStrings) -> Option { + match name { + StaticStrings::Sys => Some(Self::Sys), + StaticStrings::Typing => Some(Self::Typing), + StaticStrings::Asyncio => Some(Self::Asyncio), + StaticStrings::Pathlib => Some(Self::Pathlib), + StaticStrings::Os => Some(Self::Os), + StaticStrings::OsPath | StaticStrings::Posixpath => Some(Self::OsPath), + StaticStrings::Math => Some(Self::Math), + StaticStrings::Json => Some(Self::Json), + StaticStrings::Re => Some(Self::Re), + StaticStrings::Datetime => Some(Self::Datetime), + StaticStrings::Unicodedata => Some(Self::Unicodedata), + StaticStrings::Itertools => Some(Self::Itertools), + StaticStrings::Dataclasses => Some(Self::Dataclasses), + StaticStrings::Collections => Some(Self::Collections), + StaticStrings::Functools => Some(Self::Functools), + StaticStrings::Base64 => Some(Self::Base64), + StaticStrings::Binascii => Some(Self::Binascii), + StaticStrings::Random => Some(Self::Random), + StaticStrings::Copy => Some(Self::Copy), + StaticStrings::Time => Some(Self::Time), + StaticStrings::Hashlib => Some(Self::Hashlib), + StaticStrings::Bisect => Some(Self::Bisect), + StaticStrings::Csv => Some(Self::Csv), + StaticStrings::Tomllib => Some(Self::Tomllib), + StaticStrings::DecimalMod => Some(Self::Decimal), + #[cfg(feature = "test-hooks")] + StaticStrings::Gc => Some(Self::Gc), + _ => None, + } + } + + /// The import names of every built-in module (`os.path` included), so a + /// host can keep its own module names clear of them. + pub fn names() -> impl Iterator { + (0..) + .map_while(StaticStrings::from_repr) + .filter_map(|name| Self::from_static(name).map(|_| <&'static str>::from(name))) + } + + /// Creates a new instance of this module on the heap. + pub fn create(self, vm: &mut VM<'_>) -> HeapId { + match self { + Self::Sys => sys::create_module(vm), + Self::Typing => typing::create_module(vm), + Self::Asyncio => asyncio::create_module(vm), + Self::Pathlib => pathlib::create_module(vm), + Self::Os => os::create_module(vm), + Self::OsPath => os_path::create_module(vm), + Self::Math => math::create_module(vm), + Self::Json => json::create_module(vm), + Self::Re => re::create_module(vm), + Self::Datetime => datetime::create_module(vm), + Self::Unicodedata => unicodedata::create_module(vm), + Self::Itertools => itertools::create_module(vm), + Self::Dataclasses => dataclasses::create_module(vm), + Self::Collections => collections::create_module(vm), + Self::Functools => functools::create_module(vm), + Self::Base64 => base64::create_module(vm), + Self::Binascii => binascii::create_module(vm), + Self::Random => random::create_module(vm), + Self::Copy => copy::create_module(vm), + Self::Time => time::create_module(vm), + Self::Hashlib => hashlib::create_module(vm), + Self::Bisect => bisect::create_module(vm), + Self::Csv => csv::create_module(vm), + Self::Tomllib => tomllib::create_module(vm), + Self::Decimal => decimal::create_module(vm), + #[cfg(feature = "test-hooks")] + Self::Gc => gc::create_module(vm), + } + } +} + +/// All stdlib module function (but not builtins). +/// +/// Every dump reaches these through `Value::ModuleFunction`, encoded by variant +/// name, so renaming a variant needs `#[serde(alias)]` (see `DUMP_VERSION`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) enum ModuleFunctions { + Asyncio(asyncio::AsyncioFunctions), + Collections(collections::CollectionsFunctions), + Json(json::JsonFunctions), + Math(math::MathFunctions), + Os(os::OsFunctions), + OsPath(os_path::OsPathFunctions), + Re(re::ReFunctions), + Unicodedata(unicodedata::UnicodedataFunctions), + Itertools(itertools::ItertoolsFunctions), + Dataclasses(dataclasses::DataclassesFunctions), + Functools(functools::FunctoolsFunctions), + Base64(base64::Base64Functions), + Binascii(binascii::BinasciiFunctions), + Random(random::RandomFunctions), + Copy(copy::CopyFunctions), + /// Private primitives passed explicitly to frozen Python implementations. + Frozen(FrozenFunctions), + Time(time::TimeFunctions), + Hashlib(hashlib::HashlibFunctions), + Bisect(bisect::BisectFunctions), + Csv(csv::CsvFunctions), + Tomllib(tomllib::TomllibFunctions), + Decimal(decimal::DecimalFunctions), + /// `gc` module functions — only present under the `test-hooks` feature. + /// See [`gc`] for why it is gated; as in [`StandardLib`], the gated block + /// goes last and new variants are appended ahead of it. + #[cfg(feature = "test-hooks")] + Gc(gc::GcFunctions), + /// `sys` module functions — only present under the `test-hooks` feature. + /// Production `sys` is attribute-only; the test feature adds callables + /// like `setrecursionlimit` that fixtures use to align behavior with + /// CPython. See [`sys`] for the rationale. + #[cfg(feature = "test-hooks")] + Sys(sys::SysFunctions), +} + +impl fmt::Display for ModuleFunctions { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Asyncio(func) => write!(f, "{func}"), + Self::Collections(func) => write!(f, "{func}"), + Self::Json(func) => write!(f, "{func}"), + Self::Math(func) => write!(f, "{func}"), + Self::Os(func) => write!(f, "{func}"), + Self::OsPath(func) => write!(f, "{func}"), + Self::Re(func) => write!(f, "{func}"), + Self::Unicodedata(func) => write!(f, "{func}"), + Self::Itertools(func) => write!(f, "{func}"), + Self::Dataclasses(func) => write!(f, "{func}"), + Self::Functools(func) => write!(f, "{func}"), + Self::Base64(func) => write!(f, "{func}"), + Self::Binascii(func) => write!(f, "{func}"), + Self::Random(func) => write!(f, "{func}"), + Self::Copy(func) => write!(f, "{func}"), + Self::Frozen(func) => write!(f, "{func}"), + Self::Time(func) => write!(f, "{func}"), + Self::Hashlib(func) => write!(f, "{func}"), + Self::Bisect(func) => write!(f, "{func}"), + Self::Csv(func) => write!(f, "{func}"), + Self::Tomllib(func) => write!(f, "{func}"), + Self::Decimal(func) => write!(f, "{func}"), + #[cfg(feature = "test-hooks")] + Self::Gc(func) => write!(f, "{func}"), + #[cfg(feature = "test-hooks")] + Self::Sys(func) => write!(f, "{func}"), + } + } +} + +impl ModuleFunctions { + /// Calls the module function with the given arguments. + /// + /// Returns `CallResult` to support both immediate values and OS calls that + /// require host involvement (e.g., `os.getenv()` needs the host to provide environment variables). + pub fn call(self, vm: &mut VM<'_>, args: ArgValues) -> RunResult { + match self { + Self::Asyncio(functions) => asyncio::call(vm, functions, args), + Self::Collections(functions) => collections::call(vm, functions, args).map(CallResult::Value), + Self::Json(functions) => json::call(vm, functions, args), + Self::Math(functions) => math::call(vm, functions, args).map(CallResult::Value), + Self::Os(functions) => os::call(vm, functions, args), + Self::OsPath(functions) => os_path::call(vm, functions, args), + Self::Re(functions) => re::call(vm, functions, args), + Self::Unicodedata(functions) => unicodedata::call(vm, functions, args).map(CallResult::Value), + Self::Itertools(functions) => itertools::call(vm, functions, args).map(CallResult::Value), + Self::Dataclasses(functions) => dataclasses::call(vm, functions, args).map(CallResult::Value), + Self::Functools(functions) => functools::call(vm, functions, args), + Self::Base64(functions) => base64::call(vm, functions, args).map(CallResult::Value), + Self::Binascii(functions) => binascii::call(vm, functions, args).map(CallResult::Value), + Self::Random(functions) => random::call(vm, functions, args), + Self::Copy(functions) => copy::call(vm, functions, args).map(CallResult::Value), + Self::Frozen(functions) => frozen::call_helper(functions, args, vm), + Self::Time(functions) => time::call(vm, functions, args), + Self::Hashlib(functions) => hashlib::call(vm, functions, args).map(CallResult::Value), + Self::Bisect(functions) => bisect::call(vm, functions, args).map(CallResult::Value), + Self::Csv(functions) => csv::call(vm, functions, args), + Self::Tomllib(functions) => tomllib::call(vm, functions, args), + Self::Decimal(functions) => decimal::call(vm, functions, args).map(CallResult::Value), + #[cfg(feature = "test-hooks")] + Self::Gc(functions) => gc::call(vm, functions, args).map(CallResult::Value), + #[cfg(feature = "test-hooks")] + Self::Sys(functions) => sys::call(vm, functions, args).map(CallResult::Value), + } + } + + /// Writes the Python repr() string for this function to a formatter. + pub fn py_repr_fmt(self, f: &mut W, py_id: impl fmt::LowerHex) -> fmt::Result { + write!(f, "") + } +} diff --git a/crates/bashkit-monty/src/modules/os.rs b/crates/bashkit-monty/src/modules/os.rs new file mode 100644 index 000000000..d559d0031 --- /dev/null +++ b/crates/bashkit-monty/src/modules/os.rs @@ -0,0 +1,818 @@ +//! Implementation of the `os` module. +//! +//! Environment access (`getenv`, `environ`), filesystem wrappers (`listdir`, +//! `stat`, `mkdir`, `makedirs`, `remove`, `unlink`, `rmdir`, `rename`, +//! `replace`), the pure `fspath`, the `os.path` submodule (see `os_path`) +//! and the POSIX path constants (`sep`, `linesep`, `name`, ...). The sandbox +//! always presents a POSIX view regardless of host OS, so the constants are +//! fixed. +//! +//! Filesystem functions never touch the host directly: they yield an +//! [`OsFunctionCall`] (the same variants `pathlib.Path` methods use) for the +//! host to permit or reject. `os.listdir` reuses the `Iterdir` call and +//! reduces the returned child paths to bare names via +//! [`PreConversionEffect::ListdirNames`] (see `os_dispatch::listdir_names`). +//! +//! `dir_fd` / `follow_symlinks` keyword arguments are parsed for signature +//! parity but rejected with the `NotImplementedError` CPython raises on +//! platforms without them — Monty never supports fd-relative paths. An int +//! where CPython accepts an fd as the path is a closed fd here, so it fails +//! as one would there (see [`PathArgError`]). + +use monty_types::{GetenvArgs, MkdirCallArgs, MontyObject, MontyPath, OsFunctionCall, RenameCallArgs, UrandomArgs}; + +use crate::{ + args::{ArgValues, FromArgs, LaxBool}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{HeapData, HeapId}, + intern::{StaticStrings, StringId}, + modules::{ModuleFunctions, os_path}, + object_bridge::MontyObjectExt, + os_dispatch::{PreConversionEffect, value_to_owned_string}, + types::{ + Bytes, Module, Property, PyTrait, Type, + dir_scan::{scandir_call, walk_call}, + property::ZeroArgOsProperty, + str::allocate_string, + }, + value::Value, + virtual_path::posix_join, +}; + +/// OS module functions. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "lowercase")] +pub(crate) enum OsFunctions { + Getenv, + Listdir, + Stat, + Mkdir, + Makedirs, + Remove, + Unlink, + Rmdir, + Rename, + Replace, + Fspath, + Getcwd, + Getcwdb, + Chdir, + Urandom, + Scandir, + Walk, +} + +/// Creates the `os` module and allocates it on the heap. +/// +/// Functions yield to the host via `OsFunction` callbacks (except the pure +/// `fspath`); constants are fixed POSIX values since the sandbox path model +/// is always POSIX. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + /// Shorthand for the function-attribute entries in the table below. + fn function(f: OsFunctions) -> Value { + Value::ModuleFunction(ModuleFunctions::Os(f)) + } + + let attrs = [ + // Callables — each dispatches through `ModuleFunctions::Os`. + (StaticStrings::Getenv, function(OsFunctions::Getenv)), + (StaticStrings::Listdir, function(OsFunctions::Listdir)), + (StaticStrings::StatMethod, function(OsFunctions::Stat)), + (StaticStrings::Mkdir, function(OsFunctions::Mkdir)), + (StaticStrings::Makedirs, function(OsFunctions::Makedirs)), + (StaticStrings::Remove, function(OsFunctions::Remove)), + (StaticStrings::Unlink, function(OsFunctions::Unlink)), + (StaticStrings::Rmdir, function(OsFunctions::Rmdir)), + (StaticStrings::Rename, function(OsFunctions::Rename)), + (StaticStrings::Replace, function(OsFunctions::Replace)), + (StaticStrings::Getcwd, function(OsFunctions::Getcwd)), + (StaticStrings::Getcwdb, function(OsFunctions::Getcwdb)), + (StaticStrings::Chdir, function(OsFunctions::Chdir)), + (StaticStrings::Urandom, function(OsFunctions::Urandom)), + (StaticStrings::Scandir, function(OsFunctions::Scandir)), + (StaticStrings::Walk, function(OsFunctions::Walk)), + (StaticStrings::OsFspath, function(OsFunctions::Fspath)), + // os.environ — property that yields the host environment as a dict. + ( + StaticStrings::Environ, + Value::Property(Property::Os(ZeroArgOsProperty::GetEnviron)), + ), + // `os.path` is its own module object, like CPython's `posixpath`. + (StaticStrings::Path, Value::Ref(os_path::create_module(vm))), + // POSIX path constants — the sandbox path model is POSIX on every host. + (StaticStrings::Sep, Value::InternString(StringId::from_ascii(b'/'))), + (StaticStrings::Pathsep, Value::InternString(StringId::from_ascii(b':'))), + ( + StaticStrings::Defpath, + Value::InternString(vm.interns.intern_static(StaticStrings::DefpathString)), + ), + (StaticStrings::Altsep, Value::None), + (StaticStrings::Extsep, Value::InternString(StringId::from_ascii(b'.'))), + (StaticStrings::Curdir, Value::InternString(StringId::from_ascii(b'.'))), + ( + StaticStrings::Pardir, + Value::InternString(vm.interns.intern_static(StaticStrings::ParentDirString)), + ), + (StaticStrings::Linesep, Value::InternString(StringId::from_ascii(b'\n'))), + ( + StaticStrings::Name, + Value::InternString(vm.interns.intern_static(StaticStrings::Posix)), + ), + ( + StaticStrings::Devnull, + Value::InternString(vm.interns.intern_static(StaticStrings::DevNullString)), + ), + ]; + + let mut module = Module::new(StaticStrings::Os, vm.interns); + for (attr, value) in attrs { + module.set_attr(attr, value, vm); + } + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a call to an os module function. +/// +/// Returns `CallResult::OsCall` for functions that need host involvement, +/// or `CallResult::Value` for functions that can be computed immediately. +pub(super) fn call(vm: &mut VM<'_>, functions: OsFunctions, args: ArgValues) -> RunResult { + match functions { + OsFunctions::Getenv => getenv(vm, args), + OsFunctions::Listdir => listdir(vm, args), + OsFunctions::Stat => stat(vm, args), + OsFunctions::Mkdir => mkdir(vm, args), + OsFunctions::Makedirs => makedirs(vm, args), + OsFunctions::Remove => remove(vm, args), + OsFunctions::Unlink => unlink(vm, args), + OsFunctions::Rmdir => rmdir(vm, args), + OsFunctions::Rename => rename(vm, args), + OsFunctions::Replace => replace(vm, args), + OsFunctions::Fspath => fspath(vm, args), + OsFunctions::Getcwd => getcwd(vm, args), + OsFunctions::Getcwdb => getcwdb(vm, args), + OsFunctions::Chdir => chdir(vm, args), + OsFunctions::Urandom => urandom(vm, args), + OsFunctions::Scandir => scandir(vm, args), + OsFunctions::Walk => walk(vm, args), + } +} + +/// `os.scandir(path=None)` argument shape — clinic-parsed with the +/// `at_most_total` pre-count, like `os.listdir`. +#[derive(FromArgs)] +#[from_args(name = "scandir", at_most_total)] +struct ScandirArgs { + #[from_args(default = Value::None)] + path: Value, +} + +/// Implementation of `os.scandir(path=None)`: one depth-one host scan, +/// answered with a `ScandirIterator` whose entries need no further host calls. +fn scandir(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ScandirArgs { path } = ScandirArgs::from_args(args, vm)?; + defer_drop!(path, vm); + let path = if matches!(path, Value::None) { + MontyPath::from(".") + } else { + extract_os_path(path, "scandir", "path", PathAccepts::FdOrNone, vm)? + }; + if path.is_empty() { + // The host would scan the working directory; CPython fails with ENOENT. + Err(ExcType::file_not_found_error("")) + } else { + Ok(scandir_call(path)) + } +} + +/// `os.walk(top, topdown=True, onerror=None, followlinks=False)` argument +/// shape — a pure-Python generator in CPython, hence `style = def`. +#[derive(FromArgs)] +#[from_args(name = "walk", style = def)] +struct WalkArgs { + top: Value, + #[from_args(default = LaxBool::new(true))] + topdown: LaxBool, + #[from_args(default = Value::None)] + onerror: Value, + #[from_args(default = LaxBool::new(false))] + followlinks: LaxBool, +} + +/// Implementation of `os.walk(top, topdown=True, onerror=None, followlinks=False)`. +/// +/// One host scan reads the whole tree; the returned iterator then walks it, +/// honouring `dirnames` pruning and calling `onerror` as CPython's generator +/// does. `top` is converted eagerly, so a bad type raises here rather than at +/// the first `next()`. +fn walk(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let WalkArgs { + top, + topdown, + onerror, + followlinks, + } = WalkArgs::from_args(args, vm)?; + defer_drop!(top, vm); + let top = match extract_path(top, vm, ExcType::type_error_fspath) { + Ok(top) => top, + Err(err) => { + onerror.drop_with(vm); + return Err(err); + } + }; + walk_call( + top.into_string(), + false, + topdown.bool(), + onerror, + followlinks.bool(), + vm, + ) +} + +/// `os.urandom(size, /)` argument shape: clinic-parsed, positional-only. +#[derive(FromArgs)] +#[from_args(name = "urandom")] +struct UrandomFnArgs { + #[from_args(pos_only)] + size: Value, +} + +/// Implementation of `os.urandom(size)`: asks the host for `size` bytes of +/// entropy. `size` is checked here so a negative count never reaches a +/// handler, and checked against the memory limit before the call so an +/// oversized request never leaves the sandbox when a limit is set (hosts +/// still cap it themselves). The reply must be exactly `size` bytes, +/// enforced by [`PreConversionEffect::UrandomLength`] before it is converted. +fn urandom(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let UrandomFnArgs { size } = UrandomFnArgs::from_args(args, vm)?; + defer_drop!(size, vm); + let size = size.as_int_with_overflow(vm, ExcType::overflow_c_ssize_t)?; + if size < 0 { + return Err(ExcType::value_error("negative argument not allowed")); + } + // `ssize_t` is the platform's word, so a 32-bit target rejects here as CPython does. + let len = usize::try_from(size).map_err(|_| ExcType::overflow_c_ssize_t())?; + vm.heap.tracker.check_allocation(len)?; + Ok(CallResult::OsCallWithEffect { + call: OsFunctionCall::Urandom(UrandomArgs { size: len as u64 }), + effect: PreConversionEffect::UrandomLength { size: len }.into(), + }) +} + +/// Implementation of `os.getcwd()` — the sandbox's virtual working +/// directory, held by the VM so no host round-trip is needed. +fn getcwd(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + args.check_zero_args("getcwd", vm.heap)?; + Ok(CallResult::Value(allocate_string(&*vm.env.cwd, vm.heap))) +} + +/// Implementation of `os.getcwdb()`: the working directory as bytes. +/// +/// Virtual paths are always UTF-8, so this is `os.getcwd().encode()` with no +/// filesystem encoding involved. +fn getcwdb(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + args.check_zero_args("getcwdb", vm.heap)?; + let bytes = Bytes::new(vm.env.cwd.as_bytes().to_vec()); + Ok(CallResult::Value(Value::Ref(vm.heap.allocate(HeapData::Bytes(bytes))))) +} + +/// `os.chdir(path)` accepts a positional or keyword path, with CPython's total-count check. +#[derive(FromArgs)] +#[from_args(name = "chdir", style = c_named, at_most_total)] +struct ChdirArgs { + path: Value, +} + +/// Implementation of `os.chdir(path)`. +/// +/// The VM owns the working directory, but the target must exist and be a +/// directory, so the resolved path goes to the host as a `Path.stat` call +/// with a [`PreConversionEffect::Chdir`] that adopts it on a directory reply. +/// `FileNotFoundError` therefore comes from the host, `NotADirectoryError` +/// from the resume side. +fn chdir(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ChdirArgs { path } = ChdirArgs::from_args(args, vm)?; + defer_drop!(path, vm); + let spelled = extract_os_path(path, "chdir", "path", PathAccepts::Fd, vm)?; + if spelled.is_empty() { + // CPython's `chdir("")` fails with ENOENT; the host would otherwise stat the root. + return Err(ExcType::file_not_found_error("")); + } + if spelled.contains('\0') { + // The VM's generic NUL check names the `Path.stat` call this becomes; CPython names `chdir`. + return Err(ExcType::value_error("chdir: embedded null character in path")); + } + // Keep every component until the host validates the target; normalize on success. + let path = posix_join(&vm.env.cwd, &spelled); + Ok(CallResult::OsCallWithEffect { + call: OsFunctionCall::Stat(MontyPath::new(path.clone())), + effect: PreConversionEffect::Chdir { + path, + spelled: spelled.into_string(), + } + .into(), + }) +} + +/// Implementation of `os.getenv(key, default=None)`. +/// +/// Hand-rolled rather than `FromArgs`-derived so the `key`-must-be-`str` +/// error matches CPython's wording exactly — CPython routes `os.getenv` +/// through `os.environ.__getitem__`, whose `check_str` helper raises +/// `TypeError("str expected, not ")`. That wording is bespoke to +/// `os._Environ` in the CPython stdlib, so it lives inline here rather +/// than as a shared helper. +fn getenv(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let (key_value, default_value) = args.get_one_two_args("os.getenv", vm.heap)?; + if let Some(key) = key_value.as_either_str(vm.heap) { + key_value.drop_with(vm.heap); + Ok(CallResult::OsCall(OsFunctionCall::Getenv(GetenvArgs { + key: key.into_string(vm.interns), + default: MontyObject::export(default_value.unwrap_or(Value::None), vm), + }))) + } else { + let type_name = key_value.py_type_name_heap(vm.heap, vm.interns); + key_value.drop_with(vm.heap); + + if let Some(d) = default_value { + d.drop_with(vm.heap); + } + Err(ExcType::type_error(format!("str expected, not {type_name}"))) + } +} + +/// `os.listdir(path=None)` argument shape — clinic-parsed with the +/// `at_most_total` pre-count (`listdir() takes at most 1 argument (2 given)`). +#[derive(FromArgs)] +#[from_args(name = "listdir", at_most_total)] +struct ListdirArgs { + #[from_args(default = Value::None)] + path: Value, +} + +/// Implementation of `os.listdir(path=None)`. +/// +/// Reuses the `Iterdir` OS call (host returns full child paths) with a +/// [`PreConversionEffect::ListdirNames`] — armed at dispatch, not here — so the +/// resume reduces them to bare entry names. `None` maps to `'.'` like +/// CPython, which the VM resolves to the working directory on its way out. +fn listdir(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ListdirArgs { path } = ListdirArgs::from_args(args, vm)?; + defer_drop!(path, vm); + let path = if matches!(path, Value::None) { + MontyPath::from(".") + } else { + extract_os_path(path, "listdir", "path", PathAccepts::FdOrNone, vm)? + }; + Ok(CallResult::OsCallWithEffect { + call: OsFunctionCall::Iterdir(path), + effect: PreConversionEffect::ListdirNames.into(), + }) +} + +/// `os.stat(path, *, dir_fd=None, follow_symlinks=True)` argument shape. +/// `follow_symlinks` uses [`LaxBool`] — CPython truth-tests it, so any value +/// is accepted. +#[derive(FromArgs)] +#[from_args(name = "stat", style = c_named)] +struct StatArgs { + path: Value, + #[from_args(kw_only, default = Value::None)] + dir_fd: Value, + #[from_args(kw_only, default = LaxBool::new(true))] + follow_symlinks: LaxBool, +} + +/// Implementation of `os.stat(path)` — yields the same `Stat` OS call as +/// `Path.stat()`. `follow_symlinks=False` (lstat) is not supported. +fn stat(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let StatArgs { + path, + dir_fd, + follow_symlinks, + } = StatArgs::from_args(args, vm)?; + defer_drop!(path, vm); + defer_drop!(dir_fd, vm); + let path = extract_os_path(path, "stat", "path", PathAccepts::Fd, vm)?; + check_dir_fd(dir_fd, vm)?; + if follow_symlinks.bool() { + Ok(CallResult::OsCall(OsFunctionCall::Stat(path))) + } else { + Err(ExcType::not_implemented_os_arg(Some("stat"), "follow_symlinks")) + } +} + +/// `os.mkdir(path, mode=0o777, *, dir_fd=None)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "mkdir", style = c_named)] +struct MkdirArgs { + path: Value, + #[from_args(default = Value::Int(0o777))] + mode: Value, + #[from_args(kw_only, default = Value::None)] + dir_fd: Value, +} + +/// Implementation of `os.mkdir(path, mode=0o777)` — single level, no +/// exist-tolerance. `mode` is validated but ignored: Monty's filesystem +/// backends do not model POSIX permission bits. +fn mkdir(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let MkdirArgs { path, mode, dir_fd } = MkdirArgs::from_args(args, vm)?; + defer_drop!(path, vm); + defer_drop!(mode, vm); + defer_drop!(dir_fd, vm); + let path = extract_os_path(path, "mkdir", "path", PathAccepts::NoFd, vm)?; + check_mode(mode, vm)?; + check_dir_fd(dir_fd, vm)?; + Ok(CallResult::OsCall(OsFunctionCall::Mkdir(MkdirCallArgs { + path, + parents: false, + exist_ok: false, + }))) +} + +/// `os.makedirs(name, mode=0o777, exist_ok=False)` argument shape — a pure +/// Python `def` in CPython, hence `style = def`. `exist_ok` uses [`LaxBool`] +/// (truth-tested, never type-checked) like the sibling `PathMkdirArgs`. +#[derive(FromArgs)] +#[from_args(name = "makedirs", style = def)] +struct MakedirsArgs { + name: Value, + #[from_args(default = Value::Int(0o777))] + mode: Value, + #[from_args(default = LaxBool::new(false))] + exist_ok: LaxBool, +} + +/// Implementation of `os.makedirs(name, mode=0o777, exist_ok=False)` — +/// recursive `mkdir` via the `parents=True` flag on the `Mkdir` OS call. +fn makedirs(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let MakedirsArgs { name, mode, exist_ok } = MakedirsArgs::from_args(args, vm)?; + defer_drop!(name, vm); + defer_drop!(mode, vm); + // CPython's `makedirs` body starts with `path.split(name)`, whose + // `fspath` call produces this wording (not the `mkdir` converter's). + let path = extract_path(name, vm, ExcType::type_error_fspath)?; + check_mode(mode, vm)?; + Ok(CallResult::OsCall(OsFunctionCall::Mkdir(MkdirCallArgs { + path, + parents: true, + exist_ok: exist_ok.bool(), + }))) +} + +/// `os.remove(path, *, dir_fd=None)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "remove", style = c_named)] +struct RemoveArgs { + path: Value, + #[from_args(kw_only, default = Value::None)] + dir_fd: Value, +} + +/// Implementation of `os.remove(path)` — yields the same `Unlink` OS call as +/// `Path.unlink()`. +fn remove(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let RemoveArgs { path, dir_fd } = RemoveArgs::from_args(args, vm)?; + single_path_call(path, dir_fd, "remove", OsFunctionCall::Unlink, vm) +} + +/// `os.unlink(path, *, dir_fd=None)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "unlink", style = c_named)] +struct UnlinkArgs { + path: Value, + #[from_args(kw_only, default = Value::None)] + dir_fd: Value, +} + +/// Implementation of `os.unlink(path)` — alias of [`remove`] with its own +/// name in error messages. +fn unlink(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let UnlinkArgs { path, dir_fd } = UnlinkArgs::from_args(args, vm)?; + single_path_call(path, dir_fd, "unlink", OsFunctionCall::Unlink, vm) +} + +/// Shared body of [`remove`] / [`unlink`] / [`rmdir`]: validate the path and +/// `dir_fd`, then build the OS call via `make_call`. +fn single_path_call( + path: Value, + dir_fd: Value, + func: &'static str, + make_call: impl FnOnce(MontyPath) -> OsFunctionCall, + vm: &mut VM<'_>, +) -> RunResult { + defer_drop!(path, vm); + defer_drop!(dir_fd, vm); + let path = extract_os_path(path, func, "path", PathAccepts::NoFd, vm)?; + check_dir_fd(dir_fd, vm)?; + Ok(CallResult::OsCall(make_call(path))) +} + +/// `os.rmdir(path, *, dir_fd=None)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "rmdir", style = c_named)] +struct RmdirArgs { + path: Value, + #[from_args(kw_only, default = Value::None)] + dir_fd: Value, +} + +/// Implementation of `os.rmdir(path)` — yields the same `Rmdir` OS call as +/// `Path.rmdir()`. +fn rmdir(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let RmdirArgs { path, dir_fd } = RmdirArgs::from_args(args, vm)?; + single_path_call(path, dir_fd, "rmdir", OsFunctionCall::Rmdir, vm) +} + +/// `os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "rename", style = c_named)] +struct RenameArgs { + src: Value, + dst: Value, + #[from_args(kw_only, default = Value::None)] + src_dir_fd: Value, + #[from_args(kw_only, default = Value::None)] + dst_dir_fd: Value, +} + +/// Implementation of `os.rename(src, dst)`. +fn rename(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let RenameArgs { + src, + dst, + src_dir_fd, + dst_dir_fd, + } = RenameArgs::from_args(args, vm)?; + rename_like(src, dst, src_dir_fd, dst_dir_fd, false, vm) +} + +/// `os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "replace", style = c_named)] +struct ReplaceArgs { + src: Value, + dst: Value, + #[from_args(kw_only, default = Value::None)] + src_dir_fd: Value, + #[from_args(kw_only, default = Value::None)] + dst_dir_fd: Value, +} + +/// Implementation of `os.replace(src, dst)` — same `Rename` OS call as +/// [`rename`]; overwrite behavior is whatever the host backend does. +fn replace(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReplaceArgs { + src, + dst, + src_dir_fd, + dst_dir_fd, + } = ReplaceArgs::from_args(args, vm)?; + rename_like(src, dst, src_dir_fd, dst_dir_fd, true, vm) +} + +/// Shared body of [`rename`] / [`replace`]: validate both endpoints and the +/// fd keywords (type errors per-fd first, then the combined +/// `NotImplementedError`, matching CPython's `internal_rename` ordering). +fn rename_like( + src: Value, + dst: Value, + src_dir_fd: Value, + dst_dir_fd: Value, + replace: bool, + vm: &mut VM<'_>, +) -> RunResult { + let func = if replace { "replace" } else { "rename" }; + defer_drop!(src, vm); + defer_drop!(dst, vm); + defer_drop!(src_dir_fd, vm); + defer_drop!(dst_dir_fd, vm); + let src = extract_os_path(src, func, "src", PathAccepts::NoFd, vm)?; + let dst = extract_os_path(dst, func, "dst", PathAccepts::NoFd, vm)?; + // Non-short-circuiting `|`: both fds are type-checked before either is + // rejected as unsupported, matching CPython's converter ordering. + if dir_fd_specified(src_dir_fd, vm)? | dir_fd_specified(dst_dir_fd, vm)? { + Err(ExcType::not_implemented_os_arg(Some(func), "src_dir_fd and dst_dir_fd")) + } else { + Ok(CallResult::OsCall(OsFunctionCall::Rename(RenameCallArgs { src, dst }))) + } +} + +/// `os.fspath(path)` argument shape — clinic-parsed with the `at_most_total` +/// pre-count (`fspath() takes at most 1 argument (2 given)`). +#[derive(FromArgs)] +#[from_args(name = "fspath", style = c_named, at_most_total)] +struct FspathArgs { + path: Value, +} + +/// Implementation of `os.fspath(path)` — pure, no host involvement: `str` and +/// `bytes` pass through unchanged, `Path` and `DirEntry` yield their string form. +fn fspath(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let FspathArgs { path } = FspathArgs::from_args(args, vm)?; + match path.py_type_heap(vm.heap) { + Type::Str | Type::Bytes => Ok(CallResult::Value(path)), + Type::Path | Type::DirEntry => { + let text = value_to_owned_string(&path, vm.heap, vm.interns).expect("a path-like always yields a string"); + path.drop_with(vm.heap); + Ok(CallResult::Value(allocate_string(text, vm.heap))) + } + _ => { + let type_name = path.py_type_name_heap(vm.heap, vm.interns).into_owned(); + path.drop_with(vm.heap); + Err(ExcType::type_error_fspath(&type_name)) + } + } +} + +/// `str`/`Path` → [`MontyPath`] for an `os` function's path argument, +/// raising the `path_t` converter's errors with `func`/`arg` naming the +/// callsite (see [`PathArgError`]). +pub(super) fn extract_os_path( + value: &Value, + func: &'static str, + arg: &'static str, + accepts: PathAccepts, + vm: &VM<'_>, +) -> RunResult { + extract_accepted_path(value, accepts, vm).map_err(|err| err.into_error(func, arg)) +} + +/// [`extract_os_path`] with the failure kept as data, for the predicates +/// (a closed fd answers `False`) and `samefile` (the second path's error is +/// raised only after the first stat, as CPython orders them). +pub(super) fn extract_accepted_path( + value: &Value, + accepts: PathAccepts, + vm: &VM<'_>, +) -> Result { + match fd_argument(value, vm) { + // `listdir` reaches its fd through `fdopendir`, whose error names no file + Some(PathArgError::BadFd { .. }) if matches!(accepts, PathAccepts::FdOrNone) => { + Err(PathArgError::BadFd { fd: None }) + } + Some(err) if accepts.allows_fd() => Err(err), + _ => value_to_owned_string(value, vm.heap, vm.interns) + .map(MontyPath::new) + .ok_or_else(|| PathArgError::Type { + accepted: accepts.phrase_for(value, vm).to_owned(), + type_name: value.py_type_name_heap(vm.heap, vm.interns).into_owned(), + }), + } +} + +/// Why a path argument was refused, as plain data so `samefile` can store +/// the second path's error until the first stat has succeeded. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum PathArgError { + /// The `path_t` converter's TypeError: its accepted-types phrase and the + /// rejected type's name. + Type { accepted: String, type_name: String }, + /// An fd, which is always closed in the sandbox: `EBADF`, naming the fd + /// as the argument spelled it unless the call reports none. + BadFd { fd: Option }, + /// An int outside C `int`: `_fd_converter`'s OverflowError. + FdOverflow { above: bool }, +} + +impl PathArgError { + /// The exception, with `func`/`arg` naming the callsite in the TypeError. + pub(crate) fn into_error(self, func: &str, arg: &str) -> RunError { + match self { + Self::Type { accepted, type_name } => ExcType::type_error_os_path(func, arg, &accepted, &type_name), + Self::BadFd { fd } => ExcType::bad_file_descriptor(fd.as_deref()), + Self::FdOverflow { above } => fd_overflow_error(above), + } + } +} + +/// CPython's `_fd_converter` applied to an int or bool (which it fd-converts +/// with only a `RuntimeWarning`): a C-int value is a closed fd, the rest +/// overflow. `None` for any other type. +fn fd_argument(value: &Value, vm: &VM<'_>) -> Option { + match value { + Value::Bool(fd) => Some(PathArgError::BadFd { + fd: Some(if *fd { "True" } else { "False" }.to_owned()), + }), + Value::Int(fd) => Some(match i32::try_from(*fd) { + Ok(_) => PathArgError::BadFd { + fd: Some(fd.to_string()), + }, + Err(_) => PathArgError::FdOverflow { above: *fd > 0 }, + }), + // Big ints (`LongInt`) are outside i64, so far outside C int. + _ => (value.py_type_heap(vm.heap) == Type::Int).then(|| PathArgError::FdOverflow { + above: !value.long_int_is_negative(vm), + }), + } +} + +/// `_fd_converter`'s OverflowError for an int outside C `int`. +fn fd_overflow_error(above: bool) -> RunError { + if above { + ExcType::overflow_fd_maximum() + } else { + ExcType::overflow_fd_minimum() + } +} + +/// Which `path_t` converter kinds an `os` function accepts in CPython. +/// +/// Drives the accepted-types phrase in the converter TypeError. Monty takes +/// `str`/`Path`, and an int where an fd is allowed, so the phrase has two +/// forms: CPython's verbatim (so types CPython also rejects get a +/// byte-identical message) and one without `bytes`, used when the rejected +/// value is `bytes` — otherwise the error would list the very type it just +/// refused. +#[derive(Clone, Copy)] +pub(super) enum PathAccepts { + /// `path_t(allow_fd=False)` — `mkdir`, `remove`, `unlink`, `rmdir`, `rename`. + NoFd, + /// `path_t(allow_fd=True)` — `stat`. + Fd, + /// `path_t(nullable=True, allow_fd=True)` — `listdir`. + FdOrNone, +} + +impl PathAccepts { + /// Whether CPython's converter takes an int as an fd here. + fn allows_fd(self) -> bool { + matches!(self, Self::Fd | Self::FdOrNone) + } + + /// The accepted-types phrase for a value this converter is rejecting. + pub(super) fn phrase_for(self, value: &Value, vm: &VM<'_>) -> &'static str { + // `bytes` paths are the one kind CPython takes and Monty never will; + // everything else keeps CPython's wording exactly. + let refused = value.py_type_heap(vm.heap) == Type::Bytes; + match (self, refused) { + (Self::NoFd, false) => "string, bytes or os.PathLike", + (Self::Fd, false) => "string, bytes, os.PathLike or integer", + (Self::FdOrNone, false) => "string, bytes, os.PathLike, integer or None", + (Self::NoFd, true) => "string or os.PathLike", + (Self::Fd, true) => "string, os.PathLike or integer", + (Self::FdOrNone, true) => "string, os.PathLike, integer or None", + } + } +} + +/// Core `str`/`Path` → [`MontyPath`] extraction; `type_error` supplies the +/// per-callsite wording (the `path_t` converter's or `os.fspath`'s). +fn extract_path(value: &Value, vm: &VM<'_>, type_error: impl FnOnce(&str) -> RunError) -> RunResult { + value_to_owned_string(value, vm.heap, vm.interns).map_or_else( + || Err(type_error(&value.py_type_name_heap(vm.heap, vm.interns))), + |path| Ok(MontyPath::new(path)), + ) +} + +/// Validates a `dir_fd` keyword for the single-fd functions: `None` passes, +/// anything specified is rejected — ints with CPython's platform +/// `NotImplementedError`, other types with the converter TypeError. +fn check_dir_fd(value: &Value, vm: &VM<'_>) -> RunResult<()> { + if dir_fd_specified(value, vm)? { + Err(ExcType::not_implemented_os_arg(None, "dir_fd")) + } else { + Ok(()) + } +} + +/// Type-checks a `dir_fd`-shaped value like CPython's `dir_fd_converter` +/// (`argument should be integer or None, not {type}`; out-of-C-int-range ints +/// raise the fd `OverflowError`), returning whether a (necessarily +/// unsupported) fd was actually supplied. +fn dir_fd_specified(value: &Value, vm: &VM<'_>) -> RunResult { + match (value, fd_argument(value, vm)) { + (Value::None, _) => Ok(false), + (_, Some(PathArgError::FdOverflow { above })) => Err(fd_overflow_error(above)), + (_, Some(_)) => Ok(true), + (_, None) => Err(ExcType::type_error_dir_fd( + &value.py_type_name_heap(vm.heap, vm.interns), + )), + } +} + +/// Validates a `mode` argument as an int fitting C `int`, raising CPython's +/// `'{type}' object cannot be interpreted as an integer` / the C-int +/// `OverflowError`. The value itself is ignored — Monty does not model POSIX +/// permission bits. +pub(crate) fn check_mode(value: &Value, vm: &mut VM<'_>) -> RunResult<()> { + match value { + Value::Bool(_) => Ok(()), + Value::Int(mode) => i32::try_from(*mode).map(|_| ()).map_err(|_| ExcType::overflow_c_int()), + _ => match value.py_type_heap(vm.heap) { + // Big ints (`LongInt`) are outside i64, so far outside C int. + Type::Int => Err(ExcType::overflow_c_int()), + other => { + if let Some(index) = value.py_index_impl(vm)? { + defer_drop!(index, vm); + check_mode(index, vm) + } else { + Err(ExcType::type_error_not_integer(&other.name(vm.heap, vm.interns))) + } + } + }, + } +} diff --git a/crates/bashkit-monty/src/modules/os_path/mod.rs b/crates/bashkit-monty/src/modules/os_path/mod.rs new file mode 100644 index 000000000..765535285 --- /dev/null +++ b/crates/bashkit-monty/src/modules/os_path/mod.rs @@ -0,0 +1,1247 @@ +//! Implementation of the `os.path` module — CPython's `posixpath`, which is +//! also what `import posixpath` yields. +//! +//! The sandbox path model is POSIX on every host, so the pure functions +//! (`join`, `split`, `normpath`, `relpath`, ...) are the `posixpath` +//! algorithms, implemented on bytes in [`posix`] so `str` and `bytes` +//! arguments share one code path. The predicates (`exists`, `isfile`, +//! `isdir`, `islink`) yield the same host calls as the `pathlib.Path` +//! methods, the stat getters (`getsize`, `getmtime`, ...) yield `Path.stat` +//! and pick one field on resume, `realpath` yields `Path.resolve`, and +//! `expanduser` / `expandvars` ask the host for `$HOME` / the environment +//! only when the path actually needs them. + +use std::iter; + +use ahash::AHashMap; +use monty_types::{ + GetenvArgs, MontyObject, MontyPath, OsFunctionCall, ResourceTracker, normalize_virtual_path, + unstable::{self, MontyNode}, +}; +use smallvec::smallvec; + +use crate::{ + args::{ArgValues, FromArgs, LaxBool}, + builtins::{Builtins, BuiltinsFunctions, candidate_wins}, + bytecode::{CallResult, VM}, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{Heap, HeapData, HeapId}, + intern::{StaticStrings, StringId}, + modules::{ + ModuleFunctions, + os::{PathAccepts, PathArgError, extract_accepted_path, extract_os_path}, + }, + os_dispatch::{ + PreConversionEffect, Reshaped, bool_reply, invalid_reply, stat_result_field, value_to_owned_bytes, + value_to_owned_string, + }, + types::{Bytes, Module, PyTrait, Slice, Type, allocate_tuple, collect_iterable, str::allocate_string}, + value::Value, + virtual_path::posix_join, +}; + +pub(crate) mod posix; + +/// `os.path` module functions. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "lowercase")] +pub(crate) enum OsPathFunctions { + Abspath, + Basename, + Commonpath, + Commonprefix, + Dirname, + Exists, + Expanduser, + Expandvars, + Getatime, + Getctime, + Getmtime, + Getsize, + Isabs, + Isdevdrive, + Isdir, + Isfile, + Isjunction, + Islink, + Ismount, + Join, + Lexists, + Normcase, + Normpath, + Realpath, + Relpath, + Samefile, + Samestat, + Split, + Splitdrive, + Splitext, + Splitroot, +} + +/// Creates the `os.path` module (named `posixpath`, as CPython's is) and +/// allocates it on the heap. `os.create_module` hangs one off `os.path`; +/// `import os.path` / `import posixpath` build their own. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + /// Shorthand for the function-attribute entries in the table below. + fn function(f: OsPathFunctions) -> Value { + Value::ModuleFunction(ModuleFunctions::OsPath(f)) + } + + let attrs = [ + (StaticStrings::Abspath, function(OsPathFunctions::Abspath)), + (StaticStrings::Basename, function(OsPathFunctions::Basename)), + (StaticStrings::Commonpath, function(OsPathFunctions::Commonpath)), + (StaticStrings::Commonprefix, function(OsPathFunctions::Commonprefix)), + (StaticStrings::Dirname, function(OsPathFunctions::Dirname)), + (StaticStrings::Exists, function(OsPathFunctions::Exists)), + (StaticStrings::Expanduser, function(OsPathFunctions::Expanduser)), + (StaticStrings::Expandvars, function(OsPathFunctions::Expandvars)), + (StaticStrings::Getatime, function(OsPathFunctions::Getatime)), + (StaticStrings::Getctime, function(OsPathFunctions::Getctime)), + (StaticStrings::Getmtime, function(OsPathFunctions::Getmtime)), + (StaticStrings::Getsize, function(OsPathFunctions::Getsize)), + (StaticStrings::Isabs, function(OsPathFunctions::Isabs)), + (StaticStrings::Isdevdrive, function(OsPathFunctions::Isdevdrive)), + (StaticStrings::Isdir, function(OsPathFunctions::Isdir)), + (StaticStrings::Isfile, function(OsPathFunctions::Isfile)), + (StaticStrings::Isjunction, function(OsPathFunctions::Isjunction)), + (StaticStrings::Islink, function(OsPathFunctions::Islink)), + (StaticStrings::Ismount, function(OsPathFunctions::Ismount)), + (StaticStrings::Lexists, function(OsPathFunctions::Lexists)), + (StaticStrings::Join, function(OsPathFunctions::Join)), + (StaticStrings::Normcase, function(OsPathFunctions::Normcase)), + (StaticStrings::Normpath, function(OsPathFunctions::Normpath)), + (StaticStrings::Realpath, function(OsPathFunctions::Realpath)), + (StaticStrings::Relpath, function(OsPathFunctions::Relpath)), + (StaticStrings::Samefile, function(OsPathFunctions::Samefile)), + (StaticStrings::Samestat, function(OsPathFunctions::Samestat)), + (StaticStrings::Split, function(OsPathFunctions::Split)), + (StaticStrings::Splitdrive, function(OsPathFunctions::Splitdrive)), + (StaticStrings::Splitext, function(OsPathFunctions::Splitext)), + (StaticStrings::Splitroot, function(OsPathFunctions::Splitroot)), + // POSIX constants — the sandbox path model is POSIX on every host. + (StaticStrings::Curdir, Value::InternString(StringId::from_ascii(b'.'))), + ( + StaticStrings::Pardir, + Value::InternString(vm.interns.intern_static(StaticStrings::ParentDirString)), + ), + (StaticStrings::Extsep, Value::InternString(StringId::from_ascii(b'.'))), + (StaticStrings::Sep, Value::InternString(StringId::from_ascii(b'/'))), + (StaticStrings::Pathsep, Value::InternString(StringId::from_ascii(b':'))), + ( + StaticStrings::Defpath, + Value::InternString(vm.interns.intern_static(StaticStrings::DefpathString)), + ), + (StaticStrings::Altsep, Value::None), + ( + StaticStrings::Devnull, + Value::InternString(vm.interns.intern_static(StaticStrings::DevNullString)), + ), + // CPython sets this from `sys.platform == 'darwin'`; the sandbox is never darwin. + (StaticStrings::SupportsUnicodeFilenames, Value::Bool(false)), + ]; + + let mut module = Module::new(StaticStrings::Posixpath, vm.interns); + for (attr, value) in attrs { + module.set_attr(attr, value, vm); + } + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a call to an `os.path` function. +pub(super) fn call(vm: &mut VM<'_>, functions: OsPathFunctions, args: ArgValues) -> RunResult { + match functions { + OsPathFunctions::Abspath => abspath(vm, args).map(CallResult::Value), + OsPathFunctions::Basename => basename(vm, args).map(CallResult::Value), + OsPathFunctions::Commonpath => commonpath(vm, args).map(CallResult::Value), + OsPathFunctions::Commonprefix => commonprefix(vm, args).map(CallResult::Value), + OsPathFunctions::Dirname => dirname(vm, args).map(CallResult::Value), + OsPathFunctions::Exists => exists(vm, args), + OsPathFunctions::Expanduser => expanduser(vm, args), + OsPathFunctions::Expandvars => expandvars(vm, args), + OsPathFunctions::Getatime => getatime(vm, args), + OsPathFunctions::Getctime => getctime(vm, args), + OsPathFunctions::Getmtime => getmtime(vm, args), + OsPathFunctions::Getsize => getsize(vm, args), + OsPathFunctions::Isabs => isabs(vm, args).map(CallResult::Value), + OsPathFunctions::Isdevdrive => isdevdrive(vm, args).map(CallResult::Value), + OsPathFunctions::Isdir => isdir(vm, args), + OsPathFunctions::Isfile => isfile(vm, args), + OsPathFunctions::Isjunction => isjunction(vm, args).map(CallResult::Value), + OsPathFunctions::Islink => islink(vm, args), + OsPathFunctions::Ismount => ismount(vm, args), + OsPathFunctions::Lexists => lexists(vm, args), + OsPathFunctions::Join => join(vm, args).map(CallResult::Value), + OsPathFunctions::Normcase => normcase(vm, args).map(CallResult::Value), + OsPathFunctions::Normpath => normpath(vm, args).map(CallResult::Value), + OsPathFunctions::Realpath => realpath(vm, args), + OsPathFunctions::Relpath => relpath(vm, args).map(CallResult::Value), + OsPathFunctions::Samefile => samefile(vm, args), + OsPathFunctions::Samestat => samestat(vm, args).map(CallResult::Value), + OsPathFunctions::Split => split(vm, args).map(CallResult::Value), + OsPathFunctions::Splitdrive => splitdrive(vm, args).map(CallResult::Value), + OsPathFunctions::Splitext => splitext(vm, args).map(CallResult::Value), + OsPathFunctions::Splitroot => splitroot(vm, args).map(CallResult::Value), + } +} + +// ============================================================================ +// Pure functions +// ============================================================================ + +/// `os.path.join(a, *p)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "join")] +struct JoinArgs { + a: Value, + #[from_args(varargs)] + p: Vec, +} + +/// Implementation of `os.path.join(a, *p)`: one kind of path throughout. +/// Any failure re-inspects the arguments like `genericpath._check_arg_types` +/// (`a` after `os.fspath`, `*p` as passed), so the error names the first +/// non-path argument before complaining about mixed kinds. +fn join(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let JoinArgs { a, p } = JoinArgs::from_args(args, vm)?; + defer_drop!(a, vm); + defer_drop!(p, vm); + let first = PathText::fspath(a, vm)?; + let mut parts = Vec::with_capacity(p.len() + 1); + parts.push(first); + for part in p { + match PathText::fspath(part, vm) { + Ok(text) if text.is_bytes == parts[0].is_bytes => parts.push(text), + _ => { + let kinds = iter::once(parts[0].py_type()).chain(p.iter().map(|arg| arg.py_type_heap(vm.heap))); + return Err(check_arg_types("join", kinds, vm)); + } + } + } + let joined = posix::join(parts.iter().map(|part| part.bytes.as_slice())); + Ok(parts[0].allocate(joined, vm.heap)) +} + +/// `os.path.split(p)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "split", style = def)] +struct SplitArgs { + p: Value, +} + +/// Implementation of `os.path.split(p)`. +fn split(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let SplitArgs { p } = SplitArgs::from_args(args, vm)?; + defer_drop!(p, vm); + let text = PathText::fspath(p, vm)?; + let (head, tail) = posix::split(&text.bytes); + Ok(text.allocate_pair(head, tail, vm.heap)) +} + +/// `os.path.splitext(p)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "splitext", style = def)] +struct SplitextArgs { + p: Value, +} + +/// Implementation of `os.path.splitext(p)`. +fn splitext(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let SplitextArgs { p } = SplitextArgs::from_args(args, vm)?; + defer_drop!(p, vm); + let text = PathText::fspath(p, vm)?; + let (root, ext) = posix::splitext(&text.bytes); + Ok(text.allocate_pair(root, ext, vm.heap)) +} + +/// `os.path.splitdrive(p)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "splitdrive", style = def)] +struct SplitdriveArgs { + p: Value, +} + +/// Implementation of `os.path.splitdrive(p)`: POSIX paths have no drive. +fn splitdrive(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let SplitdriveArgs { p } = SplitdriveArgs::from_args(args, vm)?; + defer_drop!(p, vm); + let text = PathText::fspath(p, vm)?; + Ok(text.allocate_pair(b"", &text.bytes, vm.heap)) +} + +/// `os.path.splitroot(p)` argument shape — CPython's is the C +/// `posix._path_splitroot_ex`, whose clinic wording the errors keep. +#[derive(FromArgs)] +#[from_args(name = "_path_splitroot_ex", style = c_named, at_most_total)] +struct SplitrootArgs { + p: Value, +} + +/// Implementation of `os.path.splitroot(p)`: `(drive, root, tail)` with an +/// always-empty drive. +fn splitroot(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let SplitrootArgs { p } = SplitrootArgs::from_args(args, vm)?; + defer_drop!(p, vm); + let text = PathText::extract(p, vm, |type_name| { + ExcType::type_error_os_path("_path_splitroot_ex", "path", C_PATH_ACCEPTS, type_name) + })?; + let (root, tail) = posix::splitroot(&text.bytes); + let items = smallvec![ + text.allocate(Vec::new(), vm.heap), + text.allocate(root.to_vec(), vm.heap), + text.allocate(tail.to_vec(), vm.heap), + ]; + Ok(allocate_tuple(items, vm.heap)) +} + +/// `os.path.basename(p)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "basename", style = def)] +struct BasenameArgs { + p: Value, +} + +/// Implementation of `os.path.basename(p)`. +fn basename(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let BasenameArgs { p } = BasenameArgs::from_args(args, vm)?; + defer_drop!(p, vm); + let text = PathText::fspath(p, vm)?; + Ok(text.allocate(posix::basename(&text.bytes).to_vec(), vm.heap)) +} + +/// `os.path.dirname(p)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "dirname", style = def)] +struct DirnameArgs { + p: Value, +} + +/// Implementation of `os.path.dirname(p)`. +fn dirname(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let DirnameArgs { p } = DirnameArgs::from_args(args, vm)?; + defer_drop!(p, vm); + let text = PathText::fspath(p, vm)?; + Ok(text.allocate(posix::dirname(&text.bytes).to_vec(), vm.heap)) +} + +/// `os.path.isabs(s)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "isabs", style = def)] +struct IsabsArgs { + s: Value, +} + +/// Implementation of `os.path.isabs(s)`. +fn isabs(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let IsabsArgs { s } = IsabsArgs::from_args(args, vm)?; + defer_drop!(s, vm); + let text = PathText::fspath(s, vm)?; + Ok(Value::Bool(posix::isabs(&text.bytes))) +} + +/// `os.path.normcase(s)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "normcase", style = def)] +struct NormcaseArgs { + s: Value, +} + +/// Implementation of `os.path.normcase(s)`: the identity on POSIX, after `os.fspath`. +fn normcase(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let NormcaseArgs { s } = NormcaseArgs::from_args(args, vm)?; + defer_drop!(s, vm); + let text = PathText::fspath(s, vm)?; + Ok(text.into_value(vm.heap)) +} + +/// `os.path.normpath(path)` argument shape — CPython's is the C +/// `posix._path_normpath`, whose clinic wording the errors keep. +#[derive(FromArgs)] +#[from_args(name = "_path_normpath", style = c_named, at_most_total)] +struct NormpathArgs { + path: Value, +} + +/// Implementation of `os.path.normpath(path)`. +fn normpath(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let NormpathArgs { path } = NormpathArgs::from_args(args, vm)?; + defer_drop!(path, vm); + let text = PathText::extract(path, vm, |type_name| { + ExcType::type_error_os_path("_path_normpath", "path", C_PATH_ACCEPTS, type_name) + })?; + Ok(text.allocate(posix::normpath(&text.bytes), vm.heap)) +} + +/// The accepted-types phrase of the C path converters behind `normpath` and +/// `splitroot`, which take no file descriptor. +const C_PATH_ACCEPTS: &str = "string, bytes or os.PathLike"; + +/// `os.path.abspath(path)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "abspath", style = def)] +struct AbspathArgs { + path: Value, +} + +/// Implementation of `os.path.abspath(path)`: pure, against the sandbox's +/// virtual working directory. +fn abspath(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let AbspathArgs { path } = AbspathArgs::from_args(args, vm)?; + defer_drop!(path, vm); + let text = PathText::fspath(path, vm)?; + Ok(text.allocate(posix::abspath(vm.env.cwd.as_bytes(), &text.bytes), vm.heap)) +} + +/// `os.path.relpath(path, start=None)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "relpath", style = def)] +struct RelpathArgs { + path: Value, + #[from_args(default = Value::None)] + start: Value, +} + +/// Implementation of `os.path.relpath(path, start=None)`: pure, against the +/// sandbox's virtual working directory. `start=None` means `os.curdir`. +fn relpath(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let RelpathArgs { path, start } = RelpathArgs::from_args(args, vm)?; + defer_drop!(path, vm); + defer_drop!(start, vm); + let path_text = PathText::fspath(path, vm)?; + if path_text.bytes.is_empty() { + return Err(ExcType::value_error("no path specified")); + } + let start_text = if matches!(start, Value::None) { + PathText { + bytes: b".".to_vec(), + is_bytes: path_text.is_bytes, + } + } else { + PathText::fspath(start, vm)? + }; + // Both are past `os.fspath`, so CPython's `_check_arg_types` can only report a mix. + if start_text.is_bytes != path_text.is_bytes { + return Err(ExcType::type_error_mixed_path_components()); + } + let relative = posix::relpath(vm.env.cwd.as_bytes(), &path_text.bytes, &start_text.bytes); + Ok(path_text.allocate(relative, vm.heap)) +} + +/// `os.path.commonpath(paths)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "commonpath", style = def)] +struct CommonpathArgs { + paths: Value, +} + +/// Implementation of `os.path.commonpath(paths)`: `os.fspath` over the +/// sequence first, so a non-path element fails before an empty sequence or +/// mixed kinds do. +fn commonpath(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let CommonpathArgs { paths } = CommonpathArgs::from_args(args, vm)?; + defer_drop!(paths, vm); + let items = collect_iterable(paths, vm)?; + defer_drop!(items, vm); + let texts = items + .iter() + .map(|item| PathText::fspath(item, vm)) + .collect::>>()?; + let Some(first) = texts.first() else { + return Err(ExcType::value_error("commonpath() arg is an empty sequence")); + }; + if texts.iter().any(|text| text.is_bytes != first.is_bytes) { + return Err(ExcType::type_error_mixed_path_components()); + } + let slices: Vec<&[u8]> = texts.iter().map(|text| text.bytes.as_slice()).collect(); + let common = posix::commonpath(&slices).map_err(ExcType::value_error)?; + Ok(first.allocate(common, vm.heap)) +} + +/// `os.path.commonprefix(m)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "commonprefix", style = def)] +struct CommonprefixArgs { + m: Value, +} + +/// Implementation of `genericpath.commonprefix(m)`: the longest common +/// leading slice of `min(m)` and `max(m)`. Elements are passed through +/// `os.fspath` unless `m[0]` is a list or tuple, in which case the elements +/// are compared as sequences and the prefix is a slice of the smallest one. +fn commonprefix(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let CommonprefixArgs { m } = CommonprefixArgs::from_args(args, vm)?; + defer_drop!(m, vm); + if !m.py_bool(vm)? { + return Ok(allocate_string("", vm.heap)); + } + let first = m.py_getitem(&Value::Int(0), vm)?; + defer_drop!(first, vm); + let nested = matches!(first.py_type_heap(vm.heap), Type::List | Type::Tuple); + let raw_items = collect_iterable(m, vm)?; + defer_drop!(raw_items, vm); + // Guarded before conversion so a later `os.fspath` failure releases the + // values already converted. + let items = Vec::with_capacity(raw_items.len()); + defer_drop_mut!(items, vm); + for item in raw_items { + items.push(if nested { + item.clone_with_heap(vm) + } else { + PathText::fspath(item, vm)?.into_value(vm.heap) + }); + } + let smallest = extreme(items, true, vm)?; + let largest = extreme(items, false, vm)?; + common_leading_slice(smallest, largest, vm) +} + +/// `min(items)` / `max(items)` by reference: the first item that no later +/// item strictly beats, with `min`'s own `<`-unsupported error. +fn extreme<'a>(items: &'a [Value], is_min: bool, vm: &mut VM<'_>) -> RunResult<&'a Value> { + let mut best = &items[0]; + for item in &items[1..] { + if candidate_wins(best, item, is_min, vm)? { + best = item; + } + } + Ok(best) +} + +/// `s1[:i]` for the first `i` where `s1[i] != s2[i]`, or `s1` itself when +/// there is none (CPython returns the very object, so a list prefix of one +/// list is that list). Strings slice by code point and bytes by byte; +/// anything else is iterated and indexed like CPython does it (so a dict's +/// int keys raise `TypeError`), with `==` on the elements. +fn common_leading_slice(s1: &Value, s2: &Value, vm: &mut VM<'_>) -> RunResult { + match (s1.py_type_heap(vm.heap), s2.py_type_heap(vm.heap)) { + (Type::Str, Type::Str) => { + let a = value_to_owned_string(s1, vm.heap, vm.interns).expect("checked str"); + let b = value_to_owned_string(s2, vm.heap, vm.interns).expect("checked str"); + let mismatch = a.char_indices().zip(b.chars()).find(|((_, x), y)| x != y); + Ok(match mismatch { + Some(((end, _), _)) => allocate_string(&a[..end], vm.heap), + None => s1.clone_with_heap(vm), + }) + } + (Type::Bytes, Type::Bytes) => { + let a = value_to_owned_bytes(s1, vm.heap, vm.interns).expect("checked bytes"); + let b = value_to_owned_bytes(s2, vm.heap, vm.interns).expect("checked bytes"); + Ok(match a.iter().zip(&b).position(|(x, y)| x != y) { + Some(end) => Value::Ref(vm.heap.allocate(HeapData::Bytes(Bytes::new(a[..end].to_vec())))), + None => s1.clone_with_heap(vm), + }) + } + _ => { + let elements = collect_iterable(s1, vm)?; + defer_drop!(elements, vm); + let mut mismatch = None; + for (i, element) in elements.iter().enumerate() { + let other = s2.py_getitem(&Value::Int(i64::try_from(i).expect("sequence index fits i64")), vm)?; + defer_drop!(other, vm); + if !element.py_eq_operator(other, vm)? { + mismatch = Some(i); + break; + } + } + match mismatch { + Some(end) => { + let stop = i64::try_from(end).expect("sequence index fits i64"); + let slice = Value::Ref(vm.heap.allocate(HeapData::Slice(Slice::new(None, Some(stop), None)))); + defer_drop!(slice, vm); + s1.py_getitem(slice, vm) + } + None => Ok(s1.clone_with_heap(vm)), + } + } + } +} + +/// `os.path.isjunction(path)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "isjunction", style = def)] +struct IsjunctionArgs { + path: Value, +} + +/// Implementation of `os.path.isjunction(path)`: junctions are a Windows +/// concept, so this is `False` once `os.fspath` accepts the argument. +fn isjunction(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let IsjunctionArgs { path } = IsjunctionArgs::from_args(args, vm)?; + defer_drop!(path, vm); + PathText::fspath(path, vm)?; + Ok(Value::Bool(false)) +} + +/// `os.path.isdevdrive(path)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "isdevdrive", style = def)] +struct IsdevdriveArgs { + path: Value, +} + +/// Implementation of `os.path.isdevdrive(path)`: Dev Drives are a Windows +/// concept, so this is `False` once `os.fspath` accepts the argument. +fn isdevdrive(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let IsdevdriveArgs { path } = IsdevdriveArgs::from_args(args, vm)?; + defer_drop!(path, vm); + PathText::fspath(path, vm)?; + Ok(Value::Bool(false)) +} + +/// `os.path.samestat(s1, s2)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "samestat", style = def)] +struct SamestatArgs { + s1: Value, + s2: Value, +} + +/// Implementation of `os.path.samestat(s1, s2)`: +/// `s1.st_ino == s2.st_ino and s1.st_dev == s2.st_dev`, evaluated in that +/// order so a missing attribute is reported as CPython reports it. +fn samestat(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let SamestatArgs { s1, s2 } = SamestatArgs::from_args(args, vm)?; + defer_drop!(s1, vm); + defer_drop!(s2, vm); + let same = + attributes_equal(s1, s2, StaticStrings::StIno, vm)? && attributes_equal(s1, s2, StaticStrings::StDev, vm)?; + Ok(Value::Bool(same)) +} + +/// `a.attr == b.attr` for a plain data attribute. +fn attributes_equal(a: &Value, b: &Value, attr: StaticStrings, vm: &mut VM<'_>) -> RunResult { + let x = data_attribute(a, attr, vm)?; + defer_drop!(x, vm); + let y = data_attribute(b, attr, vm)?; + defer_drop!(y, vm); + x.py_eq_operator(y, vm) +} + +/// `getattr(value, attr)` through the synchronous call path, so any +/// stat-like object works; a lazy host attribute reads as absent there. +fn data_attribute(value: &Value, attr: StaticStrings, vm: &mut VM<'_>) -> RunResult { + let name = Value::InternString(vm.interns.intern_static(attr)); + let getattr = Value::Builtin(Builtins::Function(BuiltinsFunctions::Getattr)); + vm.evaluate_function(&getattr, ArgValues::Two(value.clone_with_heap(vm), name)) +} + +// ============================================================================ +// Host-backed functions +// ============================================================================ + +/// `os.path.exists(path)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "exists", style = def)] +struct ExistsArgs { + path: Value, +} + +/// Implementation of `os.path.exists(path)` — the `Path.exists` host call. +fn exists(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ExistsArgs { path } = ExistsArgs::from_args(args, vm)?; + defer_drop!(path, vm); + predicate(path, "stat", PathAccepts::Fd, OsFunctionCall::Exists, vm) +} + +/// `os.path.isfile(path)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "isfile", style = def)] +struct IsfileArgs { + path: Value, +} + +/// Implementation of `os.path.isfile(path)` — the `Path.is_file` host call. +fn isfile(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let IsfileArgs { path } = IsfileArgs::from_args(args, vm)?; + defer_drop!(path, vm); + predicate(path, "stat", PathAccepts::Fd, OsFunctionCall::IsFile, vm) +} + +/// `os.path.isdir(s)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "isdir", style = def)] +struct IsdirArgs { + s: Value, +} + +/// Implementation of `os.path.isdir(s)` — the `Path.is_dir` host call. +fn isdir(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let IsdirArgs { s } = IsdirArgs::from_args(args, vm)?; + defer_drop!(s, vm); + predicate(s, "stat", PathAccepts::Fd, OsFunctionCall::IsDir, vm) +} + +/// `os.path.islink(path)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "islink", style = def)] +struct IslinkArgs { + path: Value, +} + +/// Implementation of `os.path.islink(path)` — the `Path.is_symlink` host +/// call. CPython reaches it through `os.lstat`, whose converter takes no fd. +fn islink(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let IslinkArgs { path } = IslinkArgs::from_args(args, vm)?; + defer_drop!(path, vm); + predicate(path, "lstat", PathAccepts::NoFd, OsFunctionCall::IsSymlink, vm) +} + +/// `os.path.ismount(path)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "ismount", style = def)] +struct IsmountArgs { + path: Value, +} + +/// Implementation of `os.path.ismount(path)`: every existing path counts as a +/// mount point, so this is the `Path.exists` host call. The sandbox cannot +/// see where the host's mounts begin, and answering `True` is what keeps the +/// usual "walk up until a mount point" loops terminating. +fn ismount(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let IsmountArgs { path } = IsmountArgs::from_args(args, vm)?; + defer_drop!(path, vm); + predicate(path, "lstat", PathAccepts::NoFd, OsFunctionCall::Exists, vm) +} + +/// `os.path.lexists(path)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "lexists", style = def)] +struct LexistsArgs { + path: Value, +} + +/// Implementation of `os.path.lexists(path)`: `Path.exists`, and when that is +/// `False`, `Path.is_symlink` (a dangling symlink exists without a target); +/// see [`PreConversionEffect::Lexists`]. +fn lexists(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let LexistsArgs { path } = LexistsArgs::from_args(args, vm)?; + defer_drop!(path, vm); + let path = extract_os_path(path, "lstat", "path", PathAccepts::NoFd, vm)?; + if path.is_empty() { + Ok(CallResult::Value(Value::Bool(false))) + } else { + Ok(CallResult::OsCallWithEffect { + effect: PreConversionEffect::Lexists { + path: path.as_str().to_owned(), + } + .into(), + call: OsFunctionCall::Exists(path), + }) + } +} + +/// Completes `os.path.lexists` from the `Path.exists` reply — the resume half +/// of [`PreConversionEffect::Lexists`]. `False` may still be a dangling +/// symlink, which `Path.is_symlink` reports. +pub(crate) fn lexists_reply(value: &MontyObject, path: String) -> Result { + Ok(if bool_reply(value, "os.path.lexists")? { + Reshaped::Value(MontyObject::bool(true)) + } else { + Reshaped::Call { + call: OsFunctionCall::IsSymlink(MontyPath::new(path)), + effect: None, + } + }) +} + +/// `os.path.samefile(f1, f2)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "samefile", style = def)] +struct SamefileArgs { + f1: Value, + f2: Value, +} + +/// Implementation of `os.path.samefile(f1, f2)`: `Path.stat` on each in turn, +/// then `samestat` on the replies (see [`PreConversionEffect::SamefileFirst`]). +/// `f2` is extracted now but its errors are deferred to after the first +/// stat, which is when CPython's `os.stat(f2)` would raise them. +fn samefile(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let SamefileArgs { f1, f2 } = SamefileArgs::from_args(args, vm)?; + defer_drop!(f1, vm); + defer_drop!(f2, vm); + let first = extract_os_path(f1, "stat", "path", PathAccepts::Fd, vm)?; + if first.is_empty() { + return Err(ExcType::file_not_found_error("")); + } + let second = extract_accepted_path(f2, PathAccepts::Fd, vm).map(|path| path.as_str().to_owned()); + Ok(CallResult::OsCallWithEffect { + effect: PreConversionEffect::SamefileFirst { + first: first.as_str().to_owned(), + second, + } + .into(), + call: OsFunctionCall::Stat(first), + }) +} + +/// Moves `os.path.samefile` from its first `Path.stat` to its second — the +/// resume half of [`PreConversionEffect::SamefileFirst`]. The second path's +/// deferred converter error and `FileNotFoundError` for the empty path raise +/// here, where CPython's `os.stat(f2)` raises them. +pub(crate) fn samefile_first_reply( + value: &MontyObject, + first: String, + second: Result, +) -> Result { + let first_identity = + stat_identity(value).ok_or_else(|| invalid_reply("os.path.samefile", "a stat result", value))?; + let second = match second { + Ok(second) if second.is_empty() => return Err(ExcType::file_not_found_error("")), + Ok(second) => second, + Err(err) => return Err(err.into_error("stat", "path")), + }; + Ok(Reshaped::Call { + call: OsFunctionCall::Stat(MontyPath::new(second.clone())), + effect: Some( + PreConversionEffect::SamefileSecond { + first, + first_identity, + second, + } + .into(), + ), + }) +} + +/// Completes `os.path.samefile` from the second `Path.stat` reply — the +/// resume half of [`PreConversionEffect::SamefileSecond`]. CPython compares +/// `(st_ino, st_dev)`; mounts report both as zero, so when neither reply +/// carries an identity the normalized virtual paths decide instead. +pub(crate) fn samefile_second_reply( + value: &MontyObject, + first: &str, + first_identity: &(String, String), + second: &str, + cwd: &str, +) -> Result { + let second_identity = + stat_identity(value).ok_or_else(|| invalid_reply("os.path.samefile", "a stat result", value))?; + let unknown = |identity: &(String, String)| identity.0 == "0" && identity.1 == "0"; + let same = if unknown(first_identity) && unknown(&second_identity) { + normalize_virtual_path(&posix_join(cwd, first)) == normalize_virtual_path(&posix_join(cwd, second)) + } else { + *first_identity == second_identity + }; + Ok(MontyObject::bool(same)) +} + +/// `(st_ino, st_dev)` of a `Path.stat` reply as decimal text, `None` unless +/// both are ints (of either width, as the stat getters accept them). +fn stat_identity(value: &MontyObject) -> Option<(String, String)> { + let number = |name: &str| match stat_result_field(value, name)? { + MontyNode::Int(int) => Some(int.to_string()), + MontyNode::BigInt(int) => Some(int.to_string()), + _ => None, + }; + Some((number("st_ino")?, number("st_dev")?)) +} + +/// Shared body of the predicates: the `os.stat` / `os.lstat` converter +/// error for a bad type, `False` for a closed fd and for the empty path +/// (which CPython's `stat` fails on without the host's help), else the host +/// call. A NUL byte is answered `False` by the VM before the call leaves the +/// sandbox. +fn predicate( + path: &Value, + func: &'static str, + accepts: PathAccepts, + make_call: impl FnOnce(MontyPath) -> OsFunctionCall, + vm: &VM<'_>, +) -> RunResult { + match extract_accepted_path(path, accepts, vm) { + Err(PathArgError::BadFd { .. }) => Ok(CallResult::Value(Value::Bool(false))), + Err(err) => Err(err.into_error(func, "path")), + Ok(path) if path.is_empty() => Ok(CallResult::Value(Value::Bool(false))), + Ok(path) => Ok(CallResult::OsCall(make_call(path))), + } +} + +/// `os.path.getsize(filename)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "getsize", style = def)] +struct GetsizeArgs { + filename: Value, +} + +/// Implementation of `os.path.getsize(filename)`: `os.stat(filename).st_size`. +fn getsize(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let GetsizeArgs { filename } = GetsizeArgs::from_args(args, vm)?; + defer_drop!(filename, vm); + stat_field(filename, StatField::Size, vm) +} + +/// `os.path.getmtime(filename)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "getmtime", style = def)] +struct GetmtimeArgs { + filename: Value, +} + +/// Implementation of `os.path.getmtime(filename)`: `os.stat(filename).st_mtime`. +fn getmtime(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let GetmtimeArgs { filename } = GetmtimeArgs::from_args(args, vm)?; + defer_drop!(filename, vm); + stat_field(filename, StatField::Mtime, vm) +} + +/// `os.path.getatime(filename)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "getatime", style = def)] +struct GetatimeArgs { + filename: Value, +} + +/// Implementation of `os.path.getatime(filename)`: `os.stat(filename).st_atime`. +fn getatime(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let GetatimeArgs { filename } = GetatimeArgs::from_args(args, vm)?; + defer_drop!(filename, vm); + stat_field(filename, StatField::Atime, vm) +} + +/// `os.path.getctime(filename)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "getctime", style = def)] +struct GetctimeArgs { + filename: Value, +} + +/// Implementation of `os.path.getctime(filename)`: `os.stat(filename).st_ctime`. +fn getctime(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let GetctimeArgs { filename } = GetctimeArgs::from_args(args, vm)?; + defer_drop!(filename, vm); + stat_field(filename, StatField::Ctime, vm) +} + +/// Shared body of the stat getters: the `Path.stat` host call with a +/// [`PreConversionEffect::StatField`] that keeps one field of the reply. The +/// empty path fails as CPython's `stat('')` does, without consulting the host. +fn stat_field(path: &Value, field: StatField, vm: &VM<'_>) -> RunResult { + let path = extract_os_path(path, "stat", "path", PathAccepts::Fd, vm)?; + if path.is_empty() { + Err(ExcType::file_not_found_error("")) + } else { + Ok(CallResult::OsCallWithEffect { + call: OsFunctionCall::Stat(path), + effect: PreConversionEffect::StatField(field).into(), + }) + } +} + +/// The `os.stat` result field an `os.path` getter returns. +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +pub(crate) enum StatField { + /// `os.path.getsize` → `st_size`. + Size, + /// `os.path.getmtime` → `st_mtime`. + Mtime, + /// `os.path.getatime` → `st_atime`. + Atime, + /// `os.path.getctime` → `st_ctime`. + Ctime, +} + +impl StatField { + /// The stat result field name. + fn name(self) -> &'static str { + match self { + Self::Size => "st_size", + Self::Mtime => "st_mtime", + Self::Atime => "st_atime", + Self::Ctime => "st_ctime", + } + } + + /// The `os.path` function that asked for the field, for error messages. + pub(crate) fn function(self) -> &'static str { + match self { + Self::Size => "os.path.getsize", + Self::Mtime => "os.path.getmtime", + Self::Atime => "os.path.getatime", + Self::Ctime => "os.path.getctime", + } + } +} + +/// Picks `field` out of a host `Path.stat` reply — the resume half of +/// [`PreConversionEffect::StatField`]. Only a number is accepted, so a host +/// that answered with something other than a stat result gets the same +/// `RuntimeError` shape as `os.chdir`. +pub(crate) fn stat_field_reply(value: &MontyObject, field: StatField) -> Result { + match stat_result_field(value, field.name()) { + Some(number @ (MontyNode::Int(_) | MontyNode::BigInt(_) | MontyNode::Float(_))) => { + Ok(unstable::object_from_node(number.clone())) + } + _ => Err(invalid_reply(field.function(), "a stat result", value)), + } +} + +/// `os.path.realpath(filename, *, strict=False)` argument shape. `strict` is +/// truth-tested like CPython's, hence [`LaxBool`]. +#[derive(FromArgs)] +#[from_args(name = "realpath", style = def)] +struct RealpathArgs { + filename: Value, + #[from_args(kw_only, default = LaxBool::new(false))] + strict: LaxBool, +} + +/// Implementation of `os.path.realpath(filename)` — the `Path.resolve` host +/// call, with a [`PreConversionEffect::ResolvedPath`] turning the host's path +/// reply into `str` and, under `strict`, chaining the existence check. The +/// empty path is `os.getcwd()` without a call, as in CPython; the sandbox's +/// working directory is session state, so there is nothing to check. +fn realpath(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let RealpathArgs { filename, strict } = RealpathArgs::from_args(args, vm)?; + defer_drop!(filename, vm); + let text = PathText::fspath(filename, vm)?; + if text.is_bytes { + // The host boundary takes `str` paths only, like every `os` function. + let accepted = PathAccepts::NoFd.phrase_for(filename, vm); + return Err(ExcType::type_error_os_path("lstat", "path", accepted, "bytes")); + } + if text.bytes.is_empty() { + Ok(CallResult::Value(allocate_string(&*vm.env.cwd, vm.heap))) + } else { + let path = String::from_utf8(text.bytes).expect("str input"); + Ok(CallResult::OsCallWithEffect { + call: OsFunctionCall::Resolve(MontyPath::new(path)), + effect: PreConversionEffect::ResolvedPath { strict: strict.bool() }.into(), + }) + } +} + +/// Turns a `Path.resolve` reply into the `str` that `os.path.realpath` +/// returns — the resume half of [`PreConversionEffect::ResolvedPath`]. A +/// host answering the callback itself may already return `str`. Under +/// `strict`, mounts resolve lexically and never report a missing path, so a +/// `Path.exists` call on the result follows. +pub(crate) fn resolved_path_reply(value: &MontyObject, strict: bool) -> Result { + let resolved = match unstable::root_node(value) { + MontyNode::Path(path) | MontyNode::String(path) => path.clone(), + _ => return Err(invalid_reply("os.path.realpath", "a path", value)), + }; + // The VM answers an existence check on a NUL path with `False`, which + // would become `realpath`'s result; CPython's strict `lstat` raises. + if strict && resolved.contains('\0') { + let call = OsFunctionCall::Resolve(MontyPath::new(resolved)); + return Err(ExcType::value_error(call.embedded_null_message(false))); + } + Ok(if strict { + Reshaped::Call { + call: OsFunctionCall::Exists(MontyPath::new(resolved.clone())), + effect: Some(PreConversionEffect::RealpathStrict { resolved }.into()), + } + } else { + Reshaped::Value(MontyObject::string(resolved)) + }) +} + +/// Completes `os.path.realpath(strict=True)` from the `Path.exists` reply on +/// the resolved path — the resume half of [`PreConversionEffect::RealpathStrict`]. +pub(crate) fn realpath_strict_reply(value: &MontyObject, resolved: String) -> Result { + if bool_reply(value, "os.path.realpath")? { + Ok(MontyObject::string(resolved)) + } else { + Err(ExcType::file_not_found_error(&resolved)) + } +} + +/// `os.path.expanduser(path)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "expanduser", style = def)] +struct ExpanduserArgs { + path: Value, +} + +/// Implementation of `os.path.expanduser(path)`. Only a leading `~` (bare or +/// followed by `/`) needs the host: it becomes an `os.getenv('HOME')` call +/// with a [`PreConversionEffect::ExpandUser`] splicing the answer in. `~user` +/// needs the password database, which the sandbox has no access to, so it is +/// returned unchanged as CPython does for an unknown user. +fn expanduser(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ExpanduserArgs { path } = ExpanduserArgs::from_args(args, vm)?; + defer_drop!(path, vm); + let text = PathText::fspath(path, vm)?; + if posix::tilde_end(&text.bytes) == Some(1) { + Ok(CallResult::OsCallWithEffect { + call: OsFunctionCall::Getenv(GetenvArgs { + key: "HOME".to_owned(), + default: MontyObject::none(), + }), + effect: PreConversionEffect::ExpandUser { + tail: text.bytes[1..].to_vec(), + is_bytes: text.is_bytes, + } + .into(), + }) + } else { + Ok(CallResult::Value(text.into_value(vm.heap))) + } +} + +/// Completes `os.path.expanduser` from the `os.getenv('HOME')` reply — the +/// resume half of [`PreConversionEffect::ExpandUser`]. `None` (no `$HOME`) +/// returns the path as written, since the sandbox has no password database +/// to fall back on. +pub(crate) fn expand_user_reply(value: &MontyObject, tail: &[u8], is_bytes: bool) -> Result { + match unstable::root_node(value) { + MontyNode::None => Ok(text_reply([b"~", tail].concat(), is_bytes)), + MontyNode::String(home) => Ok(text_reply(posix::expand_home(home.as_bytes(), tail), is_bytes)), + _ => Err(invalid_reply("os.path.expanduser", "str or None", value)), + } +} + +/// `os.path.expandvars(path)` argument shape. +#[derive(FromArgs)] +#[from_args(name = "expandvars", style = def)] +struct ExpandvarsArgs { + path: Value, +} + +/// Implementation of `os.path.expandvars(path)`. A path without `$` is +/// returned as is; otherwise the host's `os.environ` is fetched and a +/// [`PreConversionEffect::ExpandVars`] performs the substitution on resume. +fn expandvars(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ExpandvarsArgs { path } = ExpandvarsArgs::from_args(args, vm)?; + defer_drop!(path, vm); + let text = PathText::fspath(path, vm)?; + if text.bytes.contains(&b'$') { + Ok(CallResult::OsCallWithEffect { + call: OsFunctionCall::GetEnviron, + effect: PreConversionEffect::ExpandVars { + path: text.bytes, + is_bytes: text.is_bytes, + } + .into(), + }) + } else { + Ok(CallResult::Value(text.into_value(vm.heap))) + } +} + +/// Completes `os.path.expandvars` from the `os.environ` reply — the resume +/// half of [`PreConversionEffect::ExpandVars`]. Entries whose key or value +/// is not `str` cannot be named by a path, so they are ignored. The reply is +/// indexed once, so the work stays linear in the (sandbox-sized) path rather +/// than one environment scan per `$reference`, and the result's growth is +/// charged to `tracker` since many references to a long value amplify it. +pub(crate) fn expand_vars_reply( + value: &MontyObject, + path: &[u8], + is_bytes: bool, + tracker: &ResourceTracker, +) -> Result { + let MontyNode::Dict(entries) = unstable::root_node(value) else { + return Err(invalid_reply("os.path.expandvars", "a dict", value)); + }; + let environ: AHashMap<&[u8], &[u8]> = entries + .iter() + .filter_map(|(key, item)| { + match ( + unstable::node(unstable::child(value.as_ref(), *key)), + unstable::node(unstable::child(value.as_ref(), *item)), + ) { + (MontyNode::String(key), MontyNode::String(item)) => Some((key.as_bytes(), item.as_bytes())), + _ => None, + } + }) + .collect(); + let lookup = |name: &[u8]| environ.get(name).copied(); + let reserve = |bytes: usize| tracker.check_allocation(bytes).map_err(RunError::from); + Ok(text_reply(posix::expandvars(path, lookup, reserve)?, is_bytes)) +} + +/// Builds an `os.path` reply of the type the argument had. `str` arguments +/// only ever gain `str` host data at ASCII separators, so the bytes stay UTF-8. +fn text_reply(bytes: Vec, is_bytes: bool) -> MontyObject { + if is_bytes { + MontyObject::bytes(bytes) + } else { + MontyObject::string(String::from_utf8(bytes).expect("str path data stays UTF-8")) + } +} + +// ============================================================================ +// Argument plumbing +// ============================================================================ + +/// A path argument after `os.fspath`: its bytes, and whether it arrived as +/// `bytes` — results are built with the same type the argument had. +struct PathText { + bytes: Vec, + is_bytes: bool, +} + +impl PathText { + /// `os.fspath(value)`: `str` and `Path` give text, `bytes` gives bytes, + /// anything else raises the error `type_error` builds from its type name. + fn extract(value: &Value, vm: &VM<'_>, type_error: impl FnOnce(&str) -> RunError) -> RunResult { + if let Some(text) = value_to_owned_string(value, vm.heap, vm.interns) { + Ok(Self { + bytes: text.into_bytes(), + is_bytes: false, + }) + } else if let Some(bytes) = value_to_owned_bytes(value, vm.heap, vm.interns) { + Ok(Self { bytes, is_bytes: true }) + } else { + Err(type_error(&value.py_type_name_heap(vm.heap, vm.interns))) + } + } + + /// [`Self::extract`] with `os.fspath`'s own error wording. + fn fspath(value: &Value, vm: &VM<'_>) -> RunResult { + Self::extract(value, vm, ExcType::type_error_fspath) + } + + /// The type `os.fspath` produced, for `check_arg_types`. + fn py_type(&self) -> Type { + if self.is_bytes { Type::Bytes } else { Type::Str } + } + + /// Allocates `bytes` as the type this argument arrived with. + fn allocate(&self, bytes: Vec, heap: &Heap) -> Value { + allocate_text(bytes, self.is_bytes, heap) + } + + /// Allocates the argument itself, unchanged, as the type it arrived with. + fn into_value(self, heap: &Heap) -> Value { + allocate_text(self.bytes, self.is_bytes, heap) + } + + /// A two-tuple of [`Self::allocate`]d results, for `split` and friends. + fn allocate_pair(&self, first: &[u8], second: &[u8], heap: &Heap) -> Value { + let items = smallvec![ + self.allocate(first.to_vec(), heap), + self.allocate(second.to_vec(), heap) + ]; + allocate_tuple(items, heap) + } +} + +/// `bytes` as a `bytes` value, or as the `str` it was sliced from. +fn allocate_text(bytes: Vec, is_bytes: bool, heap: &Heap) -> Value { + if is_bytes { + Value::Ref(heap.allocate(HeapData::Bytes(Bytes::new(bytes)))) + } else { + let text = String::from_utf8(bytes).expect("path algorithms split at ASCII separators, preserving UTF-8"); + allocate_string(text, heap) + } +} + +/// `genericpath._check_arg_types`: the error for a path operation that +/// failed on its arguments, given their types. The first that is neither +/// `str` nor `bytes` is named, else the arguments mixed `str` and `bytes`. +/// Callers pass the type `os.fspath` produced for the arguments CPython +/// rebinds before the check, and the raw type (a `Path` included) otherwise. +fn check_arg_types(func: &str, kinds: impl IntoIterator, vm: &VM<'_>) -> RunError { + for kind in kinds { + match kind { + Type::Str | Type::Bytes => {} + other => return ExcType::type_error_path_argument(func, &other.dunder_name(vm.heap, vm.interns)), + } + } + ExcType::type_error_mixed_path_components() +} diff --git a/crates/bashkit-monty/src/modules/os_path/posix.rs b/crates/bashkit-monty/src/modules/os_path/posix.rs new file mode 100644 index 000000000..3f9f0c498 --- /dev/null +++ b/crates/bashkit-monty/src/modules/os_path/posix.rs @@ -0,0 +1,253 @@ +//! The `posixpath` algorithms, on bytes. +//! +//! Each function mirrors the CPython 3.14 `posixpath` / `genericpath` +//! function of the same name. They work on `&[u8]` because `os.path` accepts +//! `str` and `bytes` alike and only ever splits at ASCII separators (`/`, +//! `.`), so one implementation serves both and slicing cannot break UTF-8. +//! Nothing here touches the VM: the module layer owns argument extraction, +//! allocation and host calls. + +/// `os.path.isabs`: a leading `/`. +pub(super) fn isabs(path: &[u8]) -> bool { + path.starts_with(b"/") +} + +/// `os.path.split`: `(head, tail)` around the last `/`, with trailing +/// slashes stripped from `head` unless it is all slashes. +pub(super) fn split(path: &[u8]) -> (&[u8], &[u8]) { + let (head, tail) = path.split_at(tail_start(path)); + (strip_trailing_slashes(head), tail) +} + +/// `os.path.basename`: everything after the last `/`. +pub(super) fn basename(path: &[u8]) -> &[u8] { + &path[tail_start(path)..] +} + +/// `os.path.dirname`: everything before the last `/`, trailing slashes +/// stripped unless the head is the root. +pub(super) fn dirname(path: &[u8]) -> &[u8] { + strip_trailing_slashes(&path[..tail_start(path)]) +} + +/// Index just past the last `/`, or 0 when there is none. +fn tail_start(path: &[u8]) -> usize { + path.iter().rposition(|&c| c == b'/').map_or(0, |i| i + 1) +} + +/// `head.rstrip('/')` unless `head` is empty or entirely slashes. +fn strip_trailing_slashes(head: &[u8]) -> &[u8] { + if head.iter().all(|&c| c == b'/') { + head + } else { + let end = head.iter().rposition(|&c| c != b'/').map_or(0, |i| i + 1); + &head[..end] + } +} + +/// `os.path.splitext`: `(root, ext)` where `ext` starts at the last `.` of +/// the final component, unless that component is nothing but leading dots. +pub(super) fn splitext(path: &[u8]) -> (&[u8], &[u8]) { + let sep_index = path.iter().rposition(|&c| c == b'/'); + let dot_index = path.iter().rposition(|&c| c == b'.'); + if let Some(dot) = dot_index + && sep_index.is_none_or(|sep| dot > sep) + { + // Leading dots name a hidden file rather than an extension. + let filename_start = sep_index.map_or(0, |sep| sep + 1); + if path[filename_start..dot].iter().any(|&c| c != b'.') { + return path.split_at(dot); + } + } + (path, &path[..0]) +} + +/// `os.path.splitroot` without the always-empty drive: `(root, tail)`, where +/// the root is `/`, exactly `//` (implementation-defined per POSIX), or empty. +pub(super) fn splitroot(path: &[u8]) -> (&[u8], &[u8]) { + if !path.starts_with(b"/") { + (&path[..0], path) + } else if path.get(1) != Some(&b'/') || path.get(2) == Some(&b'/') { + path.split_at(1) + } else { + path.split_at(2) + } +} + +/// `os.path.normpath`: collapse `//`, `.` and `..` lexically. A leading `..` +/// survives in relative paths and is dropped under the root. +pub(super) fn normpath(path: &[u8]) -> Vec { + if path.is_empty() { + return b".".to_vec(); + } + let (root, rest) = splitroot(path); + let mut components: Vec<&[u8]> = Vec::new(); + for component in rest.split(|&c| c == b'/') { + match component { + b"" | b"." => {} + b".." if !root.is_empty() || components.last().is_some_and(|last| *last != b"..") => { + components.pop(); + } + component => components.push(component), + } + } + let mut out = root.to_vec(); + out.extend(components.join(&b'/')); + if out.is_empty() { + out.push(b'.'); + } + out +} + +/// `os.path.join`: an absolute part discards everything before it; a `/` is +/// inserted between parts unless the accumulated path is empty or already +/// ends in one. +pub(super) fn join<'a>(parts: impl IntoIterator) -> Vec { + let mut path = Vec::new(); + for part in parts { + if part.starts_with(b"/") || path.is_empty() { + path.clear(); + } else if !path.ends_with(b"/") { + path.push(b'/'); + } + path.extend_from_slice(part); + } + path +} + +/// `os.path.abspath` against a known working directory: join then normalize. +pub(super) fn abspath(cwd: &[u8], path: &[u8]) -> Vec { + if isabs(path) { + normpath(path) + } else { + normpath(&join([cwd, path])) + } +} + +/// `os.path.relpath`: `path` relative to `start`, both made absolute against +/// `cwd` first. `..` climbs out of the components `start` does not share. +pub(super) fn relpath(cwd: &[u8], path: &[u8], start: &[u8]) -> Vec { + let start_list = absolute_components(cwd, start); + let path_list = absolute_components(cwd, path); + let shared = start_list.iter().zip(&path_list).take_while(|(a, b)| a == b).count(); + let climbs = start_list.len() - shared; + let parts: Vec<&[u8]> = (0..climbs) + .map(|_| &b".."[..]) + .chain(path_list[shared..].iter().map(Vec::as_slice)) + .collect(); + if parts.is_empty() { + b".".to_vec() + } else { + parts.join(&b'/') + } +} + +/// The components of `abspath(path)` with the leading slashes removed. +fn absolute_components(cwd: &[u8], path: &[u8]) -> Vec> { + let absolute = abspath(cwd, path); + let tail = &absolute[absolute.iter().position(|&c| c != b'/').unwrap_or(absolute.len())..]; + if tail.is_empty() { + Vec::new() + } else { + tail.split(|&c| c == b'/').map(<[u8]>::to_vec).collect() + } +} + +/// `os.path.commonpath` over non-empty `paths` of one kind: the longest +/// shared component prefix, comparing the lexicographically smallest and +/// largest component lists. Errors when absolute and relative paths mix. +pub(super) fn commonpath(paths: &[&[u8]]) -> Result, &'static str> { + let absolute = isabs(paths[0]); + if paths.iter().any(|path| isabs(path) != absolute) { + return Err("Can't mix absolute and relative paths"); + } + let split_paths: Vec> = paths + .iter() + .map(|path| { + path.split(|&c| c == b'/') + .filter(|component| !component.is_empty() && *component != b".") + .collect() + }) + .collect(); + let smallest = split_paths.iter().min().expect("caller rejects an empty sequence"); + let largest = split_paths.iter().max().expect("caller rejects an empty sequence"); + let shared = smallest.iter().zip(largest).take_while(|(a, b)| a == b).count(); + let mut out = if absolute { b"/".to_vec() } else { Vec::new() }; + out.extend(smallest[..shared].join(&b'/')); + Ok(out) +} + +/// Where `~`-expansion's user part ends: `Some(i)` for a path starting with +/// `~`, `i` being the index of the first `/` (or the length). `i == 1` is the +/// bare `~` form `expanduser` serves from `$HOME`. +pub(super) fn tilde_end(path: &[u8]) -> Option { + path.starts_with(b"~") + .then(|| path[1..].iter().position(|&c| c == b'/').map_or(path.len(), |i| i + 1)) +} + +/// `os.path.expanduser` once `$HOME` is known: `home` with trailing slashes +/// stripped, then the path after the `~`, or `/` when both are empty. +pub(crate) fn expand_home(home: &[u8], tail: &[u8]) -> Vec { + let end = home.iter().rposition(|&c| c != b'/').map_or(0, |i| i + 1); + let mut out = home[..end].to_vec(); + out.extend_from_slice(tail); + if out.is_empty() { + out.push(b'/'); + } + out +} + +/// `os.path.expandvars`: replace `$name` and `${name}` with `lookup(name)`, +/// leaving unknown names and malformed references as written. `name` is an +/// ASCII `\w+` run for the bare form and anything up to the first `}` for +/// the braced form, which stays unexpanded when that `}` never comes. +/// +/// Values can be far longer than the references they replace, so the result +/// is an amplifying allocation: `reserve` is asked to approve each capacity +/// doubling before it happens (see `ResourceTracker::check_allocation`). +pub(crate) fn expandvars<'e, E>( + path: &[u8], + mut lookup: impl FnMut(&[u8]) -> Option<&'e [u8]>, + mut reserve: impl FnMut(usize) -> Result<(), E>, +) -> Result, E> { + let mut out = Vec::new(); + let mut push = |out: &mut Vec, bytes: &[u8]| { + let needed = out.len() + bytes.len(); + if needed > out.capacity() { + let capacity = needed.max(out.capacity() * 2).max(path.len()); + reserve(capacity - out.capacity())?; + out.reserve_exact(capacity - out.len()); + } + out.extend_from_slice(bytes); + Ok(()) + }; + let mut rest = path; + while let Some(dollar) = rest.iter().position(|&c| c == b'$') { + push(&mut out, &rest[..dollar])?; + let after = &rest[dollar + 1..]; + let (reference, name) = if after.starts_with(b"{") { + let Some(close) = after.iter().position(|&c| c == b'}') else { + // `${` with no closing brace: the rest of the path is one unexpandable match. + push(&mut out, &rest[dollar..])?; + return Ok(out); + }; + (&rest[dollar..dollar + close + 2], &after[1..close]) + } else { + let len = after + .iter() + .position(|&c| !(c.is_ascii_alphanumeric() || c == b'_')) + .unwrap_or(after.len()); + (&rest[dollar..=dollar + len], &after[..len]) + }; + if name.is_empty() && !reference.starts_with(b"${") { + // A lone `$` matches nothing and is copied through. + push(&mut out, b"$")?; + rest = after; + continue; + } + push(&mut out, lookup(name).unwrap_or(reference))?; + rest = &rest[dollar + reference.len()..]; + } + push(&mut out, rest)?; + Ok(out) +} diff --git a/crates/bashkit-monty/src/modules/pathlib.rs b/crates/bashkit-monty/src/modules/pathlib.rs new file mode 100644 index 000000000..79187ff95 --- /dev/null +++ b/crates/bashkit-monty/src/modules/pathlib.rs @@ -0,0 +1,27 @@ +//! Implementation of the `pathlib` module. +//! +//! Provides a minimal implementation of Python's `pathlib` module with: +//! - `Path`: A class for filesystem path operations +//! +//! The `Path` class supports both pure methods (no I/O, handled directly) and +//! filesystem methods (require I/O, yield external function calls for host resolution). + +use crate::{ + builtins::Builtins, + bytecode::VM, + heap::{HeapData, HeapId}, + intern::StaticStrings, + types::{Module, Type}, + value::Value, +}; + +/// Creates the `pathlib` module and allocates it on the heap. +/// +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Pathlib, vm.interns); + + // pathlib.Path - the Path class (callable to create Path instances) + module.set_attr(StaticStrings::PathClass, Value::Builtin(Builtins::Type(Type::Path)), vm); + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} diff --git a/crates/bashkit-monty/src/modules/random.rs b/crates/bashkit-monty/src/modules/random.rs new file mode 100644 index 000000000..0fbcb618f --- /dev/null +++ b/crates/bashkit-monty/src/modules/random.rs @@ -0,0 +1,1647 @@ +//! Implementation of Python's `random` module. +//! +//! The pure-Python bodies of `Lib/random.py` are ported here 1:1 on top of the +//! [`Mt19937`] core in `types::random`, so a seeded generator produces exactly +//! CPython's sequence: `randrange`, `choice`, `shuffle`, `sample`, `choices` +//! and the distributions all consume the same draws in the same order. The +//! module-level functions and the `random.Random` methods share one +//! dispatcher, [`random_dispatch`], parameterised by the [`RandomTarget`]. +//! +//! The first draw seeds an unseeded generator according to `RandomStart`: +//! OS entropy, a session seed, or an `os.urandom` host call. For host calls, +//! [`apply_seed_random`] seeds the generator and retries the draw on resume. +//! See `limitations/random.md` for divergences. + +use std::{ + cmp::Ordering, + f64::consts::{E, PI, TAU}, + iter::once, + mem, +}; + +use ahash::AHashSet; +use monty_types::{OsFunctionCall, ResourceTracker, UrandomArgs}; +use num_bigint::{BigInt, BigUint}; +use serde::{Deserialize, Serialize}; +use smallvec::SmallVec; + +use crate::{ + args::{ArgValues, FromArgs}, + builtins::Builtins, + bytecode::{CallResult, VM, unpack_exact}, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{ContainsHeap, DropGuard, DropWithContext, HeapData, HeapId, HeapReadOutput}, + intern::StaticStrings, + modules::ModuleFunctions, + os_dispatch::{PostConversionEffect, urandom_reply_error}, + types::{ + List, LongInt, Module, PyTrait, Type, + bytes::allocate_bytes, + iter::collect_owned_iterable, + long_int::bigint_to_f64_checked, + random::{Mt19937, RandomTarget, SEED_BYTES, seed_key_from_value}, + tuple::{TupleVec, allocate_tuple}, + }, + value::{VALUE_SIZE, Value, float_pow}, +}; + +/// `random` module functions, each also a method of `random.Random`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, Serialize, Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum RandomFunctions { + Random, + Seed, + Getstate, + Setstate, + Getrandbits, + Randbytes, + Randrange, + Randint, + Choice, + Choices, + Shuffle, + Sample, + Uniform, + Triangular, + Normalvariate, + Gauss, + Lognormvariate, + Expovariate, + Vonmisesvariate, + Gammavariate, + Betavariate, + Paretovariate, + Weibullvariate, + Binomialvariate, +} + +/// Every function with the interned name it is bound to, for the module +/// namespace and for method lookup on `random.Random`. +const RANDOM_FUNCTIONS: &[(StaticStrings, RandomFunctions)] = &[ + (StaticStrings::Random, RandomFunctions::Random), + (StaticStrings::Seed, RandomFunctions::Seed), + (StaticStrings::Getstate, RandomFunctions::Getstate), + (StaticStrings::Setstate, RandomFunctions::Setstate), + (StaticStrings::Getrandbits, RandomFunctions::Getrandbits), + (StaticStrings::Randbytes, RandomFunctions::Randbytes), + (StaticStrings::Randrange, RandomFunctions::Randrange), + (StaticStrings::Randint, RandomFunctions::Randint), + (StaticStrings::Choice, RandomFunctions::Choice), + (StaticStrings::Choices, RandomFunctions::Choices), + (StaticStrings::Shuffle, RandomFunctions::Shuffle), + (StaticStrings::Sample, RandomFunctions::Sample), + (StaticStrings::Uniform, RandomFunctions::Uniform), + (StaticStrings::Triangular, RandomFunctions::Triangular), + (StaticStrings::Normalvariate, RandomFunctions::Normalvariate), + (StaticStrings::Gauss, RandomFunctions::Gauss), + (StaticStrings::Lognormvariate, RandomFunctions::Lognormvariate), + (StaticStrings::Expovariate, RandomFunctions::Expovariate), + (StaticStrings::Vonmisesvariate, RandomFunctions::Vonmisesvariate), + (StaticStrings::Gammavariate, RandomFunctions::Gammavariate), + (StaticStrings::Betavariate, RandomFunctions::Betavariate), + (StaticStrings::Paretovariate, RandomFunctions::Paretovariate), + (StaticStrings::Weibullvariate, RandomFunctions::Weibullvariate), + (StaticStrings::Binomialvariate, RandomFunctions::Binomialvariate), +]; + +impl RandomFunctions { + /// The function a `random.Random` attribute name refers to, if any. + pub(crate) fn from_static_string(name: StaticStrings) -> Option { + RANDOM_FUNCTIONS + .iter() + .find_map(|(attr, function)| (*attr == name).then_some(*function)) + } +} + +/// Creates the `random` module on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Random, vm.interns); + for (name, function) in RANDOM_FUNCTIONS { + module.set_attr(*name, Value::ModuleFunction(ModuleFunctions::Random(*function)), vm); + } + module.set_attr( + StaticStrings::RandomClass, + Value::Builtin(Builtins::Type(Type::Random)), + vm, + ); + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a module-level call, which acts on the VM's own generator. +pub(super) fn call(vm: &mut VM<'_>, function: RandomFunctions, args: ArgValues) -> RunResult { + random_dispatch(RandomTarget::Global, function, args, vm) +} + +/// Runs `function` against `target`'s generator, for module functions and +/// `Random` methods alike. +/// +/// Unseeded generators initialize from `RandomStart`, except for `seed(x)` and +/// `setstate()`. `CallHost` stores the call in a [`RandomRetry`] to replay after seeding. +pub(crate) fn random_dispatch( + target: RandomTarget, + function: RandomFunctions, + args: ArgValues, + vm: &mut VM<'_>, +) -> RunResult { + match function { + RandomFunctions::Seed => seed(target, args, vm), + RandomFunctions::Setstate => setstate(target, args, vm).map(CallResult::Value), + _ => { + if !target.is_seeded(vm) { + match vm.random.first_state(target, &vm.env.os_policy.random_start) { + Ok(Some(state)) => target.reseed(vm, state), + Ok(None) => return Ok(request_entropy(target, Some(RandomRetry { function, args }), vm)), + Err(err) => { + args.drop_with(vm); + return Err(err); + } + } + } + call_seeded(target, function, args, vm).map(CallResult::Value) + } + } +} + +/// A draw stashed while its generator waits for host entropy, replayed by +/// [`apply_seed_random`]. Owns the call's arguments across the yield. +#[derive(Debug, Serialize, Deserialize)] +pub(crate) struct RandomRetry { + function: RandomFunctions, + args: ArgValues, +} + +impl DropWithContext for RandomRetry { + fn drop_with(self, ctx: &mut C) { + self.args.drop_with(ctx); + } +} + +/// Suspends for [`SEED_BYTES`] of host entropy, pinning an instance target +/// across the yield (released by [`apply_seed_random`] or the effect's `release`). +fn request_entropy(target: RandomTarget, retry: Option, vm: &mut VM<'_>) -> CallResult { + if let RandomTarget::Instance(id) = target { + vm.heap.inc_ref(id); + } + CallResult::OsCallWithEffect { + call: OsFunctionCall::Urandom(UrandomArgs { + size: SEED_BYTES as u64, + }), + effect: PostConversionEffect::SeedRandom { target, retry }.into(), + } +} + +/// Resume half of [`request_entropy`]: seeds `target` from the host's +/// `os.urandom` reply, then answers `None` (`seed()`) or replays the stashed +/// draw. The instance pin is dropped on every path. +pub(crate) fn apply_seed_random( + target: RandomTarget, + retry: Option, + reply: Value, + vm: &mut VM<'_>, +) -> RunResult { + let result = seed_from_reply(target, retry, reply, vm); + if let RandomTarget::Instance(id) = target { + vm.heap.dec_ref(id); + } + result +} + +/// [`apply_seed_random`] without the unpin: validates the reply as exactly +/// [`SEED_BYTES`] bytes, seeds, and replays. +fn seed_from_reply( + target: RandomTarget, + retry: Option, + reply: Value, + vm: &mut VM<'_>, +) -> RunResult { + defer_drop!(reply, vm); + let seeded = match value_as_bytes(reply, vm) { + Some(bytes) if bytes.len() == SEED_BYTES => Ok(Mt19937::from_entropy(bytes)), + Some(bytes) => Err(urandom_reply_error(Ok(bytes.len()), SEED_BYTES)), + None => Err(urandom_reply_error(Err(&reply.py_type_name(vm)), SEED_BYTES)), + }; + let rng = match seeded { + Ok(rng) => rng, + Err(err) => { + retry.drop_with(vm); + return Err(err); + } + }; + target.reseed(vm, rng); + match retry { + None => Ok(Value::None), + Some(RandomRetry { function, args }) => match random_dispatch(target, function, args, vm)? { + CallResult::Value(value) => Ok(value), + other => { + other.drop_with(vm); + unreachable!("a seeded generator never suspends") + } + }, + } +} + +/// Borrows the bytes behind a `bytes` value, interned or heap-allocated. +fn value_as_bytes<'a>(value: &'a Value, vm: &'a VM<'_>) -> Option<&'a [u8]> { + match value { + Value::InternBytes(id) => Some(vm.interns.get_bytes(*id)), + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Bytes(bytes) => Some(bytes.as_slice()), + _ => None, + }, + _ => None, + } +} + +/// Dispatch for a generator known to be seeded. +fn call_seeded(target: RandomTarget, function: RandomFunctions, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + match function { + RandomFunctions::Random => random(target, args, vm), + RandomFunctions::Getstate => getstate(target, args, vm), + RandomFunctions::Getrandbits => getrandbits(target, args, vm), + RandomFunctions::Randbytes => randbytes(target, args, vm), + RandomFunctions::Randrange => randrange(target, args, vm), + RandomFunctions::Randint => randint(target, args, vm), + RandomFunctions::Choice => choice(target, args, vm), + RandomFunctions::Choices => choices(target, args, vm), + RandomFunctions::Shuffle => shuffle(target, args, vm), + RandomFunctions::Sample => sample(target, args, vm), + RandomFunctions::Uniform => uniform(target, args, vm), + RandomFunctions::Triangular => triangular(target, args, vm), + RandomFunctions::Normalvariate => normalvariate(target, args, vm), + RandomFunctions::Gauss => gauss(target, args, vm), + RandomFunctions::Lognormvariate => lognormvariate(target, args, vm), + RandomFunctions::Expovariate => expovariate(target, args, vm), + RandomFunctions::Vonmisesvariate => vonmisesvariate(target, args, vm), + RandomFunctions::Gammavariate => gammavariate(target, args, vm), + RandomFunctions::Betavariate => betavariate(target, args, vm), + RandomFunctions::Paretovariate => paretovariate(target, args, vm), + RandomFunctions::Weibullvariate => weibullvariate(target, args, vm), + RandomFunctions::Binomialvariate => binomialvariate(target, args, vm), + RandomFunctions::Seed | RandomFunctions::Setstate => { + unreachable!("seed and setstate are dispatched before the seeded check") + } + } +} + +// ============================================================================ +// Seeding and state +// ============================================================================ + +/// `seed(a=None, version=2)` — a Python `def` in CPython. +#[derive(FromArgs)] +#[from_args(name = "Random.seed", style = def)] +struct SeedArgs { + #[from_args(default = Value::None)] + a: Value, + #[from_args(default = Value::Int(2))] + version: Value, +} + +/// `seed(a=None, version=2)`: `None` takes a fresh state according to `RandomStart`; +/// explicit seeds follow `random.py`. +fn seed(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let SeedArgs { a, version } = SeedArgs::from_args(args, vm)?; + defer_drop!(a, vm); + defer_drop!(version, vm); + let state = if matches!(a, Value::None) { + match vm.random.fresh_state(&vm.env.os_policy.random_start)? { + Some(state) => state, + None => return Ok(request_entropy(target, None, vm)), + } + } else { + Mt19937::from_key(&seed_key_from_value(a, version_number(version), vm)?) + }; + target.reseed(vm, state); + Ok(CallResult::Value(Value::None)) +} + +/// The `version` a seed call named, for the `== 1` / `== 2` tests in +/// `random.py`; anything that equals neither reads as 0. +fn version_number(version: &Value) -> i64 { + match version { + Value::Int(i) => *i, + Value::Bool(b) => i64::from(*b), + #[expect(clippy::cast_possible_truncation, reason = "only 1.0 and 2.0 matter")] + Value::Float(f) if f.fract() == 0.0 && f.abs() < 3.0 => *f as i64, + _ => 0, + } +} + +/// `getstate()`: `(3, (624 words..., index), gauss_next)`. +fn getstate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + args.check_zero_args("Random.getstate", vm.heap)?; + let (words, index, gauss_next) = target.with_generator(vm, |random, _| { + let (words, index) = random.rng().state(); + (words.to_vec(), index, random.gauss_next()) + }); + let internal: TupleVec = words + .into_iter() + .map(|word| Value::Int(i64::from(word))) + .chain(once(Value::Int(i64::try_from(index).expect("index fits i64")))) + .collect(); + let internal = allocate_tuple(internal, vm.heap); + let gauss_next = gauss_next.map_or(Value::None, Value::Float); + Ok(allocate_tuple( + SmallVec::from_vec(vec![Value::Int(3), internal, gauss_next]), + vm.heap, + )) +} + +/// `setstate(state)` — a Python `def` wrapping the C `setstate`. +#[derive(FromArgs)] +#[from_args(name = "Random.setstate", style = def)] +struct SetstateArgs { + state: Value, +} + +/// `setstate(state)`: restores a `getstate()` tuple, accepting version 2 +/// states (signed words) as CPython does. +fn setstate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let SetstateArgs { state } = SetstateArgs::from_args(args, vm)?; + defer_drop!(state, vm); + + // `version = state[0]` runs before the unpack, so a non-subscriptable + // state reports that rather than an unpack failure. + let version = state.py_getitem(&Value::Int(0), vm)?; + defer_drop!(version, vm); + let version = match version { + Value::Int(v @ (2 | 3)) => *v, + // `version == 3` in Python, which `3.0` satisfies. + Value::Float(f) if f.fract() == 0.0 && (2.0..=3.0).contains(f) => { + #[expect(clippy::cast_possible_truncation, reason = "exactly 2.0 or 3.0")] + let v = *f as i64; + v + } + other => { + let text = other.py_str(vm)?; + defer_drop!(text, vm); + let text = text.to_str_heap(vm.heap, vm.interns)?; + return Err(ExcType::value_error(format!( + "state with version {text} passed to Random.setstate() of version 3" + ))); + } + }; + + // `version, internalstate, self.gauss_next = state` + let items = unpack_exact(state, 3, vm)?; + defer_drop!(items, vm); + let internal = &items[1]; + let gauss_next = match &items[2] { + Value::None => None, + Value::Float(f) => Some(*f), + Value::Int(i) => Some(*i as f64), + Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }), + other => { + return Err(ExcType::type_error(format!( + "Random.setstate() gauss_next must be a float or None, not {}", + other.py_type_name(vm) + ))); + } + }; + + // Version 2 runs `tuple(x % (2**32) for x in internalstate)` before the + // C-level checks, so it accepts any iterable and a non-number reports the + // `%` error; version 3 hands the object straight to C, which wants a tuple. + let entries: Vec = if version == 2 { + reduce_state_words(internal, vm)? + } else { + let tuple = match internal { + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Tuple(tuple) => Some(tuple), + _ => None, + }, + _ => None, + }; + let Some(tuple) = tuple else { + return Err(ExcType::type_error("state vector must be a tuple")); + }; + // Size first, so an oversized tuple is rejected before it is copied. + if tuple.as_slice().len() != Mt19937::state_len() + 1 { + return Err(ExcType::value_error("state vector is the wrong size")); + } + tuple + .as_slice() + .iter() + .map(|entry| entry.clone_with_heap(vm.heap)) + .collect() + }; + defer_drop!(entries, vm); + if entries.len() != Mt19937::state_len() + 1 { + return Err(ExcType::value_error("state vector is the wrong size")); + } + let mut words = Vec::with_capacity(Mt19937::state_len()); + for entry in &entries[..Mt19937::state_len()] { + words.push(state_word(entry, vm)?); + } + let index = match &entries[Mt19937::state_len()] { + Value::Int(i) => *i, + Value::Bool(b) => i64::from(*b), + other => { + return Err(ExcType::type_error(format!( + "'{}' object cannot be interpreted as an integer", + other.py_type_name(vm) + ))); + } + }; + let index = usize::try_from(index) + .ok() + .filter(|index| *index <= Mt19937::state_len()) + .ok_or_else(|| ExcType::value_error("invalid state"))?; + + target.with_generator(vm, |random, _| { + random.reseed(Mt19937::from_state(words, index)); + random.set_gauss_next(gauss_next); + }); + Ok(Value::None) +} + +/// `tuple(x % (2**32) for x in internalstate)`: the reduction `random.py` +/// applies to a version 2 state before the C `setstate` sees it. +fn reduce_state_words(internal: &Value, vm: &mut VM<'_>) -> RunResult> { + let items: Vec = collect_owned_iterable(internal.clone_with_heap(vm), vm)?; + defer_drop!(items, vm); + let modulus = Value::Int(1 << 32); + let mut reduced = Vec::with_capacity(items.len()); + for item in items { + match item.py_mod(&modulus, vm) { + Ok(word) => reduced.push(word), + Err(err) => { + reduced.drop_with(vm); + return Err(err); + } + } + } + Ok(reduced) +} + +/// One state word as the C `setstate` reads it: `PyLong_AsUnsignedLong`, +/// truncated to 32 bits. +fn state_word(entry: &Value, vm: &VM<'_>) -> RunResult { + const NEGATIVE: &str = "can't convert negative value to unsigned int"; + const TOO_LARGE: &str = "Python int too large to convert to C unsigned long"; + let overflow = |message: &str| SimpleException::new_msg(ExcType::OverflowError, message).into(); + match entry { + Value::Bool(b) => Ok(u32::from(*b)), + #[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "truncation to 32 bits is the C behaviour; the sign is checked first" + )] + Value::Int(i) => { + if *i < 0 { + Err(overflow(NEGATIVE)) + } else { + Ok(*i as u32) + } + } + // Outside `i64`: `unsigned long` is 64 bits on the platforms CPython + // is compared against, so `2**63..2**64` converts and then truncates. + _ => match entry.as_long_int(vm) { + Some(big) if big.sign() == num_bigint::Sign::Minus => Err(overflow(NEGATIVE)), + #[expect( + clippy::cast_possible_truncation, + reason = "truncation to 32 bits is the C behaviour" + )] + Some(big) => u64::try_from(big) + .map(|word| word as u32) + .map_err(|_| overflow(TOO_LARGE)), + None => Err(ExcType::type_error("an integer is required")), + }, + } +} + +// ============================================================================ +// Core draws +// ============================================================================ + +/// `random()`: the next float in `[0, 1)`. +fn random(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + args.check_zero_args("Random.random", vm.heap)?; + Ok(Value::Float( + target.with_generator(vm, |random, _| random.rng().random()), + )) +} + +/// `getrandbits(k)`: `k` random bits as a non-negative int. +fn getrandbits(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + // A clinic `uint64_t` parameter: keywords are refused before the count. + let k = args + .reject_kwargs("Random.getrandbits", vm.heap)? + .get_one_arg("Random.getrandbits", vm.heap)?; + defer_drop!(k, vm); + let k = k.as_int_with_overflow(vm, ExcType::overflow_c_uint64)?; + let k = u64::try_from(k).map_err(|_| ExcType::value_error_negative_int())?; + if k == 0 { + return Ok(Value::Int(0)); + } + if k <= 64 { + #[expect(clippy::cast_possible_truncation, reason = "k <= 64")] + let bits = target.with_generator(vm, |random, _| random.rng().getrandbits_u128(k as u32)); + return Ok(LongInt::value_from_u128(bits, vm.heap)); + } + let words = usize::try_from((k - 1) / 32 + 1).map_err(|_| ExcType::value_error("number of bits too large"))?; + // One preflight for the word buffer and the big int built from it. + vm.heap.tracker.check_allocation(words.saturating_mul(8))?; + let words = target.with_generator(vm, |random, vm| { + random.rng().getrandbits_words(k, words, &vm.heap.tracker) + })?; + Ok(LongInt::new(BigInt::from(BigUint::from_slice(&words))).into_value(vm.heap)) +} + +/// `randbytes(n)` — a Python `def`: `getrandbits(n * 8).to_bytes(n, 'little')`. +#[derive(FromArgs)] +#[from_args(name = "Random.randbytes", style = def)] +struct RandbytesArgs { + n: Value, +} + +/// `randbytes(n)`: `n` random bytes, the little-endian bytes of `getrandbits(8n)`. +fn randbytes(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let RandbytesArgs { n } = RandbytesArgs::from_args(args, vm)?; + defer_drop!(n, vm); + // `getrandbits(n * 8)` is what rejects a negative or oversized count. + let n = n.as_int_with_overflow(vm, ExcType::overflow_c_uint64)?; + let n = usize::try_from(n).map_err(|_| ExcType::value_error_negative_int())?; + if n == 0 { + return Ok(allocate_bytes(Vec::new(), vm.heap)); + } + let bits = u64::try_from(n) + .ok() + .and_then(|n| n.checked_mul(8)) + .ok_or_else(ExcType::overflow_c_uint64)?; + // The word buffer plus the exactly-sized byte buffer built from it. + let words = n.div_ceil(4); + vm.heap + .tracker + .check_allocation(words.saturating_mul(4).saturating_add(n))?; + let words = target.with_generator(vm, |random, vm| { + random.rng().getrandbits_words(bits, words, &vm.heap.tracker) + })?; + let mut bytes = Vec::with_capacity(n); + for word in &words { + let take = (n - bytes.len()).min(4); + bytes.extend_from_slice(&word.to_le_bytes()[..take]); + } + Ok(allocate_bytes(bytes, vm.heap)) +} + +/// `randrange(start, stop=None, step=1)` — a Python `def`. `step` is optional +/// rather than defaulted so the `step is not _ONE` check can tell an explicit +/// step from the default. +#[derive(FromArgs)] +#[from_args(name = "Random.randrange", style = def)] +struct RandrangeArgs { + start: Value, + #[from_args(default = Value::None)] + stop: Value, + #[from_args(default)] + step: Option, +} + +/// `randrange(start, stop=None, step=1)`: a random member of the range. +fn randrange(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let RandrangeArgs { start, stop, step } = RandrangeArgs::from_args(args, vm)?; + defer_drop!(start, vm); + defer_drop!(stop, vm); + defer_drop!(step, vm); + + let istart = i128::from(start.as_int(vm)?); + if matches!(stop, Value::None) { + // CPython tests `step is not _ONE`, and `1` is that very object. + if step.as_ref().is_some_and(|step| !matches!(step, Value::Int(1))) { + return Err(ExcType::type_error("Missing a non-None stop argument")); + } + return if istart > 0 { + Ok(int_value(istart_plus( + 0, + target.with_generator(vm, |random, vm| { + random.rng().randbelow(as_u128(istart), &vm.heap.tracker) + })?, + ))) + } else { + Err(ExcType::value_error("empty range for randrange()")) + }; + } + + let istop = i128::from(stop.as_int(vm)?); + let width = istop - istart; + let istep = match step { + Some(step) => i128::from(step.as_int(vm)?), + None => 1, + }; + if istep == 1 { + return if width > 0 { + let offset = target.with_generator(vm, |random, vm| { + random.rng().randbelow(as_u128(width), &vm.heap.tracker) + })?; + Ok(int_value(istart_plus(istart, offset))) + } else { + Err(ExcType::value_error(format!( + "empty range in randrange({}, {})", + int_arg_str(start), + int_arg_str(stop) + ))) + }; + } + + let n = match istep.cmp(&0) { + Ordering::Greater => floor_div(width + istep - 1, istep), + Ordering::Less => floor_div(width + istep + 1, istep), + Ordering::Equal => return Err(ExcType::value_error("zero step for randrange()")), + }; + if n <= 0 { + let step = step.as_ref().expect("a unit step returned above"); + return Err(ExcType::value_error(format!( + "empty range in randrange({}, {}, {})", + int_arg_str(start), + int_arg_str(stop), + int_arg_str(step) + ))); + } + let offset = target.with_generator(vm, |random, vm| random.rng().randbelow(as_u128(n), &vm.heap.tracker))?; + Ok(int_value( + istart + istep * i128::try_from(offset).expect("offset below n"), + )) +} + +/// `randint(a, b)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.randint", style = def)] +struct RandintArgs { + a: Value, + b: Value, +} + +/// `randint(a, b)`: a random int in `[a, b]`. +fn randint(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let RandintArgs { a, b } = RandintArgs::from_args(args, vm)?; + defer_drop!(a, vm); + defer_drop!(b, vm); + let a = i128::from(a.as_int(vm)?); + let b = i128::from(b.as_int(vm)?); + if b < a { + return Err(ExcType::value_error(format!("empty range in randint({a}, {b})"))); + } + let offset = target.with_generator(vm, |random, vm| { + random.rng().randbelow(as_u128(b - a + 1), &vm.heap.tracker) + })?; + Ok(int_value(istart_plus(a, offset))) +} + +/// `start + offset` for a `randbelow` draw that cannot leave the range. +fn istart_plus(start: i128, offset: u128) -> i128 { + start + i128::try_from(offset).expect("offset below an i64-sized range") +} + +/// A positive range width as the unsigned count `randbelow` takes. +fn as_u128(n: i128) -> u128 { + u128::try_from(n).expect("range width checked positive") +} + +/// An int known to sit inside an `i64` range, back to a `Value`. +fn int_value(n: i128) -> Value { + Value::Int(i64::try_from(n).expect("result lies within the i64 arguments")) +} + +/// Python's floor division for the `randrange` step arithmetic. +fn floor_div(a: i128, b: i128) -> i128 { + let q = a / b; + if (a % b != 0) && ((a < 0) != (b < 0)) { q - 1 } else { q } +} + +/// How `randrange` spells an argument in its empty-range message: the +/// f-string formats the original object, so `True` stays `True`. +fn int_arg_str(value: &Value) -> String { + match value { + Value::Bool(b) => if *b { "True" } else { "False" }.to_owned(), + Value::Int(i) => i.to_string(), + _ => unreachable!("only ints and bools pass `as_int`"), + } +} + +// ============================================================================ +// Sequences +// ============================================================================ + +/// `choice(seq)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.choice", style = def)] +struct ChoiceArgs { + seq: Value, +} + +/// `choice(seq)`: `seq[randbelow(len(seq))]`. +fn choice(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let ChoiceArgs { seq } = ChoiceArgs::from_args(args, vm)?; + defer_drop!(seq, vm); + let len = len_of(seq, vm)?; + if len == 0 { + return Err(ExcType::index_error("Cannot choose from an empty sequence")); + } + let index = target.with_generator(vm, |random, vm| random.rng().randbelow(len as u128, &vm.heap.tracker))?; + seq.py_getitem(&Value::Int(index_value(index)), vm) +} + +/// `shuffle(x)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.shuffle", style = def)] +struct ShuffleArgs { + x: Value, +} + +/// `shuffle(x)`: Fisher–Yates in place, from the end. +/// +/// Lists are swapped directly. Anything else goes through `x[i], x[j] = x[j], +/// x[i]` per swap, as `random.py` does, so a tuple, `str`, set or dict fails +/// (or, for a dict keyed `0..n`, succeeds) exactly where CPython does. +fn shuffle(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let ShuffleArgs { x } = ShuffleArgs::from_args(args, vm)?; + defer_drop_mut!(x, vm); + let len = len_of(x, vm)?; + if let Value::Ref(id) = x + && let HeapReadOutput::List(list) = vm.heap.read(*id) + { + return target.with_generator(vm, |random, vm| { + for i in (1..len).rev() { + vm.heap.tracker.check_time_every(i)?; + let j = index_value(random.rng().randbelow(i as u128 + 1, &vm.heap.tracker)?); + list.get_mut(vm.heap) + .as_vec_mut() + .swap(i, usize::try_from(j).expect("j <= i")); + } + Ok(Value::None) + }); + } + for i in (1..len).rev() { + vm.heap.tracker.check_time_every(i)?; + let j = target.with_generator(vm, |random, vm| random.rng().randbelow(i as u128 + 1, &vm.heap.tracker))?; + swap_items(x, i64::try_from(i).expect("index fits i64"), index_value(j), vm)?; + } + Ok(Value::None) +} + +/// `x[i], x[j] = x[j], x[i]` through the subscript protocol: both reads happen +/// before either write, and `__getitem__` may run Python, so the caller draws +/// `j` before calling. +fn swap_items(x: &mut Value, i: i64, j: i64, vm: &mut VM<'_>) -> RunResult<()> { + let (i, j) = (Value::Int(i), Value::Int(j)); + let mut xj_guard = DropGuard::new(x.py_getitem(&j, vm)?, vm); + let (_, vm) = xj_guard.as_parts_mut(); + let xi = x.py_getitem(&i, vm)?; + let (xj, vm) = xj_guard.into_parts(); + // `py_setitem` consumes its value on every path, so only `xi` needs guarding. + let mut xi_guard = DropGuard::new(xi, vm); + let (_, vm) = xi_guard.as_parts_mut(); + x.py_setitem(i, xj, vm)?; + let (xi, vm) = xi_guard.into_parts(); + x.py_setitem(j, xi, vm) +} + +/// `sample(population, k, *, counts=None)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.sample", style = def)] +struct SampleArgs { + population: Value, + k: Value, + #[from_args(kw_only, default = Value::None)] + counts: Value, +} + +/// `sample(population, k, *, counts=None)`: `k` distinct picks, in selection +/// order, drawn exactly as CPython does (pool below its set-size threshold, +/// rejection into a set above it). +fn sample(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let SampleArgs { population, k, counts } = SampleArgs::from_args(args, vm)?; + defer_drop!(population, vm); + defer_drop!(k, vm); + defer_drop!(counts, vm); + + if !is_sequence(population.py_type_heap(vm.heap)) { + return Err(ExcType::type_error( + "Population must be a sequence. For dicts or sets, use sorted(d).", + )); + } + let n = len_of(population, vm)?; + let k = k.as_int(vm)?; + + let picks = if matches!(counts, Value::None) { + let indices = sample_indices(target, n, k, vm)?; + collect_items(population, indices.into_iter(), vm)? + } else { + let cum_counts = cumulative_counts(counts, vm)?; + if cum_counts.len() != n { + return Err(ExcType::value_error( + "The number of counts does not match the population", + )); + } + let total = cum_counts.last().copied().unwrap_or(0); + if total < 0 { + return Err(ExcType::value_error("Counts must be non-negative")); + } + let total = i64::try_from(total).map_err(|_| ExcType::overflow_c_ssize_t())?; + let total = usize::try_from(total).map_err(|_| ExcType::overflow_c_ssize_t())?; + let selections = sample_indices(target, total, k, vm)?; + let indices = selections + .into_iter() + .map(|s| bisect_right(&cum_counts, i128::try_from(s).expect("selection below total"))); + collect_items(population, indices, vm)? + }; + Ok(Value::Ref(vm.heap.allocate(HeapData::List(List::new(picks))))) +} + +/// The positions `sample` picks from a population of `n` — the whole +/// algorithm from `random.py`, so the draws match CPython's. +fn sample_indices(target: RandomTarget, n: usize, k: i64, vm: &mut VM<'_>) -> RunResult> { + let k = match usize::try_from(k) { + Ok(k) if k <= n => k, + _ => return Err(ExcType::value_error("Sample larger than population or is negative")), + }; + // `setsize = 21 + 4 ** ceil(log(k * 3, 4))` for k > 5: the point where a + // k-sized set costs less than an n-sized pool. + // `k` can be a `range` length near `i64::MAX`, so the arithmetic here must + // not overflow before `check_allocation` refuses the request. + let setsize: usize = if k > 5 { + let exponent = (k.saturating_mul(3) as f64).ln() / 4f64.ln(); + #[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "small positive exponent" + )] + let exponent = exponent.ceil() as u32; + 4usize.checked_pow(exponent).map_or(usize::MAX, |table| 21 + table) + } else { + 21 + }; + // The index buffer, the result list built from it, and the pool if used. + let pool_bytes = if n <= setsize { + n.saturating_mul(mem::size_of::()) + } else { + 0 + }; + vm.heap.tracker.check_allocation( + k.saturating_mul(VALUE_SIZE + mem::size_of::()) + .saturating_add(pool_bytes), + )?; + + target.with_generator(vm, |random, vm| { + let rng = random.rng(); + let mut result = Vec::with_capacity(k); + if n <= setsize { + let mut pool: Vec = (0..n).collect(); + for i in 0..k { + vm.heap.tracker.check_time_every(i)?; + let j = index_value(rng.randbelow((n - i) as u128, &vm.heap.tracker)?); + let j = usize::try_from(j).expect("j < n"); + result.push(pool[j]); + pool[j] = pool[n - i - 1]; + } + } else { + let mut selected = AHashSet::with_capacity(k); + let mut attempts = 0usize; + for i in 0..k { + vm.heap.tracker.check_time_every(i)?; + let mut j = index_value(rng.randbelow(n as u128, &vm.heap.tracker)?); + while selected.contains(&j) { + vm.heap.tracker.check_time_every(attempts)?; + attempts = attempts.wrapping_add(1); + j = index_value(rng.randbelow(n as u128, &vm.heap.tracker)?); + } + selected.insert(j); + result.push(usize::try_from(j).expect("j < n")); + } + } + Ok(result) + }) +} + +/// `list(accumulate(counts))` for `sample(counts=...)`, which must be ints. +fn cumulative_counts(counts: &Value, vm: &mut VM<'_>) -> RunResult> { + let items: Vec = collect_owned_iterable(counts.clone_with_heap(vm), vm)?; + defer_drop!(items, vm); + let mut cumulative = Vec::with_capacity(items.len()); + let mut running: i128 = 0; + for item in items { + let count = match item { + Value::Int(i) => i128::from(*i), + Value::Bool(b) => i128::from(*b), + _ => return Err(ExcType::type_error("Counts must be integers")), + }; + running += count; + cumulative.push(running); + } + Ok(cumulative) +} + +/// `choices(population, weights=None, *, cum_weights=None, k=1)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.choices", style = def)] +struct ChoicesArgs { + population: Value, + #[from_args(default = Value::None)] + weights: Value, + #[from_args(kw_only, default = Value::None)] + cum_weights: Value, + #[from_args(kw_only, default = Value::Int(1))] + k: Value, +} + +/// `choices(population, weights=None, *, cum_weights=None, k=1)`: `k` picks +/// with replacement, uniform or by (cumulative) weight. +fn choices(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let ChoicesArgs { + population, + weights, + cum_weights, + k, + } = ChoicesArgs::from_args(args, vm)?; + defer_drop!(population, vm); + defer_drop!(weights, vm); + defer_drop!(cum_weights, vm); + defer_drop!(k, vm); + + let n = len_of(population, vm)?; + let cumulative = if matches!(cum_weights, Value::None) { + if matches!(weights, Value::None) { + None + } else if matches!(weights, Value::Int(_) | Value::Bool(_)) || weights.as_long_int(vm).is_some() { + // The common mistake `choices(pop, 5)`, which CPython names too, + // for any int (`k=True` for a bool, as CPython's f-string prints). + let k = weights.py_str(vm)?; + defer_drop!(k, vm); + return Err(ExcType::type_error(format!( + "The number of choices must be a keyword argument: k={}", + k.to_str_heap(vm.heap, vm.interns)? + ))); + } else { + Some(cumulative_weights(weights, vm)?) + } + } else if matches!(weights, Value::None) { + let items: Vec = collect_owned_iterable(cum_weights.clone_with_heap(vm), vm)?; + defer_drop!(items, vm); + let mut cumulative = Vec::with_capacity(items.len()); + for item in items { + cumulative.push(to_float(item, vm)?); + } + Some(cumulative) + } else { + return Err(ExcType::type_error( + "Cannot specify both weights and cumulative weights", + )); + }; + let k = k.as_int(vm)?; + let k = usize::try_from(k).unwrap_or(0); + // The index buffer and the result list built from it. + vm.heap + .tracker + .check_allocation(k.saturating_mul(VALUE_SIZE + mem::size_of::()))?; + + let indices: Vec = match cumulative { + None => { + // `floor(random() * n)` with `n` as a float, as CPython computes it. + let n_f = n as f64; + target.with_generator(vm, |random, vm| { + let rng = random.rng(); + let mut indices = Vec::with_capacity(k); + for i in 0..k { + vm.heap.tracker.check_time_every(i)?; + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "0 <= floor < n")] + indices.push((rng.random() * n_f).floor() as usize); + } + Ok::<_, RunError>(indices) + })? + } + Some(cumulative) => { + if cumulative.len() != n { + return Err(ExcType::value_error( + "The number of weights does not match the population", + )); + } + let total = cumulative + .last() + .copied() + .ok_or_else(|| ExcType::index_error("list index out of range"))?; + if total <= 0.0 { + return Err(ExcType::value_error("Total of weights must be greater than zero")); + } + if !total.is_finite() { + return Err(ExcType::value_error("Total of weights must be finite")); + } + let hi = n - 1; + target.with_generator(vm, |random, vm| { + let rng = random.rng(); + let mut indices = Vec::with_capacity(k); + for i in 0..k { + vm.heap.tracker.check_time_every(i)?; + indices.push(bisect_right_f64(&cumulative, rng.random() * total, hi)); + } + Ok::<_, RunError>(indices) + })? + } + }; + let picks = collect_items(population, indices.into_iter(), vm)?; + Ok(Value::Ref(vm.heap.allocate(HeapData::List(List::new(picks))))) +} + +/// `list(accumulate(weights))` for `choices`, as floats. +fn cumulative_weights(weights: &Value, vm: &mut VM<'_>) -> RunResult> { + let items: Vec = collect_owned_iterable(weights.clone_with_heap(vm), vm)?; + defer_drop!(items, vm); + let mut cumulative = Vec::with_capacity(items.len()); + let mut running = 0.0; + for item in items { + running += to_float(item, vm)?; + cumulative.push(running); + } + Ok(cumulative) +} + +/// `population[i]` for each index, as owned values for a new list. +fn collect_items(population: &Value, indices: impl Iterator, vm: &mut VM<'_>) -> RunResult> { + let mut items: Vec = Vec::new(); + for index in indices { + match population.py_getitem(&Value::Int(i64::try_from(index).expect("index fits i64")), vm) { + Ok(item) => items.push(item), + Err(err) => { + items.drop_with(vm); + return Err(err); + } + } + } + Ok(items) +} + +/// `bisect.bisect_right(a, x)` over cumulative counts. +fn bisect_right(a: &[i128], x: i128) -> usize { + let (mut lo, mut hi) = (0, a.len()); + while lo < hi { + let mid = lo.midpoint(hi); + if x < a[mid] { hi = mid } else { lo = mid + 1 } + } + lo +} + +/// `bisect.bisect_right(a, x, 0, hi)` over cumulative weights. +fn bisect_right_f64(a: &[f64], x: f64, hi: usize) -> usize { + let (mut lo, mut hi) = (0, hi); + while lo < hi { + let mid = lo.midpoint(hi); + if x < a[mid] { hi = mid } else { lo = mid + 1 } + } + lo +} + +/// Whether `sample` accepts `ty` as a population (`collections.abc.Sequence`). +fn is_sequence(ty: Type) -> bool { + matches!( + ty, + Type::List | Type::Tuple | Type::Str | Type::Bytes | Type::Range | Type::Deque + ) +} + +/// `len(value)`, with `len()`'s own `TypeError` for unsized values and its +/// `OverflowError` for a `range` longer than `ssize_t`. +fn len_of(value: &Value, vm: &VM<'_>) -> RunResult { + let len = value + .py_len(vm) + .ok_or_else(|| ExcType::type_error(format!("object of type '{}' has no len()", value.py_type_name(vm))))?; + if i64::try_from(len).is_ok() { + Ok(len) + } else { + Err(ExcType::overflow_c_ssize_t()) + } +} + +/// A `randbelow` result, which always fits the `i64` length it was drawn below. +fn index_value(index: u128) -> i64 { + i64::try_from(index).expect("index below an i64 length") +} + +// ============================================================================ +// Real-valued distributions +// ============================================================================ + +/// `uniform(a, b)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.uniform", style = def)] +struct UniformArgs { + a: Value, + b: Value, +} + +/// `uniform(a, b)`: `a + (b - a) * random()`. +fn uniform(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let UniformArgs { a, b } = UniformArgs::from_args(args, vm)?; + defer_drop!(a, vm); + defer_drop!(b, vm); + let (a, b) = (to_float(a, vm)?, to_float(b, vm)?); + let r = target.with_generator(vm, |random, _| random.rng().random()); + Ok(Value::Float(a + (b - a) * r)) +} + +/// `triangular(low=0.0, high=1.0, mode=None)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.triangular", style = def)] +struct TriangularArgs { + #[from_args(default = Value::Float(0.0))] + low: Value, + #[from_args(default = Value::Float(1.0))] + high: Value, + #[from_args(default = Value::None)] + mode: Value, +} + +/// `triangular(low=0.0, high=1.0, mode=None)`: the triangular distribution. +/// With `mode` given and `low == high`, CPython catches the `ZeroDivisionError` +/// and returns `low` itself, so an int `low` comes back as an int. +fn triangular(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let TriangularArgs { low, high, mode } = TriangularArgs::from_args(args, vm)?; + defer_drop!(low, vm); + defer_drop!(high, vm); + defer_drop!(mode, vm); + let (low_value, high_value) = (low, high); + let (mut low, mut high) = (to_float(low_value, vm)?, to_float(high_value, vm)?); + let mode = if matches!(mode, Value::None) { + None + } else { + Some(to_float(mode, vm)?) + }; + + let mut u = target.with_generator(vm, |random, _| random.rng().random()); + let mut c = match mode { + None => 0.5, + Some(_) if high - low == 0.0 => return Ok(low_value.clone_with_heap(vm)), + Some(mode) => (mode - low) / (high - low), + }; + if u > c { + u = 1.0 - u; + c = 1.0 - c; + mem::swap(&mut low, &mut high); + } + Ok(Value::Float(low + (high - low) * (u * c).sqrt())) +} + +/// `normalvariate(mu=0.0, sigma=1.0)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.normalvariate", style = def)] +struct NormalArgs { + #[from_args(default = Value::Float(0.0))] + mu: Value, + #[from_args(default = Value::Float(1.0))] + sigma: Value, +} + +/// `normalvariate(mu=0.0, sigma=1.0)`: Kinderman–Monahan ratio of uniforms. +fn normalvariate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let NormalArgs { mu, sigma } = NormalArgs::from_args(args, vm)?; + defer_drop!(mu, vm); + defer_drop!(sigma, vm); + let (mu, sigma) = (to_float(mu, vm)?, to_float(sigma, vm)?); + let z = target.with_generator(vm, |random, vm| normal_deviate(random.rng(), &vm.heap.tracker))?; + Ok(Value::Float(mu + z * sigma)) +} + +/// One standard normal deviate by `normalvariate`'s rejection loop. +fn normal_deviate(rng: &mut Mt19937, tracker: &ResourceTracker) -> RunResult { + // `NV_MAGICCONST = 4 * exp(-0.5) / sqrt(2.0)`, evaluated the same way. + let nv_magicconst = 4.0 * (-0.5f64).exp() / 2f64.sqrt(); + let mut attempts = 0usize; + loop { + tracker.check_time_every(attempts)?; + attempts = attempts.wrapping_add(1); + let u1 = rng.random(); + let u2 = 1.0 - rng.random(); + let z = nv_magicconst * (u1 - 0.5) / u2; + let zz = z * z / 4.0; + if zz <= -u2.ln() { + return Ok(z); + } + } +} + +/// `gauss(mu=0.0, sigma=1.0)` — parsed separately to preserve its error messages. +#[derive(FromArgs)] +#[from_args(name = "Random.gauss", style = def)] +struct GaussArgs { + #[from_args(default = Value::Float(0.0))] + mu: Value, + #[from_args(default = Value::Float(1.0))] + sigma: Value, +} + +/// `gauss(mu=0.0, sigma=1.0)`: Box–Muller, keeping the second deviate for +/// the next call. +fn gauss(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let GaussArgs { mu, sigma } = GaussArgs::from_args(args, vm)?; + defer_drop!(mu, vm); + defer_drop!(sigma, vm); + let (mu, sigma) = (to_float(mu, vm)?, to_float(sigma, vm)?); + Ok(Value::Float(target.with_generator(vm, |random, _| { + let z = if let Some(z) = random.take_gauss_next() { + z + } else { + let rng = random.rng(); + let x2pi = rng.random() * TAU; + let g2rad = (-2.0 * (1.0 - rng.random()).ln()).sqrt(); + random.set_gauss_next(Some(x2pi.sin() * g2rad)); + x2pi.cos() * g2rad + }; + mu + z * sigma + }))) +} + +/// `lognormvariate(mu, sigma)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.lognormvariate", style = def)] +struct LognormArgs { + mu: Value, + sigma: Value, +} + +/// `lognormvariate(mu, sigma)`: `exp(normalvariate(mu, sigma))`. +fn lognormvariate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let LognormArgs { mu, sigma } = LognormArgs::from_args(args, vm)?; + defer_drop!(mu, vm); + defer_drop!(sigma, vm); + let (mu, sigma) = (to_float(mu, vm)?, to_float(sigma, vm)?); + let z = target.with_generator(vm, |random, vm| normal_deviate(random.rng(), &vm.heap.tracker))?; + let exponent = mu + z * sigma; + let result = exponent.exp(); + if result.is_infinite() && exponent.is_finite() { + Err(ExcType::overflow_math_range()) + } else { + Ok(Value::Float(result)) + } +} + +/// `expovariate(lambd=1.0)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.expovariate", style = def)] +struct ExpovariateArgs { + #[from_args(default = Value::Float(1.0))] + lambd: Value, +} + +/// `expovariate(lambd=1.0)`: `-log(1 - random()) / lambd`. +fn expovariate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let ExpovariateArgs { lambd } = ExpovariateArgs::from_args(args, vm)?; + defer_drop!(lambd, vm); + let lambd = to_float(lambd, vm)?; + let r = target.with_generator(vm, |random, _| random.rng().random()); + let numerator = -(1.0 - r).ln(); + Ok(Value::Float(float_div(numerator, lambd)?)) +} + +/// `vonmisesvariate(mu, kappa)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.vonmisesvariate", style = def)] +struct VonmisesArgs { + mu: Value, + kappa: Value, +} + +/// `vonmisesvariate(mu, kappa)`: Fisher's circular distribution algorithm. +#[expect( + clippy::many_single_char_names, + reason = "the paper's names, as random.py keeps them" +)] +fn vonmisesvariate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let VonmisesArgs { mu, kappa } = VonmisesArgs::from_args(args, vm)?; + defer_drop!(mu, vm); + defer_drop!(kappa, vm); + let (mu, kappa) = (to_float(mu, vm)?, to_float(kappa, vm)?); + target.with_generator(vm, |random, vm| { + let rng = random.rng(); + if kappa <= 1e-6 { + return Ok(Value::Float(TAU * rng.random())); + } + let s = 0.5 / kappa; + let r = s + (1.0 + s * s).sqrt(); + let mut attempts = 0usize; + let z = loop { + vm.heap.tracker.check_time_every(attempts)?; + attempts = attempts.wrapping_add(1); + let u1 = rng.random(); + let z = (PI * u1).cos(); + let d = z / (r + z); + let u2 = rng.random(); + if u2 < 1.0 - d * d || u2 <= (1.0 - d) * d.exp() { + break z; + } + }; + let q = 1.0 / r; + let f = (q + z) / (1.0 + q * z); + let u3 = rng.random(); + let result = if u3 > 0.5 { + py_fmod(mu + f.acos(), TAU) + } else { + py_fmod(mu - f.acos(), TAU) + }; + Ok(Value::Float(result)) + }) +} + +/// `gammavariate(alpha, beta)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.gammavariate", style = def)] +struct GammaArgs { + alpha: Value, + beta: Value, +} + +/// `gammavariate(alpha, beta)`: the gamma distribution, by Cheng's method +/// above `alpha == 1`, exponential at it, and Kennedy & Gentle's below. +fn gammavariate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let GammaArgs { alpha, beta } = GammaArgs::from_args(args, vm)?; + defer_drop!(alpha, vm); + defer_drop!(beta, vm); + let (alpha, beta) = (to_float(alpha, vm)?, to_float(beta, vm)?); + if alpha <= 0.0 || beta <= 0.0 { + return Err(ExcType::value_error("gammavariate: alpha and beta must be > 0.0")); + } + target + .with_generator(vm, |random, vm| { + gamma_deviate(random.rng(), alpha, beta, &vm.heap.tracker) + }) + .map(Value::Float) +} + +/// The `gammavariate` body for validated `alpha`/`beta`. +#[expect( + clippy::float_cmp, + reason = "`alpha == 1.0` is the exact branch condition in random.py" +)] +fn gamma_deviate(rng: &mut Mt19937, alpha: f64, beta: f64, tracker: &ResourceTracker) -> RunResult { + let log4 = 4f64.ln(); + let sg_magicconst = 1.0 + 4.5f64.ln(); + let mut attempts = 0usize; + if alpha > 1.0 { + let ainv = (2.0 * alpha - 1.0).sqrt(); + let bbb = alpha - log4; + let ccc = alpha + ainv; + loop { + tracker.check_time_every(attempts)?; + attempts = attempts.wrapping_add(1); + let u1 = rng.random(); + if !(1e-7 < u1 && u1 < 0.999_999_9) { + continue; + } + let u2 = 1.0 - rng.random(); + let v = (u1 / (1.0 - u1)).ln() / ainv; + let x = alpha * v.exp(); + let z = u1 * u1 * u2; + let r = bbb + ccc * v - x; + if r + sg_magicconst - 4.5 * z >= 0.0 || r >= z.ln() { + return Ok(x * beta); + } + } + } else if alpha == 1.0 { + Ok(-(1.0 - rng.random()).ln() * beta) + } else { + loop { + tracker.check_time_every(attempts)?; + attempts = attempts.wrapping_add(1); + let u = rng.random(); + let b = (E + alpha) / E; + let p = b * u; + let x = if p <= 1.0 { + p.powf(1.0 / alpha) + } else { + -((b - p) / alpha).ln() + }; + let u1 = rng.random(); + let accept = if p > 1.0 { + u1 <= x.powf(alpha - 1.0) + } else { + u1 <= (-x).exp() + }; + if accept { + return Ok(x * beta); + } + } + } +} + +/// `betavariate(alpha, beta)` — parsed separately to preserve its error messages. +#[derive(FromArgs)] +#[from_args(name = "Random.betavariate", style = def)] +struct BetaArgs { + alpha: Value, + beta: Value, +} + +/// `betavariate(alpha, beta)`: a ratio of two gamma deviates. +fn betavariate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let BetaArgs { alpha, beta } = BetaArgs::from_args(args, vm)?; + defer_drop!(alpha, vm); + defer_drop!(beta, vm); + let (alpha, beta) = (to_float(alpha, vm)?, to_float(beta, vm)?); + // Both inner `gammavariate` calls validate; the first rejects `alpha`, + // and `beta` only gets checked once `y` is non-zero, as in CPython. + if alpha <= 0.0 { + return Err(ExcType::value_error("gammavariate: alpha and beta must be > 0.0")); + } + let y = target.with_generator(vm, |random, vm| { + gamma_deviate(random.rng(), alpha, 1.0, &vm.heap.tracker) + })?; + if y == 0.0 { + return Ok(Value::Float(0.0)); + } + if beta <= 0.0 { + return Err(ExcType::value_error("gammavariate: alpha and beta must be > 0.0")); + } + let z = target.with_generator(vm, |random, vm| { + gamma_deviate(random.rng(), beta, 1.0, &vm.heap.tracker) + })?; + Ok(Value::Float(y / (y + z))) +} + +/// `paretovariate(alpha)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.paretovariate", style = def)] +struct ParetoArgs { + alpha: Value, +} + +/// `paretovariate(alpha)`: `(1 - random()) ** (-1 / alpha)`. +fn paretovariate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let ParetoArgs { alpha } = ParetoArgs::from_args(args, vm)?; + defer_drop!(alpha, vm); + let alpha = to_float(alpha, vm)?; + let u = 1.0 - target.with_generator(vm, |random, _| random.rng().random()); + float_pow(u, float_div(-1.0, alpha)?).map(Value::Float) +} + +/// `weibullvariate(alpha, beta)` — parsed separately to preserve its error messages. +#[derive(FromArgs)] +#[from_args(name = "Random.weibullvariate", style = def)] +struct WeibullArgs { + alpha: Value, + beta: Value, +} + +/// `weibullvariate(alpha, beta)`: `alpha * (-log(1 - random())) ** (1 / beta)`. +fn weibullvariate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let WeibullArgs { alpha, beta } = WeibullArgs::from_args(args, vm)?; + defer_drop!(alpha, vm); + defer_drop!(beta, vm); + let (alpha, beta) = (to_float(alpha, vm)?, to_float(beta, vm)?); + let u = 1.0 - target.with_generator(vm, |random, _| random.rng().random()); + Ok(Value::Float(alpha * float_pow(-u.ln(), float_div(1.0, beta)?)?)) +} + +/// `binomialvariate(n=1, p=0.5)` — a Python `def`. +#[derive(FromArgs)] +#[from_args(name = "Random.binomialvariate", style = def)] +struct BinomialArgs { + #[from_args(default = Value::Int(1))] + n: Value, + #[from_args(default = Value::Float(0.5))] + p: Value, +} + +/// `binomialvariate(n=1, p=0.5)`: successes in `n` trials — Devroye's +/// geometric method for small `n * p`, Hörmann's BTRS otherwise. +#[expect( + clippy::float_cmp, + reason = "`p == 0.0` / `p == 1.0` are exact edge cases in random.py" +)] +fn binomialvariate(target: RandomTarget, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let BinomialArgs { n, p } = BinomialArgs::from_args(args, vm)?; + defer_drop!(n, vm); + defer_drop!(p, vm); + let n = n.as_int(vm)?; + let p = to_float(p, vm)?; + if n < 0 { + return Err(ExcType::value_error("n must be non-negative")); + } + if p <= 0.0 || p >= 1.0 { + return if p == 0.0 { + Ok(Value::Int(0)) + } else if p == 1.0 { + Ok(Value::Int(n)) + } else { + Err(ExcType::value_error("p must be in the range 0.0 <= p <= 1.0")) + }; + } + target + .with_generator(vm, |random, vm| binomial_deviate(random.rng(), n, p, &vm.heap.tracker)) + .map(Value::Int) +} + +/// The `binomialvariate` body for validated `n` and `0 < p < 1`. +#[expect(clippy::cast_possible_truncation, reason = "floors of values bounded by n")] +#[expect(clippy::cast_precision_loss, reason = "n as f64, as CPython computes n * p")] +#[expect( + clippy::many_single_char_names, + reason = "the paper's names, as random.py keeps them" +)] +fn binomial_deviate(rng: &mut Mt19937, n: i64, p: f64, tracker: &ResourceTracker) -> RunResult { + if n == 1 { + return Ok(i64::from(rng.random() < p)); + } + // Exploit symmetry to establish p <= 0.5. + if p > 0.5 { + return Ok(n - binomial_deviate(rng, n, 1.0 - p, tracker)?); + } + let n_f = n as f64; + let mut attempts = 0usize; + if n_f * p < 10.0 { + // BG: Devroye's geometric method, O(np). + let mut x: i64 = 0; + let mut y: i64 = 0; + let c = (1.0 - p).log2(); + if c == 0.0 { + return Ok(x); + } + loop { + tracker.check_time_every(attempts)?; + attempts = attempts.wrapping_add(1); + let r = rng.random(); + if r == 0.0 { + // Retry zero draws before taking their logarithm. + continue; + } + y = y.saturating_add((r.log2() / c).floor() as i64).saturating_add(1); + if y > n { + return Ok(x); + } + x += 1; + } + } + + // BTRS: transformed rejection with squeeze (Hörmann). `random.py` asserts + // its precondition here, which only a NaN `p` can fail. + if !(n_f * p >= 10.0 && p <= 0.5) { + return Err(SimpleException::new(ExcType::AssertionError, None).into()); + } + let spq = (n_f * p * (1.0 - p)).sqrt(); + let b = 1.15 + 2.53 * spq; + let a = -0.0873 + 0.0248 * b + 0.01 * p; + let c = n_f * p + 0.5; + let vr = 0.92 - 4.2 / b; + let mut setup: Option<(f64, f64, f64, f64)> = None; + loop { + tracker.check_time_every(attempts)?; + attempts = attempts.wrapping_add(1); + let u = rng.random() - 0.5; + let us = 0.5 - u.abs(); + if us == 0.0 { + // Retry before dividing by zero in the proposal below. + continue; + } + let k = ((2.0 * a / us + b) * u + c).floor(); + if k < 0.0 || k > n_f { + continue; + } + let k_int = k as i64; + let mut v = rng.random(); + if us >= 0.07 && v <= vr { + return Ok(k_int); + } + let (alpha, lpq, m, h) = *setup.get_or_insert_with(|| { + let alpha = (2.83 + 5.1 / b) * spq; + let lpq = (p / (1.0 - p)).ln(); + let m = ((n_f + 1.0) * p).floor(); + let h = libm::lgamma(m + 1.0) + libm::lgamma(n_f - m + 1.0); + (alpha, lpq, m, h) + }); + v *= alpha / (a / (us * us) + b); + if v.ln() <= h - libm::lgamma(k + 1.0) - libm::lgamma(n_f - k + 1.0) + (k - m) * lpq { + return Ok(k_int); + } + } +} + +/// Python's `float % float`: the result takes the divisor's sign. +fn py_fmod(a: f64, b: f64) -> f64 { + let r = a % b; + if r != 0.0 && (r < 0.0) != (b < 0.0) { r + b } else { r } +} + +/// Python's `float / float`, raising on a zero divisor. +fn float_div(numerator: f64, divisor: f64) -> RunResult { + if divisor == 0.0 { + Err(ExcType::zero_division().into()) + } else { + Ok(numerator / divisor) + } +} + +/// Coerces a distribution parameter to a float, as the arithmetic in +/// `random.py` would; non-numbers raise `math`'s wording. +fn to_float(value: &Value, vm: &VM<'_>) -> RunResult { + match value { + Value::Float(f) => Ok(*f), + #[expect(clippy::cast_precision_loss, reason = "int to float, as Python arithmetic does")] + Value::Int(i) => Ok(*i as f64), + Value::Bool(b) => Ok(if *b { 1.0 } else { 0.0 }), + _ => match value.as_long_int(vm) { + Some(big) => bigint_to_f64_checked(big), + None => Err(ExcType::type_error(format!( + "must be real number, not {}", + value.py_type_name(vm) + ))), + }, + } +} diff --git a/crates/bashkit-monty/src/modules/re.rs b/crates/bashkit-monty/src/modules/re.rs new file mode 100644 index 000000000..588f11f64 --- /dev/null +++ b/crates/bashkit-monty/src/modules/re.rs @@ -0,0 +1,903 @@ +//! Implementation of the `re` module. +//! +//! Provides regular expression matching operations. +//! Uses the Rust `fancy-regex` crate. +//! +//! # Supported module-level functions +//! +//! - `re.compile(pattern, flags=0)` → `re.Pattern` +//! - `re.search(pattern, string, flags=0)` → `re.Match` or `None` +//! - `re.match(pattern, string, flags=0)` → `re.Match` or `None` +//! - `re.fullmatch(pattern, string, flags=0)` → `re.Match` or `None` +//! - `re.findall(pattern, string, flags=0)` → `list` +//! - `re.sub(pattern, repl, string, count=0, flags=0)` → `str` +//! - `re.split(pattern, string, maxsplit=0, flags=0)` → `list` +//! - `re.finditer(pattern, string, flags=0)` → iterator of `re.Match` +//! - `re.escape(pattern)` → `str` +//! +//! Like CPython's pure-Python `re` functions, all arguments are accepted +//! positionally or by keyword, and `pattern` may be a `str` or an +//! already-compiled `re.Pattern` (in which case non-zero `flags` raise +//! `ValueError`). Signature errors use `#[from_args(style = def)]` so their +//! wording matches CPython's `def` binding exactly. +//! +//! # Module attributes +//! +//! - `re.NOFLAG` - no flag (value: 0) +//! - `re.IGNORECASE` / `re.I` — case-insensitive matching (value: 2) +//! - `re.MULTILINE` / `re.M` — `^`/`$` match at line boundaries (value: 8) +//! - `re.DOTALL` / `re.S` — `.` matches newlines (value: 16) +//! - `re.ASCII` / `re.A` — ASCII-only matching for `\w`, `\d`, `\s` (value: 256) +//! - `re.PatternError` / `re.error` — exception type for invalid patterns + +use std::rc::Rc; + +use ahash::RandomState; + +use crate::{ + args::{ArgValues, FromArgs}, + builtins::Builtins, + bytecode::{CallResult, VM}, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{ContainsHeap, DropWithContext, Heap, HeapData, HeapId}, + intern::StaticStrings, + modules::ModuleFunctions, + types::{ + BoundedCompileError, Module, RePattern, Type, + re_pattern::{extract_count, extract_maxsplit, translate_replacement}, + str::allocate_string, + }, + value::Value, +}; + +/// Python regex flag: no flag being applied. +pub(crate) const NOFLAG: u16 = 0; +/// Python regex flag: case-insensitive matching. +pub(crate) const IGNORECASE: u16 = 2; +/// Python regex flag: `^` and `$` match at line boundaries. +pub(crate) const MULTILINE: u16 = 8; +/// Python regex flag: `.` matches newlines. +pub(crate) const DOTALL: u16 = 16; +/// Python regex flag: ASCII-only matching for `\w`, `\b`, `\d`, `\s`. +pub(crate) const ASCII: u16 = 256; + +/// Module-level `re` functions (`re.search(pattern, string)`, …), as opposed to the +/// methods on a compiled `re.Pattern`. String patterns go through +/// [`RePatternCache`], so repeated calls usually avoid recompiling. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "lowercase")] +pub(crate) enum ReFunctions { + /// `re.compile(pattern, flags=0)` — compile a pattern into a `re.Pattern` object. + Compile, + /// `re.search(pattern, string, flags=0)` — find first match anywhere in the string. + Search, + /// `re.match(pattern, string, flags=0)` — match anchored at the start. + Match, + /// `re.fullmatch(pattern, string, flags=0)` — match the entire string. + Fullmatch, + /// `re.findall(pattern, string, flags=0)` — return all non-overlapping matches. + Findall, + /// `re.sub(pattern, repl, string, count=0, flags=0)` — substitute matches. + Sub, + /// `re.split(pattern, string, maxsplit=0, flags=0)` — split string by pattern. + Split, + /// `re.finditer(pattern, string, flags=0)` — return iterator over all matches. + Finditer, + /// `re.escape(pattern)` — escape all non-alphanumeric characters in pattern. + Escape, +} + +/// Allocates the `re` module — every [`ReFunctions`] variant plus the flag +/// constants — and returns its `HeapId`. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Re, vm.interns); + + // Functions + module.set_attr( + StaticStrings::Compile, + Value::ModuleFunction(ModuleFunctions::Re(ReFunctions::Compile)), + vm, + ); + module.set_attr( + StaticStrings::Search, + Value::ModuleFunction(ModuleFunctions::Re(ReFunctions::Search)), + vm, + ); + module.set_attr( + StaticStrings::Match, + Value::ModuleFunction(ModuleFunctions::Re(ReFunctions::Match)), + vm, + ); + module.set_attr( + StaticStrings::Fullmatch, + Value::ModuleFunction(ModuleFunctions::Re(ReFunctions::Fullmatch)), + vm, + ); + module.set_attr( + StaticStrings::Findall, + Value::ModuleFunction(ModuleFunctions::Re(ReFunctions::Findall)), + vm, + ); + module.set_attr( + StaticStrings::Sub, + Value::ModuleFunction(ModuleFunctions::Re(ReFunctions::Sub)), + vm, + ); + module.set_attr( + StaticStrings::Split, + Value::ModuleFunction(ModuleFunctions::Re(ReFunctions::Split)), + vm, + ); + module.set_attr( + StaticStrings::Finditer, + Value::ModuleFunction(ModuleFunctions::Re(ReFunctions::Finditer)), + vm, + ); + module.set_attr( + StaticStrings::Escape, + Value::ModuleFunction(ModuleFunctions::Re(ReFunctions::Escape)), + vm, + ); + + // Flag constants + module.set_attr(StaticStrings::NoFlag, Value::Int(i64::from(NOFLAG)), vm); + module.set_attr(StaticStrings::Ignorecase, Value::Int(i64::from(IGNORECASE)), vm); + module.set_attr(StaticStrings::AsciiI, Value::Int(i64::from(IGNORECASE)), vm); + module.set_attr(StaticStrings::MultilineFlag, Value::Int(i64::from(MULTILINE)), vm); + module.set_attr(StaticStrings::AsciiM, Value::Int(i64::from(MULTILINE)), vm); + module.set_attr(StaticStrings::DotallFlag, Value::Int(i64::from(DOTALL)), vm); + module.set_attr(StaticStrings::AsciiS, Value::Int(i64::from(DOTALL)), vm); + module.set_attr(StaticStrings::AsciiFlag, Value::Int(i64::from(ASCII)), vm); + module.set_attr(StaticStrings::AsciiA, Value::Int(i64::from(ASCII)), vm); + + // Exception types + module.set_attr( + StaticStrings::PatternError, + Value::Builtin(Builtins::ExcType(ExcType::RePatternError)), + vm, + ); + // `re.error` is the historical alias for `re.PatternError` (still widely used) + module.set_attr( + StaticStrings::Error, + Value::Builtin(Builtins::ExcType(ExcType::RePatternError)), + vm, + ); + + // Constructed types + module.set_attr( + StaticStrings::PatternClass, + Value::Builtin(Builtins::Type(Type::RePattern)), + vm, + ); + module.set_attr( + StaticStrings::MatchClass, + Value::Builtin(Builtins::Type(Type::ReMatch)), + vm, + ); + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a call to a `re` module function. Always `CallResult::Value` — regex +/// operations never need host involvement. +pub(super) fn call(vm: &mut VM<'_>, function: ReFunctions, args: ArgValues) -> RunResult { + match function { + ReFunctions::Compile => call_compile(vm, args).map(CallResult::Value), + ReFunctions::Search => call_search(vm, args).map(CallResult::Value), + ReFunctions::Match => call_match(vm, args).map(CallResult::Value), + ReFunctions::Fullmatch => call_fullmatch(vm, args).map(CallResult::Value), + ReFunctions::Findall => call_findall(vm, args).map(CallResult::Value), + ReFunctions::Sub => call_sub(vm, args).map(CallResult::Value), + ReFunctions::Split => call_split(vm, args).map(CallResult::Value), + ReFunctions::Finditer => call_finditer(vm, args).map(CallResult::Value), + ReFunctions::Escape => call_escape(vm, args).map(CallResult::Value), + } +} + +/// `re.compile(pattern, flags=0)` — returns a reusable `re.Pattern`. An +/// already-compiled pattern passes through unchanged (`re.compile(p) is p`, +/// matching CPython's `_compile`). +fn call_compile(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReCompileArgs { pattern, flags } = ReCompileArgs::from_args(args, vm)?; + match resolve_pattern(pattern, flags, vm)? { + // Clone out of the shared cache entry: the returned `re.Pattern` is the + // user's own object, independent of the cache. + ResolvedPattern::Cached(compiled) => Ok(Value::Ref( + vm.heap.allocate(HeapData::RePattern(Box::new((*compiled).clone()))), + )), + // Ownership of the extracted value transfers straight to the caller, + // so the refcount taken at argument extraction is the caller's. + ResolvedPattern::Heap(value) => Ok(value), + } +} + +/// `re.search(pattern, string, flags=0)` — scan for a match anywhere in the string, +/// returning a `re.Match` or `None`. +fn call_search(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReSearchArgs { pattern, string, flags } = ReSearchArgs::from_args(args, vm)?; + defer_drop!(string, vm); + let resolved = resolve_pattern(pattern, flags, vm)?; + defer_drop!(resolved, vm); + resolved.get(vm.heap).search(string, subject_str(string, vm)?, vm.heap) +} + +/// `re.match(pattern, string, flags=0)` — match anchored at position 0, returning a +/// `re.Match` or `None`. +fn call_match(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReMatchArgs { pattern, string, flags } = ReMatchArgs::from_args(args, vm)?; + defer_drop!(string, vm); + let resolved = resolve_pattern(pattern, flags, vm)?; + defer_drop!(resolved, vm); + resolved + .get(vm.heap) + .match_start(string, subject_str(string, vm)?, vm.heap) +} + +/// `re.fullmatch(pattern, string, flags=0)` — match the whole string, returning a +/// `re.Match` or `None`. +fn call_fullmatch(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReFullmatchArgs { pattern, string, flags } = ReFullmatchArgs::from_args(args, vm)?; + defer_drop!(string, vm); + let resolved = resolve_pattern(pattern, flags, vm)?; + defer_drop!(resolved, vm); + resolved + .get(vm.heap) + .fullmatch(string, subject_str(string, vm)?, vm.heap) +} + +/// `re.findall(pattern, string, flags=0)` — all non-overlapping matches, as a list of +/// strings or of tuples depending on the capture-group count (as CPython). +fn call_findall(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReFindallArgs { pattern, string, flags } = ReFindallArgs::from_args(args, vm)?; + defer_drop!(string, vm); + let resolved = resolve_pattern(pattern, flags, vm)?; + defer_drop!(resolved, vm); + resolved.get(vm.heap).findall(subject_str(string, vm)?, vm.heap) +} + +/// `re.sub(pattern, repl, string, count=0, flags=0)` — replace matches; `count=0` +/// replaces all. +/// +/// The pattern resolves *before* `count` is validated, so a bad pattern (or flags +/// with a compiled pattern) wins over a bad count — as in CPython, where `_compile` +/// runs before `Pattern.sub` parses its arguments. +fn call_sub(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReSubArgs { + pattern, + repl, + string, + count, + flags, + } = ReSubArgs::from_args(args, vm)?; + defer_drop!(string, vm); + defer_drop!(repl, vm); + // `count` must outlive `resolve_pattern`'s `?` (pattern errors win over a + // bad count, so it cannot be extracted yet) — guard it, then `take` it out. + defer_drop_mut!(count, vm); + let resolved = resolve_pattern(pattern, flags, vm)?; + defer_drop!(resolved, vm); + + let count = extract_count(count.take(), vm)?; + + // CPython parses the replacement template before its match loop, so a bad + // replacement raises even when a negative count skips matching. + let Ok(repl) = repl.to_str(vm) else { + return Err(ExcType::type_error( + "callable replacement is not yet supported in re.sub()", + )); + }; + + let Some(count) = count else { + // Reject out-of-range octal escapes even when the negative count skips matching. + translate_replacement(repl)?; + // Negative count — re.sub returns the input string unchanged. + // CPython still type-checks the subject before its (empty) match + // loop, so validate first, then just bump the refcount; no need to + // re-allocate (the guard drops the extraction's reference, the + // clone is the caller's). + let _ = subject_str(string, vm)?; + return Ok(string.clone_with_heap(vm.heap)); + }; + + resolved + .get(vm.heap) + .sub(repl, subject_str(string, vm)?, count, vm.heap) +} + +/// `re.split(pattern, string, maxsplit=0, flags=0)` — split on pattern occurrences. +/// A non-zero `maxsplit` caps the splits, leaving the remainder as the final element. +fn call_split(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReSplitArgs { + pattern, + string, + maxsplit, + flags, + } = ReSplitArgs::from_args(args, vm)?; + defer_drop!(string, vm); + // As in `call_sub`: `maxsplit` must survive a pattern/flags error, so + // guard it before `resolve_pattern` and `take` it out afterwards. + defer_drop_mut!(maxsplit, vm); + let resolved = resolve_pattern(pattern, flags, vm)?; + defer_drop!(resolved, vm); + + let maxsplit = extract_maxsplit(maxsplit.take(), vm)?; + resolved.get(vm.heap).split(subject_str(string, vm)?, maxsplit, vm.heap) +} + +/// Argument shape for `re.sub(pattern, repl, string, count=0, flags=0)`. +/// +/// `pattern` / `string` need `static_string =` overrides because the `Pattern` / +/// `String` interner entries are taken (by the `re.Pattern` class name and +/// `match.string`); the interned text is still `"pattern"` / `"string"`. +/// +/// Every field is a raw `Value`: CPython's `def` binding never type-checks, so all +/// coercion happens in the body, in CPython's error order. +#[derive(FromArgs)] +#[from_args(name = "sub", style = def)] +struct ReSubArgs { + #[from_args(static_string = "PatternAttr")] + pattern: Value, + repl: Value, + #[from_args(static_string = "StringAttr")] + string: Value, + #[from_args(default)] + count: Option, + #[from_args(default = Value::Int(0))] + flags: Value, +} + +/// Argument shape for `re.split(pattern, string, maxsplit=0, flags=0)`. +/// +/// See `ReSubArgs` for why `pattern` / `string` use `static_string`. +#[derive(FromArgs)] +#[from_args(name = "split", style = def)] +struct ReSplitArgs { + #[from_args(static_string = "PatternAttr")] + pattern: Value, + #[from_args(static_string = "StringAttr")] + string: Value, + #[from_args(default)] + maxsplit: Option, + #[from_args(default = Value::Int(0))] + flags: Value, +} + +/// Argument shape for `re.compile(pattern, flags=0)`. +#[derive(FromArgs)] +#[from_args(name = "compile", style = def)] +struct ReCompileArgs { + #[from_args(static_string = "PatternAttr")] + pattern: Value, + #[from_args(default = Value::Int(0))] + flags: Value, +} + +/// Argument shape for `re.escape(pattern)`. +/// +/// `pattern` stays a plain `Value`: CPython's `escape` is a str-only helper +/// whose non-str error (the `decoding to str: …` fallback) differs from the +/// pattern wording [`PatternArg`] produces. +#[derive(FromArgs)] +#[from_args(name = "escape", style = def)] +struct ReEscapeArgs { + #[from_args(static_string = "PatternAttr")] + pattern: Value, +} + +/// Argument shape for `re.search(pattern, string, flags=0)`; `re.match`, +/// `re.fullmatch`, `re.findall`, and `re.finditer` share it under their own +/// names below (the function name is baked into each struct's errors). +/// +/// See `ReSubArgs` for why `pattern` / `string` use `static_string`. +#[derive(FromArgs)] +#[from_args(name = "search", style = def)] +struct ReSearchArgs { + #[from_args(static_string = "PatternAttr")] + pattern: Value, + #[from_args(static_string = "StringAttr")] + string: Value, + #[from_args(default = Value::Int(0))] + flags: Value, +} + +/// Argument shape for `re.match(pattern, string, flags=0)` — see [`ReSearchArgs`]. +#[derive(FromArgs)] +#[from_args(name = "match", style = def)] +struct ReMatchArgs { + #[from_args(static_string = "PatternAttr")] + pattern: Value, + #[from_args(static_string = "StringAttr")] + string: Value, + #[from_args(default = Value::Int(0))] + flags: Value, +} + +/// Argument shape for `re.fullmatch(pattern, string, flags=0)` — see [`ReSearchArgs`]. +#[derive(FromArgs)] +#[from_args(name = "fullmatch", style = def)] +struct ReFullmatchArgs { + #[from_args(static_string = "PatternAttr")] + pattern: Value, + #[from_args(static_string = "StringAttr")] + string: Value, + #[from_args(default = Value::Int(0))] + flags: Value, +} + +/// Argument shape for `re.findall(pattern, string, flags=0)` — see [`ReSearchArgs`]. +#[derive(FromArgs)] +#[from_args(name = "findall", style = def)] +struct ReFindallArgs { + #[from_args(static_string = "PatternAttr")] + pattern: Value, + #[from_args(static_string = "StringAttr")] + string: Value, + #[from_args(default = Value::Int(0))] + flags: Value, +} + +/// Argument shape for `re.finditer(pattern, string, flags=0)` — see [`ReSearchArgs`]. +#[derive(FromArgs)] +#[from_args(name = "finditer", style = def)] +struct ReFinditerArgs { + #[from_args(static_string = "PatternAttr")] + pattern: Value, + #[from_args(static_string = "StringAttr")] + string: Value, + #[from_args(default = Value::Int(0))] + flags: Value, +} + +/// Validates the `string` subject and borrows its text from the heap, zero-copy. +/// +/// Runs *after* binding and pattern/flags resolution — CPython's `def` binds without +/// type checks and only the C match machinery rejects a bad subject — so arity, +/// pattern, and flags errors always win. Monty has no bytes matching: a bytes subject +/// gets CPython's mixed-types message, anything else the `sre` wording. +fn subject_str<'a>(value: &'a Value, vm: &'a VM<'_>) -> RunResult<&'a str> { + if value.is_str(vm.heap) { + value.to_str(vm) + } else if value.py_type_heap(vm.heap) == Type::Bytes { + // Monty patterns are always str, so a bytes subject is always + // CPython's string-pattern/bytes-subject mismatch. + Err(ExcType::type_error( + "cannot use a string pattern on a bytes-like object", + )) + } else { + // sre reports `type(x).__name__`, so `None` reads 'NoneType'. + Err(ExcType::type_error(format!( + "expected string or bytes-like object, got '{}'", + value.py_type_name(vm) + ))) + } +} + +/// The `pattern` argument for module-level `re` functions: an owned pattern string, +/// or a live compiled `re.Pattern` that CPython's `_compile` passes through. Anything +/// else — including `bytes`, as Monty has no bytes patterns — gets CPython's +/// `first argument must be …` error. +/// +/// Coerced in the function body (via [`resolve_pattern`]), not as a `FromArgs` field +/// type: CPython's `def` never type-checks, so failing at extraction would wrongly +/// preempt arity errors (`re.search(123)` must report the missing `string`). +pub(crate) enum PatternArg { + /// A `str` pattern, copied out because compilation stores it. + Str(String), + /// An already-compiled `re.Pattern` heap value (ownership transferred in; + /// dropped by [`resolve_pattern`]'s error path, `drop_with`, or the + /// eventual consumer). + Compiled(Value), +} + +impl PatternArg { + /// Coerces the raw `pattern` value, consuming it on every path (the + /// `Compiled` variant transfers ownership in rather than dropping). + fn extract(value: Value, vm: &mut VM<'_>) -> RunResult { + if let Some(either) = value.as_either_str(vm.heap) { + let pattern = either.into_string(vm.interns); + value.drop_with(vm); + Ok(Self::Str(pattern)) + } else if value.py_type_heap(vm.heap) == Type::RePattern { + Ok(Self::Compiled(value)) + } else { + value.drop_with(vm); + Err(ExcType::type_error("first argument must be string or compiled pattern")) + } + } +} + +impl DropWithContext for PatternArg { + fn drop_with(self, heap: &mut C) { + if let Self::Compiled(value) = self { + value.drop_with(heap); + } + } +} + +/// The `flags` argument: a non-negative integer fitting `u16`, `bool` accepted as +/// 0/1. Coerced in the function body like [`PatternArg`] so arity errors win. +/// +/// A non-int reports CPython's incidental `unsupported operand type(s) for &` — what +/// its `parse` raises when it first ANDs the flags — so the message matches exactly. +/// Out-of-range ints keep Monty's clearer wording (see `limitations/re.md`). +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct ReFlags(u16); + +impl ReFlags { + /// Coerces the raw `flags` value, consuming it on every path. + fn extract(value: Value, vm: &mut VM<'_>) -> RunResult { + let result = match value { + Value::Int(n) => u16::try_from(n) + .map(Self) + .map_err(|_| ExcType::type_error("flags must be a non-negative integer")), + Value::Bool(b) => Ok(Self(u16::from(b))), + _ => Err(ExcType::binary_type_error( + "&", + value.py_type_heap(vm.heap), + value.py_type_name(vm), + "int", + )), + }; + value.drop_with(vm); + result + } +} + +impl ReFlags { + /// The raw flags bits. + fn get(self) -> u16 { + self.0 + } +} + +/// A pattern ready to run: shared out of the [`RePatternCache`], or a still-live +/// `re.Pattern` heap value (which callers keep alive with `defer_drop!`). +enum ResolvedPattern { + /// Compiled from a `str` pattern and shared (`Rc`) with the pattern cache + /// (or uncached when its compiled form exceeds [`CACHED_SIZE_LIMIT`]). + Cached(Rc), + /// A live `re.Pattern` heap value (always a `Value::Ref` to + /// `HeapData::RePattern`, guaranteed by [`PatternArg::extract`]). + Heap(Value), +} + +impl ResolvedPattern { + /// Borrows the compiled pattern (from the heap for the `Heap` variant). + fn get<'a>(&'a self, heap: &'a Heap) -> &'a RePattern { + match self { + Self::Cached(pattern) => pattern, + Self::Heap(value) => { + let Value::Ref(heap_id) = value else { + unreachable!("ResolvedPattern::Heap always holds a heap ref") + }; + match heap.get(*heap_id) { + HeapData::RePattern(pattern) => pattern, + _ => unreachable!("ResolvedPattern::Heap always points at a re.Pattern"), + } + } + } + } +} + +impl DropWithContext for ResolvedPattern { + fn drop_with(self, heap: &mut C) { + if let Self::Heap(value) = self { + value.drop_with(heap); + } + // `Cached` holds only an `Rc` (no heap references); it drops here. + } +} + +/// One slot of [`RePatternCache`]: the key hash plus the shared compiled pattern. +/// The key itself isn't stored — `RePattern` owns the source text and flags, so a +/// hash hit rechecks via [`RePattern::is_compiled_from`] instead of a second copy. +type ReCacheEntry = Option<(u64, Rc)>; + +/// Slot count of [`RePatternCache`] — power of two so the index modulo is a mask; +/// 256 (vs CPython's 512 `re._MAXCACHE`) to halve the untracked worst-case retained +/// memory of `CACHE_CAPACITY × (CACHED_SIZE_LIMIT + CACHED_PATTERN_LIMIT)`. +const CACHE_CAPACITY: usize = 256; + +/// `delegate_size_limit` for compiles retained in the cache. The cache is invisible +/// to the resource tracker, so this caps retained *compiled* size at +/// ~`CACHE_CAPACITY × CACHED_SIZE_LIMIT`. Patterns compiling bigger still work — +/// recompiled per call at default limits, never retained. +const CACHED_SIZE_LIMIT: usize = 64 * 1024; + +/// Longest *source* pattern retained — the text-side counterpart of +/// [`CACHED_SIZE_LIMIT`], and small because an entry holds the text once per +/// `fancy_regex` engine it compiles. Source length says nothing about compiled size +/// (`(?x)a#…` comments compile to nothing), so without it a run could pin +/// `CACHE_CAPACITY` huge patterns under its own memory limit; longer ones stay uncached. +const CACHED_PATTERN_LIMIT: usize = 4 * 1024; + +/// Per-run cache of compiled patterns for module-level `re.*` calls, keyed on +/// `(pattern, flags)` — so `re.split(r'\s+', text)` in a loop compiles once. Mirrors +/// CPython's `re._cache`; not snapshotted (rebuilt on demand). Direct-mapped with +/// 5-slot linear probing and LRU-on-collision (jiter's `py_string_cache` design), +/// bounding retained memory by [`CACHED_SIZE_LIMIT`] and [`CACHED_PATTERN_LIMIT`]. +/// +/// The backing store is allocated lazily on first use: every VM builds a +/// `RePatternCache` but few touch `re`, and zeroing it eagerly measurably regressed +/// the setup-bound benchmarks (`add_two`, `func_call_*`). +#[derive(Default)] +pub(crate) struct RePatternCache(Option<(Box<[ReCacheEntry]>, RandomState)>); + +impl RePatternCache { + /// Returns the compiled pattern for `(pattern, flags)`, compiling and caching on + /// a miss. Nothing is retained for a compile error, or for a pattern over + /// [`CACHED_PATTERN_LIMIT`] / [`CACHED_SIZE_LIMIT`] — those compile uncached. The + /// backing store is allocated here, on the first cacheable call. + fn get_or_compile(&mut self, pattern: &str, flags: u16) -> RunResult> { + // Checked before the store is touched, so a run that only ever uses + // oversized patterns never allocates the slots at all. + if pattern.len() > CACHED_PATTERN_LIMIT { + return Ok(Rc::new(RePattern::compile(pattern.to_owned(), flags)?)); + } + + let (entries, hash_builder) = self + .0 + .get_or_insert_with(|| (vec![None; CACHE_CAPACITY].into_boxed_slice(), RandomState::default())); + + let hash = hash_builder.hash_one((pattern, flags)); + // `hash % CACHE_CAPACITY` is < CACHE_CAPACITY, so it always fits usize. + let hash_index = usize::try_from(hash % CACHE_CAPACITY as u64).expect("index < CACHE_CAPACITY"); + + // Probe up to 5 contiguous slots for a match, remembering the first + // empty slot to fill on a miss. + let mut empty_slot = None; + for index in hash_index..hash_index + 5 { + match entries.get(index) { + Some(Some((entry_hash, compiled))) => { + if *entry_hash == hash && compiled.is_compiled_from(pattern, flags) { + return Ok(Rc::clone(compiled)); + } + } + // First empty slot — a miss lands here. + Some(None) => { + empty_slot = Some(index); + break; + } + // Ran past the end of the array. + None => break, + } + } + + // Miss: compile size-bounded so a retained entry can never pin a huge + // compiled regex. A valid pattern that compiles past the cap is + // recompiled at default limits and returned uncached — it still works, + // just recompiled per call. + let compiled = match RePattern::compile_bounded(pattern.to_owned(), flags, CACHED_SIZE_LIMIT) { + Ok(compiled) => compiled, + Err(BoundedCompileError::TooBig) => { + return Ok(Rc::new(RePattern::compile(pattern.to_owned(), flags)?)); + } + Err(BoundedCompileError::Invalid(err)) => return Err(err), + }; + + // Fill the empty slot, else evict `hash_index` (LRU-on-collision) when + // every probed slot was occupied. + let compiled = Rc::new(compiled); + let slot = empty_slot.unwrap_or(hash_index); + entries[slot] = Some((hash, Rc::clone(&compiled))); + Ok(compiled) + } +} + +/// Coerces the raw `pattern` / `flags` values under CPython's `_compile` rules: +/// string patterns compile with the given flags; compiled patterns pass through but +/// reject non-zero flags with CPython's `ValueError`. +/// +/// Runs after `from_args` has bound the signature, in CPython's order: pattern type, +/// flags type, compiled-pattern flags rejection, then compilation. +fn resolve_pattern(pattern: Value, flags: Value, vm: &mut VM<'_>) -> RunResult { + // Sequential hand-rolled cleanup: each coercion consumes its value, so on + // failure only the *other*, not-yet-consumed value needs dropping. + let pattern = match PatternArg::extract(pattern, vm) { + Ok(pattern) => pattern, + Err(e) => { + flags.drop_with(vm); + return Err(e); + } + }; + let flags = match ReFlags::extract(flags, vm) { + Ok(flags) => flags, + Err(e) => { + pattern.drop_with(vm); + return Err(e); + } + }; + match pattern { + PatternArg::Str(pattern) => Ok(ResolvedPattern::Cached( + vm.re_pattern_cache.get_or_compile(&pattern, flags.get())?, + )), + PatternArg::Compiled(value) => { + if flags.get() == 0 { + Ok(ResolvedPattern::Heap(value)) + } else { + value.drop_with(vm); + Err(ExcType::value_error( + "cannot process flags argument with a compiled pattern", + )) + } + } + } +} + +/// `re.finditer(pattern, string, flags=0)` — return all matches as a list. +/// +/// Eagerly collected, so `for m in re.finditer(...)` iterates the returned list via +/// the VM's `GetIter` opcode. +fn call_finditer(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReFinditerArgs { pattern, string, flags } = ReFinditerArgs::from_args(args, vm)?; + defer_drop!(string, vm); + let resolved = resolve_pattern(pattern, flags, vm)?; + defer_drop!(resolved, vm); + resolved + .get(vm.heap) + .finditer(string, subject_str(string, vm)?, vm.heap) +} + +/// `re.escape(pattern)` — backslash-escape regex metacharacters and whitespace, +/// matching CPython 3.7+: `\t \n \v \f \r # $ & ( ) * + - . ? [ \ ] ^ { | } ~` +fn call_escape(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let ReEscapeArgs { pattern } = ReEscapeArgs::from_args(args, vm)?; + defer_drop!(pattern, vm); + let Ok(text) = pattern.to_str(vm) else { + // CPython's escape() falls back to `str(pattern, 'latin1')` for + // non-str input, so this is the (incidental) message it raises. + let t = pattern.py_type_name(vm); + return Err(ExcType::type_error(format!( + "decoding to str: need a bytes-like object, {t} found" + ))); + }; + + let mut result = String::with_capacity(text.len() * 2); + for c in text.chars() { + if should_escape(c) { + result.push('\\'); + } + result.push(c); + } + + Ok(allocate_string(result, vm.heap)) +} + +/// Returns whether a character should be escaped by `re.escape()`. +/// +/// Matches CPython's `_special_chars_map` — only regex metacharacters and whitespace. +fn should_escape(c: char) -> bool { + matches!( + c, + '\t' | '\n' + | '\x0b' + | '\x0c' + | '\r' + | ' ' + | '#' + | '$' + | '&' + | '(' + | ')' + | '*' + | '+' + | '-' + | '.' + | '?' + | '[' + | '\\' + | ']' + | '^' + | '{' + | '|' + | '}' + | '~' + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Counts the occupied slots in the cache (0 while unallocated). + fn occupied(cache: &RePatternCache) -> usize { + cache + .0 + .as_ref() + .map_or(0, |(entries, _)| entries.iter().filter(|e| e.is_some()).count()) + } + + #[test] + fn hit_shares_one_entry() { + let mut cache = RePatternCache::default(); + let first = cache.get_or_compile(r"\s+", 0).unwrap(); + let second = cache.get_or_compile(r"\s+", 0).unwrap(); + // A hit returns the *same* compiled pattern, not a recompile. + assert!(Rc::ptr_eq(&first, &second)); + assert_eq!(occupied(&cache), 1); + } + + #[test] + fn flags_key_the_entry() { + let mut cache = RePatternCache::default(); + let plain = cache.get_or_compile("abc", 0).unwrap(); + let ignorecase = cache.get_or_compile("abc", IGNORECASE).unwrap(); + // Same pattern text but different flags are distinct entries. + assert!(!Rc::ptr_eq(&plain, &ignorecase)); + assert_eq!(occupied(&cache), 2); + } + + #[test] + fn compile_error_caches_nothing() { + let mut cache = RePatternCache::default(); + // Unbalanced parenthesis fails to compile. + assert!(cache.get_or_compile("(", 0).is_err()); + assert_eq!(occupied(&cache), 0); + } + + /// A counted repeat that expands far past [`CACHED_SIZE_LIMIT`] in the + /// delegated regex compiler while still compiling fine at default limits. + const OVERSIZE_PATTERN: &str = "a{5000}"; + + #[test] + fn oversize_pattern_compiles_but_is_not_retained() { + let mut cache = RePatternCache::default(); + let first = cache.get_or_compile(OVERSIZE_PATTERN, 0).unwrap(); + let second = cache.get_or_compile(OVERSIZE_PATTERN, 0).unwrap(); + // Both calls succeed but nothing is retained: each call recompiles. + assert!(!Rc::ptr_eq(&first, &second)); + assert_eq!(occupied(&cache), 0); + } + + #[test] + fn oversize_pattern_does_not_disturb_cached_entries() { + let mut cache = RePatternCache::default(); + let small = cache.get_or_compile("abc", 0).unwrap(); + cache.get_or_compile(OVERSIZE_PATTERN, 0).unwrap(); + let again = cache.get_or_compile("abc", 0).unwrap(); + // The small pattern's entry survives the uncached oversize compile. + assert!(Rc::ptr_eq(&small, &again)); + assert_eq!(occupied(&cache), 1); + } + + /// A pattern whose source is far past [`CACHED_PATTERN_LIMIT`] but whose + /// compiled form is tiny: `(?x)` verbose mode discards everything from `#` + /// to the newline, so this is just `a`. + fn long_source_pattern() -> String { + format!("(?x)a#{}\n", "z".repeat(CACHED_PATTERN_LIMIT)) + } + + #[test] + fn long_source_pattern_compiles_but_is_not_retained() { + let mut cache = RePatternCache::default(); + let pattern = long_source_pattern(); + let first = cache.get_or_compile(&pattern, 0).unwrap(); + let second = cache.get_or_compile(&pattern, 0).unwrap(); + // Both calls succeed but nothing is retained: each call recompiles. + assert!(!Rc::ptr_eq(&first, &second)); + assert_eq!(occupied(&cache), 0); + } + + #[test] + fn long_source_pattern_does_not_disturb_cached_entries() { + let mut cache = RePatternCache::default(); + let small = cache.get_or_compile("abc", 0).unwrap(); + cache.get_or_compile(&long_source_pattern(), 0).unwrap(); + let again = cache.get_or_compile("abc", 0).unwrap(); + // The small pattern's entry survives the uncached long-source compile. + assert!(Rc::ptr_eq(&small, &again)); + assert_eq!(occupied(&cache), 1); + } + + #[test] + fn occupancy_is_bounded_by_capacity() { + let mut cache = RePatternCache::default(); + // Far more distinct patterns than slots: LRU-on-collision must keep + // the occupied count hard-bounded rather than growing unboundedly. + for i in 0..CACHE_CAPACITY * 4 { + cache.get_or_compile(&format!("pat{i}"), 0).unwrap(); + } + assert!(occupied(&cache) <= CACHE_CAPACITY); + } +} diff --git a/crates/bashkit-monty/src/modules/sys.rs b/crates/bashkit-monty/src/modules/sys.rs new file mode 100644 index 000000000..e1c8aaa7a --- /dev/null +++ b/crates/bashkit-monty/src/modules/sys.rs @@ -0,0 +1,377 @@ +//! Implementation of the `sys` module. +//! +//! `sys` is attribute-only in production builds: every name below is a +//! constant fixed at module creation, since the sandbox has no interpreter +//! state a program is allowed to reach. What Monty exposes is limited to +//! values that are true *of Monty* — the Python version it targets, the +//! properties of the `f64` it stores floats in, the Unicode range, and the +//! fact that it has no install tree, no `__pycache__` and no command line. +//! Structseqs describing CPython's C implementation (`hash_info`, `int_info`, +//! `thread_info`) are deliberately absent rather than fabricated; see +//! `limitations/sys.md`. +//! +//! Under the `test-hooks` feature one callable is also exposed: +//! - `setrecursionlimit(n)`: tighten the active recursion ceiling so fixtures +//! can simulate Monty's lower default depth on CPython too. Only allows +//! *lowering* the host-configured ceiling — see [`SysFunctions`]. + +use smallvec::SmallVec; + +#[cfg(feature = "test-hooks")] +use crate::{ + args::ArgValues, + exception_private::{ExcType, ExcTypeExt, RunResult}, + modules::ModuleFunctions, +}; +use crate::{ + bytecode::VM, + heap::{HeapData, HeapId}, + intern::StaticStrings, + types::{List, Module, NamedTuple, allocate_string, allocate_tuple, long_int::INT_MAX_STR_DIGITS}, + value::{EitherStr, Marker, Value}, +}; + +/// `sys.hexversion` for the version Monty reports: `3.14.0` final, encoded as +/// CPython encodes it — `major << 24 | minor << 16 | micro << 8 | level << 4 | serial`. +const MONTY_HEXVERSION: i64 = 0x030E_00F0; + +/// `sys.api_version` — the CPython 3.14 C API version. +/// +/// Monty has no C API; the number is reported so version-gated code reads the +/// value it expects from the Python version Monty targets. +const CPYTHON_API_VERSION: i64 = 1013; + +/// `sys.maxsize`, pinned to the 64-bit value rather than the host's `isize::MAX`. +/// +/// Monty behaves identically on every target, including 32-bit wasm where the +/// real container ceiling is lower — and resource limits bind long before either. +const MAXSIZE: i64 = i64::MAX; + +/// `sys.maxunicode` — the largest code point, `U+10FFFF`. +const MAXUNICODE: i64 = 0x0010_FFFF; + +/// The modules Monty can import, in the sorted order CPython uses for its own +/// `sys.builtin_module_names`. Every Monty module is compiled into the +/// interpreter, so this is the whole importable set rather than a C-extension +/// subset — keep it in step with [`StandardLib`](super::StandardLib). +const BUILTIN_MODULE_NAMES: &[StaticStrings] = &[ + StaticStrings::Asyncio, + StaticStrings::Base64, + StaticStrings::Binascii, + StaticStrings::Bisect, + StaticStrings::Collections, + StaticStrings::Dataclasses, + StaticStrings::Datetime, + StaticStrings::Functools, + #[cfg(feature = "test-hooks")] + StaticStrings::Gc, + StaticStrings::Itertools, + StaticStrings::Json, + StaticStrings::Math, + StaticStrings::Os, + StaticStrings::Pathlib, + StaticStrings::Random, + StaticStrings::Re, + StaticStrings::Sys, + StaticStrings::Typing, + StaticStrings::Unicodedata, +]; + +/// Functions exposed by the `sys` module under the `test-hooks` feature. +/// +/// Production builds keep `sys` attribute-only; this enum exists so fixtures +/// (and only fixtures) can call back into Monty internals that production +/// sandbox code must never reach. +#[cfg(feature = "test-hooks")] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "lowercase")] +pub(crate) enum SysFunctions { + /// `sys.setrecursionlimit(n)` — tightens the live recursion ceiling to + /// `n`. Only allows lowering; attempting to raise raises `ValueError`. + Setrecursionlimit, +} + +/// Creates the `sys` module and allocates it on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Sys, vm.interns); + + // Interpreter identity. `platform` is "monty" rather than the host OS, which + // the sandbox never reveals. + module.set_attr( + StaticStrings::Platform, + Value::InternString(vm.interns.intern_static(StaticStrings::Monty)), + vm, + ); + module.set_attr( + StaticStrings::Version, + Value::InternString(vm.interns.intern_static(StaticStrings::MontyVersionString)), + vm, + ); + module.set_attr(StaticStrings::VersionInfo, version_info(vm), vm); + module.set_attr(StaticStrings::Hexversion, Value::Int(MONTY_HEXVERSION), vm); + module.set_attr(StaticStrings::ApiVersion, Value::Int(CPYTHON_API_VERSION), vm); + module.set_attr( + StaticStrings::Copyright, + Value::InternString(vm.interns.intern_static(StaticStrings::MontyCopyright)), + vm, + ); + module.set_attr(StaticStrings::BuiltinModuleNames, builtin_module_names(vm), vm); + module.set_attr(StaticStrings::Argv, argv(vm), vm); + + // Numeric and text limits of the value representations Monty actually uses. + module.set_attr(StaticStrings::Maxsize, Value::Int(MAXSIZE), vm); + module.set_attr(StaticStrings::Maxunicode, Value::Int(MAXUNICODE), vm); + module.set_attr( + StaticStrings::Byteorder, + Value::InternString(vm.interns.intern_static(StaticStrings::Little)), + vm, + ); + module.set_attr(StaticStrings::FloatInfo, float_info(vm), vm); + module.set_attr( + StaticStrings::FloatReprStyle, + Value::InternString(vm.interns.intern_static(StaticStrings::Short)), + vm, + ); + + // The sandbox has no install tree, no bytecode cache and no ABI. CPython + // documents the empty string for a path it cannot determine, so these report + // "unknown" instead of raising; `prefix == base_prefix` also answers the + // usual "am I in a virtualenv?" test correctly. + module.set_attr( + StaticStrings::Executable, + Value::InternString(vm.interns.intern_static(StaticStrings::EmptyString)), + vm, + ); + module.set_attr( + StaticStrings::Prefix, + Value::InternString(vm.interns.intern_static(StaticStrings::EmptyString)), + vm, + ); + module.set_attr( + StaticStrings::ExecPrefix, + Value::InternString(vm.interns.intern_static(StaticStrings::EmptyString)), + vm, + ); + module.set_attr( + StaticStrings::BasePrefix, + Value::InternString(vm.interns.intern_static(StaticStrings::EmptyString)), + vm, + ); + module.set_attr( + StaticStrings::BaseExecPrefix, + Value::InternString(vm.interns.intern_static(StaticStrings::EmptyString)), + vm, + ); + module.set_attr( + StaticStrings::Platlibdir, + Value::InternString(vm.interns.intern_static(StaticStrings::Lib)), + vm, + ); + module.set_attr( + StaticStrings::Abiflags, + Value::InternString(vm.interns.intern_static(StaticStrings::EmptyString)), + vm, + ); + module.set_attr(StaticStrings::DontWriteBytecode, Value::Bool(true), vm); + module.set_attr(StaticStrings::PycachePrefix, Value::None, vm); + module.set_attr(StaticStrings::Flags, flags(vm), vm); + + // sys.stdout / sys.stderr - markers for standard output/error + module.set_attr(StaticStrings::Stdout, Value::Marker(Marker(StaticStrings::Stdout)), vm); + module.set_attr(StaticStrings::Stderr, Value::Marker(Marker(StaticStrings::Stderr)), vm); + + // Test-only callables — see the module-level docs and the + // [`test-hooks`] feature gate. + #[cfg(feature = "test-hooks")] + module.set_attr( + StaticStrings::Setrecursionlimit, + Value::ModuleFunction(ModuleFunctions::Sys(SysFunctions::Setrecursionlimit)), + vm, + ); + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Builds `sys.version_info`: `(major=3, minor=14, micro=0, releaselevel='final', serial=0)`. +fn version_info(vm: &VM<'_>) -> Value { + let named_tuple = NamedTuple::new( + EitherStr::Interned(vm.interns.intern_static(StaticStrings::SysVersionInfo)), + vec![ + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Major)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Minor)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Micro)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Releaselevel)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Serial)), + ], + vec![ + Value::Int(3), + Value::Int(14), + Value::Int(0), + Value::InternString(vm.interns.intern_static(StaticStrings::Final)), + Value::Int(0), + ], + ); + Value::Ref(vm.heap.allocate(HeapData::NamedTuple(Box::new(named_tuple)))) +} + +/// Builds `sys.argv`, holding the script name and nothing else. +/// +/// Monty runs no command line, so there are no arguments after `argv[0]`; +/// host-supplied ones are not wired up yet. The name is the script's final +/// path component, the same basis as `__file__`, so a host path never reaches +/// the sandbox. Like CPython's, the list is mutable — but Monty builds a fresh +/// module per `import`, so edits do not survive one (see +/// `limitations/modules.md`). +fn argv(vm: &VM<'_>) -> Value { + let script = allocate_string(vm.env.script_basename(), vm.heap); + Value::Ref(vm.heap.allocate(HeapData::List(List::new(vec![script])))) +} + +/// Builds `sys.float_info` from Rust's `f64` constants. +/// +/// Monty stores every float as an `f64`, so each field is the IEEE 754 +/// binary64 property CPython reports for its own C `double`. `rounds` is `1`, +/// the `FLT_ROUNDS` code for round-to-nearest, which is the only mode Monty +/// can be in — nothing in the sandbox can change the rounding direction. +fn float_info(vm: &VM<'_>) -> Value { + let named_tuple = NamedTuple::new( + EitherStr::Interned(vm.interns.intern_static(StaticStrings::SysFloatInfo)), + vec![ + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Max)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::MaxExp)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Max10Exp)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Min)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::MinExp)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Min10Exp)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Dig)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::MantDig)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Epsilon)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Radix)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Rounds)), + ], + vec![ + Value::Float(f64::MAX), + Value::Int(i64::from(f64::MAX_EXP)), + Value::Int(i64::from(f64::MAX_10_EXP)), + Value::Float(f64::MIN_POSITIVE), + Value::Int(i64::from(f64::MIN_EXP)), + Value::Int(i64::from(f64::MIN_10_EXP)), + Value::Int(i64::from(f64::DIGITS)), + Value::Int(i64::from(f64::MANTISSA_DIGITS)), + Value::Float(f64::EPSILON), + Value::Int(i64::from(f64::RADIX)), + Value::Int(1), + ], + ); + Value::Ref(vm.heap.allocate(HeapData::NamedTuple(Box::new(named_tuple)))) +} + +/// Builds `sys.flags` — the switches the interpreter was started with. +/// +/// Monty is started with none, so every switch reads `0`/`False`. Two fields +/// are not merely "unset" but describe the sandbox: `dont_write_bytecode` is +/// `1` to agree with `sys.dont_write_bytecode`, and `hash_randomization` is +/// `0` because Monty seeds no hashes. `int_max_str_digits` reports the limit +/// Monty actually enforces, though it has no `sys.set_int_max_str_digits` to +/// change it. +fn flags(vm: &VM<'_>) -> Value { + let named_tuple = NamedTuple::new( + EitherStr::Interned(vm.interns.intern_static(StaticStrings::SysFlags)), + vec![ + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Debug)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Inspect)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Interactive)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Optimize)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::DontWriteBytecode)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::NoUserSite)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::NoSite)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::IgnoreEnvironment)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Verbose)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::BytesWarning)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Quiet)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::HashRandomization)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Isolated)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::DevMode)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::Utf8Mode)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::WarnDefaultEncoding)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::SafePath)), + EitherStr::Interned(vm.interns.intern_static(StaticStrings::IntMaxStrDigits)), + ], + vec![ + Value::Int(0), // debug + Value::Int(0), // inspect + Value::Int(0), // interactive + Value::Int(0), // optimize + Value::Int(1), // dont_write_bytecode + Value::Int(0), // no_user_site + Value::Int(0), // no_site + Value::Int(0), // ignore_environment + Value::Int(0), // verbose + Value::Int(0), // bytes_warning + Value::Int(0), // quiet + Value::Int(0), // hash_randomization + Value::Int(0), // isolated + Value::Bool(false), // dev_mode + Value::Int(0), // utf8_mode + Value::Int(0), // warn_default_encoding + Value::Bool(false), // safe_path + int_max_str_digits(), + ], + ); + Value::Ref(vm.heap.allocate(HeapData::NamedTuple(Box::new(named_tuple)))) +} + +/// `sys.flags.int_max_str_digits`, widened from the limit the runtime enforces. +fn int_max_str_digits() -> Value { + i64::try_from(INT_MAX_STR_DIGITS).map_or(Value::Int(i64::MAX), Value::Int) +} + +/// Builds the `sys.builtin_module_names` tuple from [`BUILTIN_MODULE_NAMES`]. +fn builtin_module_names(vm: &VM<'_>) -> Value { + let names: SmallVec<_> = BUILTIN_MODULE_NAMES + .iter() + .map(|name| Value::InternString(vm.interns.intern_static(*name))) + .collect(); + allocate_tuple(names, vm.heap) +} + +/// Dispatches a `sys` module function call. +/// +/// Only present under the `test-hooks` feature — production builds register +/// no callables on the `sys` module, so this dispatcher would have nothing +/// to do. +#[cfg(feature = "test-hooks")] +pub(super) fn call(vm: &mut VM<'_>, function: SysFunctions, args: ArgValues) -> RunResult { + match function { + SysFunctions::Setrecursionlimit => setrecursionlimit(vm, args), + } +} + +/// `sys.setrecursionlimit(n)` — tightens the live recursion ceiling. +/// +/// Differs from CPython in one safety-critical way: the limit may only be +/// *lowered*, never raised. Sandboxed code raising the ceiling would let it +/// escape the host-configured depth bound that protects the Rust call stack +/// from overflow inside recursive type machinery (repr, eq, hash, json +/// dump, etc.). Attempts to raise raise `ValueError` with a message +/// pointing at the current cap. +#[cfg(feature = "test-hooks")] +fn setrecursionlimit(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let arg = args.get_one_arg("sys.setrecursionlimit", vm.heap)?; + let Value::Int(limit) = arg else { + arg.drop_with(vm); + return Err(ExcType::type_error("sys.setrecursionlimit() argument must be int")); + }; + let Ok(new_limit) = usize::try_from(limit) else { + return Err(ExcType::value_error("recursion limit must be greater or equal than 1")); + }; + if new_limit == 0 { + return Err(ExcType::value_error("recursion limit must be greater or equal than 1")); + } + match vm.heap.tracker.lower_recursion_limit(new_limit) { + Ok(()) => Ok(Value::None), + Err(current) => Err(ExcType::value_error(format!( + "sys.setrecursionlimit: cannot raise above current limit {current} (sandbox only allows lowering)" + ))), + } +} diff --git a/crates/bashkit-monty/src/modules/time.rs b/crates/bashkit-monty/src/modules/time.rs new file mode 100644 index 000000000..89e79d737 --- /dev/null +++ b/crates/bashkit-monty/src/modules/time.rs @@ -0,0 +1,898 @@ +//! Implementation of the `time` module. +//! +//! The clocks (`time`, `monotonic`, `perf_counter` and their `_ns` forms) all +//! read the session's `OsPolicy` clock, so a `call_host` host sees one +//! `time.time` call distinguished by its [`TimeCaller`]. `process_time` and +//! `thread_time` follow the separate `process_time` policy, since they exclude +//! sleeps. The conversion functions and the zone constants read the session zone. +//! See `limitations/time.md` for CPython divergences. + +use std::{borrow::Cow, time::Duration}; + +use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, TimeDelta, Timelike, format::StrftimeItems}; +use monty_types::{ + MontyTimeZone, OsFunctionCall, ProcessTime, ResourceTracker, SandboxTimeZone, SleepError, SleepMode, TimeCaller, + local_wall_clock, sleep_duration, unix_seconds, +}; +use num_traits::ToPrimitive; +use smallvec::smallvec; + +use crate::{ + args::{ArgValues, FromArgs}, + bytecode::{CallResult, VM}, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{DropWithContext, HeapData, HeapId, HeapReadOutput}, + intern::StaticStrings, + modules::ModuleFunctions, + os_dispatch::PostConversionEffect, + string_builder::StringBuilder, + types::{ + Module, NamedTuple, PyTrait, date, datetime as datetime_type, + datetime::{sandbox_instant, sandbox_local_wall_clock}, + str::allocate_string, + timezone::tzname_string, + tuple::allocate_tuple, + }, + value::{EitherStr, Value}, +}; + +/// `time` module functions, each a Python-visible callable. +/// +/// Serialised by declaration index through `ModuleFunctions`, so new variants +/// must be appended. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum TimeFunctions { + Time, + Sleep, + TimeNs, + Monotonic, + MonotonicNs, + PerfCounter, + PerfCounterNs, + ProcessTime, + ProcessTimeNs, + ThreadTime, + ThreadTimeNs, + Gmtime, + Localtime, + Mktime, + Asctime, + Ctime, + Strftime, + Strptime, +} + +/// Every function the module exposes, paired with the name it binds to. +const FUNCTIONS: [(StaticStrings, TimeFunctions); 18] = [ + (StaticStrings::Time, TimeFunctions::Time), + (StaticStrings::Sleep, TimeFunctions::Sleep), + (StaticStrings::TimeNs, TimeFunctions::TimeNs), + (StaticStrings::Monotonic, TimeFunctions::Monotonic), + (StaticStrings::MonotonicNs, TimeFunctions::MonotonicNs), + (StaticStrings::PerfCounter, TimeFunctions::PerfCounter), + (StaticStrings::PerfCounterNs, TimeFunctions::PerfCounterNs), + (StaticStrings::ProcessTime, TimeFunctions::ProcessTime), + (StaticStrings::ProcessTimeNs, TimeFunctions::ProcessTimeNs), + (StaticStrings::ThreadTime, TimeFunctions::ThreadTime), + (StaticStrings::ThreadTimeNs, TimeFunctions::ThreadTimeNs), + (StaticStrings::Gmtime, TimeFunctions::Gmtime), + (StaticStrings::Localtime, TimeFunctions::Localtime), + (StaticStrings::Mktime, TimeFunctions::Mktime), + (StaticStrings::Asctime, TimeFunctions::Asctime), + (StaticStrings::Ctime, TimeFunctions::Ctime), + (StaticStrings::Strftime, TimeFunctions::Strftime), + (StaticStrings::Strptime, TimeFunctions::Strptime), +]; + +/// Creates the `time` module and allocates it on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Time, vm.interns); + for (name, function) in FUNCTIONS { + module.set_attr(name, Value::ModuleFunction(ModuleFunctions::Time(function)), vm); + } + set_zone_constants(&mut module, vm); + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Sets `timezone`, `altzone`, `daylight` and `tzname` from the sandbox zone, +/// the values CPython reads from libc for 1 January and 1 July of the current +/// year. A named zone needs that year from the session clock, so the four are +/// unset when the clock is `CallHost`: module creation cannot suspend. +fn set_zone_constants(module: &mut Module, vm: &mut VM<'_>) { + let year = vm.env.os_policy.datetime.read().map(|utc| utc.year()); + let Some(constants) = vm.env.os_policy.timezone.constants(year) else { + return; + }; + // `time.timezone` is seconds *west* of UTC, the opposite sign to `utcoffset()`. + let west = |zone: &MontyTimeZone| Value::Int(-i64::from(zone.offset_seconds)); + let name = |zone: &MontyTimeZone, vm: &VM<'_>| { + allocate_string(tzname_string(zone.offset_seconds, zone.name.as_deref()), vm.heap) + }; + module.set_attr(StaticStrings::Timezone, west(&constants.standard), vm); + module.set_attr(StaticStrings::Altzone, west(&constants.daylight_zone), vm); + module.set_attr(StaticStrings::Daylight, Value::Int(i64::from(constants.daylight)), vm); + let tzname = allocate_tuple( + smallvec![name(&constants.standard, vm), name(&constants.daylight_zone, vm)], + vm.heap, + ); + module.set_attr(StaticStrings::Tzname, tzname, vm); +} + +/// Dispatches a call to a `time` module function. +pub(super) fn call(vm: &mut VM<'_>, function: TimeFunctions, args: ArgValues) -> RunResult { + match function { + TimeFunctions::Time => clock(vm, args, TimeCaller::Time, None), + TimeFunctions::Sleep => sleep(vm, args), + TimeFunctions::TimeNs => clock(vm, args, TimeCaller::TimeNs, Some(ClockReading::Nanoseconds)), + TimeFunctions::Monotonic => clock(vm, args, TimeCaller::Monotonic, None), + TimeFunctions::MonotonicNs => clock(vm, args, TimeCaller::MonotonicNs, Some(ClockReading::Nanoseconds)), + TimeFunctions::PerfCounter => clock(vm, args, TimeCaller::PerfCounter, None), + TimeFunctions::PerfCounterNs => clock(vm, args, TimeCaller::PerfCounterNs, Some(ClockReading::Nanoseconds)), + TimeFunctions::ProcessTime | TimeFunctions::ThreadTime => process_time(vm, args, function, false), + TimeFunctions::ProcessTimeNs | TimeFunctions::ThreadTimeNs => process_time(vm, args, function, true), + TimeFunctions::Gmtime => convert_clock(vm, args, TimeCaller::Gmtime, ClockReading::Gmtime), + TimeFunctions::Localtime => convert_clock(vm, args, TimeCaller::Localtime, ClockReading::Localtime), + TimeFunctions::Mktime => mktime(vm, args), + TimeFunctions::Asctime => asctime(vm, args), + TimeFunctions::Ctime => convert_clock(vm, args, TimeCaller::Ctime, ClockReading::Ctime), + TimeFunctions::Strftime => strftime(vm, args), + TimeFunctions::Strptime => strptime(vm, args), + } +} + +/// A clock function: returns its reading, or suspends so the host answers it. +/// `reading` is `None` for the plain-seconds clocks (`time`, `monotonic`, +/// `perf_counter`), which need no work on resume. All share the `time.time` OS +/// call; `caller` tells the host which one asked. +fn clock(vm: &mut VM<'_>, args: ArgValues, caller: TimeCaller, reading: Option) -> RunResult { + args.check_zero_args(caller.as_str(), vm.heap)?; + let Some(utc) = sandbox_instant(vm)? else { + return Ok(suspend_for_clock(caller, reading)); + }; + match reading { + None => Ok(CallResult::Value(Value::Float(unix_seconds(utc)))), + Some(reading) => reading.apply(utc, vm).map(CallResult::Value), + } +} + +/// `gmtime`/`localtime`/`ctime`, which take an optional `secs` and fall back to +/// the session clock — the one path where a conversion function can suspend. +fn convert_clock(vm: &mut VM<'_>, args: ArgValues, caller: TimeCaller, reading: ClockReading) -> RunResult { + // One struct per function because `FromArgs` bakes the name into the + // binding errors, and CPython reports each function's own. + let seconds = match caller { + TimeCaller::Gmtime => GmtimeArgs::from_args(args, vm)?.seconds, + TimeCaller::Localtime => LocaltimeArgs::from_args(args, vm)?.seconds, + _ => CtimeArgs::from_args(args, vm)?.seconds, + }; + let instant = optional_instant(&seconds, vm); + seconds.drop_with(vm.heap); + match instant? { + Some(utc) => reading.apply(utc, vm).map(CallResult::Value), + None => Ok(suspend_for_clock(caller, Some(reading))), + } +} + +/// `time.gmtime(secs=None)`; `PyArg_ParseTuple` in CPython, hence `parse_tuple`. +/// [`LocaltimeArgs`] and [`CtimeArgs`] are the same shape under their own names. +#[derive(FromArgs)] +#[from_args(name = "gmtime", style = parse_tuple)] +struct GmtimeArgs { + #[from_args(pos_only, default = Value::None)] + seconds: Value, +} + +/// `time.localtime(secs=None)`; see [`GmtimeArgs`]. +#[derive(FromArgs)] +#[from_args(name = "localtime", style = parse_tuple)] +struct LocaltimeArgs { + #[from_args(pos_only, default = Value::None)] + seconds: Value, +} + +/// `time.ctime(secs=None)`; see [`GmtimeArgs`]. +#[derive(FromArgs)] +#[from_args(name = "ctime", style = parse_tuple)] +struct CtimeArgs { + #[from_args(pos_only, default = Value::None)] + seconds: Value, +} + +/// Suspends with the shared `time.time` call, carrying the work still to do on +/// the host's answer. +fn suspend_for_clock(caller: TimeCaller, reading: Option) -> CallResult { + let call = OsFunctionCall::Time(caller); + match reading { + None => CallResult::OsCall(call), + Some(reading) => CallResult::OsCallWithEffect { + call, + effect: PostConversionEffect::ClockReading { reading }.into(), + }, + } +} + +/// What a `time` function makes of the instant once the clock has been read. +/// +/// Applied inline when the sandbox owns the clock and by [`apply_clock_reading`] +/// when the host answered `time.time`, so the two paths cannot drift. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) enum ClockReading { + /// Nanoseconds since the epoch, for the `_ns` clocks. + Nanoseconds, + /// `time.gmtime()`: a UTC `struct_time`. + Gmtime, + /// `time.localtime()`: a `struct_time` in the session zone. + Localtime, + /// `time.ctime()`: `asctime(localtime(secs))`. + Ctime, + /// `time.strftime(format)`: the format applied to the local `struct_time`. + Strftime(Box), +} + +impl ClockReading { + /// Turns the instant into the value the `time` function returns. + fn apply(self, utc: NaiveDateTime, vm: &mut VM<'_>) -> RunResult { + match self { + Self::Nanoseconds => epoch_nanoseconds(utc).map(Value::Int), + Self::Gmtime => Ok(gmtime_value(utc, vm)), + Self::Localtime => localtime_value(utc, vm), + Self::Ctime => { + let fields = local_fields(utc, vm)?; + Ok(allocate_string(fields.asctime(), vm.heap)) + } + Self::Strftime(format) => { + let fields = local_fields(utc, vm)?; + let text = fields.strftime(&format, vm)?; + Ok(allocate_string(text, vm.heap)) + } + } + } +} + +/// Resume half of [`suspend_for_clock`]: turns the host's `time.time` answer +/// (epoch seconds) into the value the suspended function returns. +pub(crate) fn apply_clock_reading(reading: ClockReading, reply: Value, vm: &mut VM<'_>) -> RunResult { + let seconds = match reply { + Value::Float(seconds) => Ok(seconds), + Value::Int(seconds) => Ok(seconds as f64), + other => { + let type_name = other.py_type_name(vm); + other.drop_with(vm); + Err(ExcType::type_error(format!( + "'time.time' must be answered with a float, not {type_name}" + ))) + } + }?; + reading.apply(instant_from_seconds(seconds)?, vm) +} + +/// `time.process_time()` / `thread_time()` and their `_ns` forms. +/// +/// These exclude sleeps, so they read the session's `process_time` policy rather +/// than its clock, and never suspend. Monty has no threads, so the thread clock +/// is the process clock. +fn process_time(vm: &mut VM<'_>, args: ArgValues, function: TimeFunctions, nanoseconds: bool) -> RunResult { + args.check_zero_args(&format!("time.{function}"), vm.heap)?; + let elapsed = match vm.env.os_policy.process_time { + ProcessTime::Zero => Duration::ZERO, + ProcessTime::Elapsed => vm.heap.tracker.elapsed(), + }; + Ok(CallResult::Value(if nanoseconds { + // Saturates rather than overflowing: a session cannot run for 292 years, + // and a wrapped negative reading would break the clock's monotonicity. + Value::Int(i64::try_from(elapsed.as_nanos()).unwrap_or(i64::MAX)) + } else { + Value::Float(elapsed.as_secs_f64()) + })) +} + +/// Validates the delay in every mode, then applies [`host_sleep`]. +/// [`PostConversionEffect::DiscardResult`] makes the call return `None` +/// regardless of the host's answer; `Zero` skips the wait. +fn sleep(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + // METH_O in CPython: keywords are refused wholesale, before arity. + let seconds = args + .reject_kwargs("time.sleep", vm.heap)? + .get_one_arg("time.sleep", vm.heap)?; + let result = sleep_seconds(&seconds, vm).and_then(|secs| { + sleep_duration(secs).map_err(|err| match err { + SleepError::NotANumber => ExcType::value_error("Invalid value NaN (not a number)"), + SleepError::Negative => ExcType::value_error("sleep length must be non-negative"), + SleepError::TooLarge => ExcType::sleep_too_long(), + }) + }); + seconds.drop_with(vm.heap); + let duration = result?; + let call = match host_sleep(vm, duration) { + Some(HostSleep::System(delay)) => OsFunctionCall::SystemSleep(delay), + Some(HostSleep::CallHost(delay)) => OsFunctionCall::Sleep(delay), + None => return Ok(CallResult::Value(Value::None)), + }; + Ok(CallResult::OsCallWithEffect { + call, + effect: PostConversionEffect::DiscardResult.into(), + }) +} + +/// Sleep destination and delay after applying the session policy. +pub(crate) enum HostSleep { + /// The host itself, for a delay already cut to the mode's maximum. + System(Duration), + /// The host's `os` handler, with the requested delay uncapped. + CallHost(Duration), +} + +/// Applies the sleep policy, returning `None` for `SleepMode::Zero`. +/// The call kind tells the host who waits without needing the session policy. +pub(crate) fn host_sleep(vm: &VM<'_>, delay: Duration) -> Option { + match vm.env.os_policy.sleep { + SleepMode::System(max) => Some(HostSleep::System(delay.min(max))), + SleepMode::CallHost => Some(HostSleep::CallHost(delay)), + SleepMode::Zero => None, + } +} + +/// The float seconds an already-`__index__`ed value denotes; an integer too +/// large for `f64` becomes infinity for the caller's range check to reject. +fn index_seconds(index: &Value, vm: &VM<'_>) -> f64 { + match index { + Value::Int(n) => *n as f64, + Value::Bool(b) => f64::from(*b), + other => other + .as_long_int(vm) + .map_or(0.0, |n| n.to_f64().unwrap_or(f64::INFINITY)), + } +} + +/// Converts a sleep length to float seconds the way CPython's +/// `_PyTime_FromSecondsObject` does: a float passes straight through, and +/// anything else goes through `__index__`, so a `str` — or a class with only +/// `__float__` — is rejected as non-integral rather than as a non-number. +/// +/// An integer too large for `f64` becomes infinity, which the caller's range +/// check turns into the same `OverflowError` CPython raises for it. +fn sleep_seconds(value: &Value, vm: &mut VM<'_>) -> RunResult { + match value { + Value::Float(f) => Ok(*f), + _ => match value.py_index_impl(vm)? { + Some(index) => { + let seconds = index_seconds(&index, vm); + index.drop_with(vm); + Ok(seconds) + } + None => Err(ExcType::type_error_not_integer_or_float(&value.py_type_name(vm))), + }, + } +} + +/// `time.mktime(t)`: the inverse of `localtime`, reading `t` as wall time in the +/// session zone. `METH_O` in CPython, hence the module-qualified arity message. +fn mktime(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args + .reject_kwargs("time.mktime", vm.heap)? + .get_one_arg("time.mktime", vm.heap)?; + // Only the wall clock matters, and CPython does not range-check the + // weekday or year day here as `asctime`/`strftime` do. + let wall = time_tuple_parts(&value, "mktime", vm).and_then(|(items, _)| naive_from_time_tuple(&items)); + value.drop_with(vm.heap); + let utc = vm + .env + .os_policy + .timezone + .utc_from_local(wall?) + .ok_or_else(ExcType::mktime_out_of_range)?; + Ok(CallResult::Value(Value::Float(unix_seconds(utc).floor()))) +} + +/// `time.asctime(t=None)`: the fixed 24-character form, from `t` or the clock. +/// `PyArg_UnpackTuple` in CPython, unlike its `gmtime` neighbours. +fn asctime(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let Some(value) = args + .reject_kwargs("asctime", vm.heap)? + .get_zero_one_arg("asctime", vm.heap)? + else { + return suspend_or_apply(vm, TimeCaller::Asctime, ClockReading::Ctime); + }; + let fields = time_fields(&value, "asctime", vm); + value.drop_with(vm.heap); + Ok(CallResult::Value(allocate_string(fields?.asctime(), vm.heap))) +} + +/// `time.strftime(format, t=None)`, formatting `t` or the clock. +fn strftime(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let StrftimeArgs { format, t } = StrftimeArgs::from_args(args, vm)?; + let result = strftime_result(&format, &t, vm); + (format, t).drop_with(vm.heap); + result +} + +/// `time.strftime(format, t=None)`; `PyArg_ParseTuple` in CPython. +#[derive(FromArgs)] +#[from_args(name = "strftime", style = parse_tuple)] +struct StrftimeArgs { + #[from_args(pos_only)] + format: Value, + #[from_args(pos_only, default = Value::None)] + t: Value, +} + +/// [`strftime`] without the argument cleanup, so every exit releases both. +fn strftime_result(format: &Value, t: &Value, vm: &mut VM<'_>) -> RunResult { + let format = string_arg(format, "strftime", 1, vm)?; + if matches!(t, Value::None) { + suspend_or_apply(vm, TimeCaller::Strftime, ClockReading::Strftime(format.into())) + } else { + let text = time_fields(t, "strftime", vm)?.strftime(&format, vm)?; + Ok(CallResult::Value(allocate_string(text, vm.heap))) + } +} + +/// `time.strptime(string, format='%a %b %d %H:%M:%S %Y')`. +/// +/// CPython's is the pure-Python `_strptime_time`, which is why the binding +/// errors name that function rather than `strptime`. +fn strptime(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let StrptimeArgs { data_string, format } = StrptimeArgs::from_args(args, vm)?; + let result = strptime_result(&data_string, &format, vm); + (data_string, format).drop_with(vm.heap); + result.map(CallResult::Value) +} + +/// `time.strptime(data_string, format)` — the pure-Python `_strptime_time`. +#[derive(FromArgs)] +#[from_args(name = "_strptime_time", style = def)] +struct StrptimeArgs { + data_string: Value, + #[from_args(default = Value::None)] + format: Value, +} + +/// [`strptime`] without the argument cleanup. +fn strptime_result(data_string: &Value, format: &Value, vm: &mut VM<'_>) -> RunResult { + let text = string_arg(data_string, "strptime", 1, vm)?; + let format = match format { + Value::None => DEFAULT_STRPTIME_FORMAT.to_owned(), + other => string_arg(other, "strptime", 2, vm)?, + }; + let wall = datetime_type::parse_time_strptime(&text, &format)?; + // A `%z` offset is parsed but dropped, so the zone half stays unset; CPython + // records it in `tm_gmtoff` (see `limitations/time.md`). + Ok(struct_time_value(&TimeFields::naive(wall), vm)) +} + +/// `time.strptime`'s format when the caller gives none: `asctime`'s form. +const DEFAULT_STRPTIME_FORMAT: &str = "%a %b %d %H:%M:%S %Y"; + +/// Reads the clock for a conversion that had no explicit time, suspending to the +/// host when it owns the clock. +fn suspend_or_apply(vm: &mut VM<'_>, caller: TimeCaller, reading: ClockReading) -> RunResult { + match sandbox_instant(vm)? { + Some(utc) => reading.apply(utc, vm).map(CallResult::Value), + None => Ok(suspend_for_clock(caller, Some(reading))), + } +} + +/// The `str` at position `position` of a `time` function's arguments, +/// with `_PyArg_BadArgument`'s positional wording. +fn string_arg(value: &Value, name: &str, position: usize, vm: &VM<'_>) -> RunResult { + match value.to_str(vm) { + Ok(text) => Ok(text.to_owned()), + Err(_) => Err(ExcType::type_error(format!( + "{name}() argument {position} must be str, not {}", + value.py_type_name(vm) + ))), + } +} + +/// A broken-down time, the payload every `struct_time` carries. +/// +/// `weekday` and `yearday` are stored rather than derived because CPython +/// formats them as given: `strftime('%a', (…, tm_wday=0, …))` prints `Mon` +/// even when the date is a Saturday. +struct TimeFields { + wall: NaiveDateTime, + weekday: i64, + yearday: i64, + /// -1 when unknown (`strptime`), else 0 or 1. + isdst: i64, + /// The zone the wall clock is expressed in; `None` leaves `tm_gmtoff` and + /// `tm_zone` unset, as CPython does for a zone-less `strptime`. + zone: Option, +} + +impl TimeFields { + /// Fields for a wall clock in `zone`, deriving the weekday and year day. + fn zoned(wall: NaiveDateTime, zone: MontyTimeZone, isdst: i64) -> Self { + Self { + wall, + weekday: i64::from(wall.weekday().num_days_from_monday()), + yearday: i64::from(wall.ordinal()), + isdst, + zone: Some(zone), + } + } + + /// `tm_wday` folded into `0..7`, Monday first, as an index into the day + /// names. The tuple can carry any integer here; CPython folds it the same way. + fn weekday_index(&self) -> usize { + usize::try_from(self.weekday.rem_euclid(7)).unwrap_or_default() + } + + /// Fields with no zone, for `strptime` and a bare 9-element tuple. + fn naive(wall: NaiveDateTime) -> Self { + Self { + wall, + weekday: i64::from(wall.weekday().num_days_from_monday()), + yearday: i64::from(wall.ordinal()), + isdst: -1, + zone: None, + } + } + + /// CPython's fixed 24-character `asctime` form, built from the stored + /// weekday rather than the date's own. + fn asctime(&self) -> String { + const DAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; + const MONTHS: [&str; 12] = [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", + ]; + let day = DAYS[self.weekday_index()]; + let month = MONTHS[(self.wall.month0() as usize).min(11)]; + format!( + "{day} {month} {:2} {:02}:{:02}:{:02} {}", + self.wall.day(), + self.wall.hour(), + self.wall.minute(), + self.wall.second(), + self.wall.year() + ) + } + + /// Applies a `strftime` format, with the zone directives from the stored zone + /// (as `datetime.strftime` does) and the day directives from the stored fields. + /// `%f` renders zeros via the shared rewrite; CPython's `time.strftime` has no + /// microsecond field at all (see `limitations/time.md`). + fn strftime(&self, format: &str, vm: &mut VM<'_>) -> RunResult { + let (offset, name) = match &self.zone { + Some(zone) => (Some(zone.offset_seconds), zone.name.clone()), + None => (None, None), + }; + let format = self.rewrite_day_directives(format, &vm.heap.tracker)?; + let format = date::rewrite_zone_directives(&format, offset, name.as_deref(), &vm.heap.tracker)?; + let format = date::rewrite_microsecond_directive(&format); + let rendered = self.wall.format_with_items(StrftimeItems::new_lenient(&format)); + date::render_strftime(rendered).ok_or_else(date::invalid_strftime_error) + } + + /// Substitutes the directives CPython reads from `tm_wday`/`tm_yday`, which + /// chrono would recompute from the date. Shifting the date instead is not an + /// option: `%d`, `%m` and `%Y` must still come from the date itself. + fn rewrite_day_directives<'f>(&self, format: &'f str, tracker: &ResourceTracker) -> RunResult> { + const DAYS: [(&str, &str); 7] = [ + ("Mon", "Monday"), + ("Tue", "Tuesday"), + ("Wed", "Wednesday"), + ("Thu", "Thursday"), + ("Fri", "Friday"), + ("Sat", "Saturday"), + ("Sun", "Sunday"), + ]; + let may_have_day = format + .as_bytes() + .windows(2) + .any(|pair| pair[0] == b'%' && matches!(pair[1], b'a' | b'A' | b'j' | b'w' | b'u' | b'U' | b'W')); + if !may_have_day { + return Ok(Cow::Borrowed(format)); + } + // C counts weekdays from Sunday and year days from zero, which is what + // the `%w`, `%U` and `%W` formulas below are written against. + let monday_based = self.weekday_index(); + let (short, long) = DAYS[monday_based]; + let sunday_based = (monday_based + 1) % 7; + let c_yearday = self.yearday - 1; + let sunday_based = i64::try_from(sunday_based).unwrap_or_default(); + let week = |first_weekday: i64| (c_yearday + 7 - (sunday_based + 7 - first_weekday) % 7) / 7; + let mut out = StringBuilder::with_capacity(format.len(), tracker)?; + let mut rest = format; + while let Some(percent) = rest.find('%') { + let (before, from_percent) = rest.split_at(percent); + out.push_str(before)?; + let directive = from_percent[1..].chars().next(); + let substitute = match directive { + Some('a') => Some(short.to_owned()), + Some('A') => Some(long.to_owned()), + Some('j') => Some(format!("{:03}", self.yearday)), + Some('w') => Some(sunday_based.to_string()), + Some('u') => Some((monday_based + 1).to_string()), + Some('U') => Some(format!("{:02}", week(0))), + Some('W') => Some(format!("{:02}", week(1))), + _ => None, + }; + let consumed = match (substitute, directive) { + (Some(text), Some(c)) => { + out.push_str(&text)?; + 1 + c.len_utf8() + } + // Copy the directive whole, so `%%a` consumes `%%` and leaves `a` as text. + (None, Some(c)) => { + out.push('%')?; + out.push(c)?; + 1 + c.len_utf8() + } + (_, None) => { + out.push('%')?; + 1 + } + }; + rest = &from_percent[consumed..]; + } + out.push_str(rest)?; + out.finish_raw().map(Cow::Owned) + } +} + +/// `time.gmtime(secs)`: the instant broken down in UTC. +fn gmtime_value(utc: NaiveDateTime, vm: &mut VM<'_>) -> Value { + let zone = MontyTimeZone { + offset_seconds: 0, + name: Some("UTC".to_owned()), + }; + struct_time_value(&TimeFields::zoned(utc, zone, 0), vm) +} + +/// `time.localtime(secs)`: the instant broken down in the session zone. +fn localtime_value(utc: NaiveDateTime, vm: &mut VM<'_>) -> RunResult { + let fields = local_fields(utc, vm)?; + Ok(struct_time_value(&fields, vm)) +} + +/// The session zone's reading of `utc`, with `tm_isdst` set from whether the +/// zone is on its daylight half at that instant. +fn local_fields(utc: NaiveDateTime, vm: &VM<'_>) -> RunResult { + let zone = vm.env.os_policy.timezone.at(utc); + let isdst = i64::from(is_daylight(&vm.env.os_policy.timezone, utc, &zone)); + let wall = sandbox_local_wall_clock(vm, utc)?; + Ok(TimeFields::zoned(wall, zone, isdst)) +} + +/// Whether `zone` is the daylight half of the session zone at `utc`, which is +/// `tm_isdst`. A fixed zone has one half, so it is never daylight. +fn is_daylight(sandbox_zone: &SandboxTimeZone, utc: NaiveDateTime, at: &MontyTimeZone) -> bool { + sandbox_zone + .constants(Some(utc.year())) + .is_some_and(|constants| constants.daylight && at.offset_seconds == constants.daylight_zone.offset_seconds) +} + +/// Builds a `time.struct_time`. +/// +/// A structseq in CPython: no class object, so `_fields`/`_replace` are absent +/// here too. Unlike CPython's, the two zone fields are part of the tuple, so +/// `len()` is 11 (see `limitations/time.md`). +fn struct_time_value(fields: &TimeFields, vm: &mut VM<'_>) -> Value { + const NAMES: [StaticStrings; 11] = [ + StaticStrings::TmYear, + StaticStrings::TmMon, + StaticStrings::TmMday, + StaticStrings::TmHour, + StaticStrings::TmMin, + StaticStrings::TmSec, + StaticStrings::TmWday, + StaticStrings::TmYday, + StaticStrings::TmIsdst, + StaticStrings::TmGmtoff, + StaticStrings::TmZone, + ]; + let wall = fields.wall; + let (gmtoff, zone_name) = match &fields.zone { + Some(zone) => ( + Value::Int(i64::from(zone.offset_seconds)), + allocate_string(tzname_string(zone.offset_seconds, zone.name.as_deref()), vm.heap), + ), + None => (Value::None, Value::None), + }; + let named_tuple = NamedTuple::new( + EitherStr::Interned(vm.interns.intern_static(StaticStrings::StructTime)), + NAMES + .into_iter() + .map(|name| EitherStr::Interned(vm.interns.intern_static(name))) + .collect(), + vec![ + Value::Int(i64::from(wall.year())), + Value::Int(i64::from(wall.month())), + Value::Int(i64::from(wall.day())), + Value::Int(i64::from(wall.hour())), + Value::Int(i64::from(wall.minute())), + Value::Int(i64::from(wall.second())), + Value::Int(fields.weekday), + Value::Int(fields.yearday), + Value::Int(fields.isdst), + gmtoff, + zone_name, + ], + ); + Value::Ref(vm.heap.allocate(HeapData::NamedTuple(Box::new(named_tuple)))) +} + +/// Reads the `struct_time` (or bare 9-element tuple) that `mktime`, `asctime` +/// and `strftime` accept. +/// +/// CPython requires exactly 9 items; Monty's own `struct_time` carries 11, so +/// both lengths are taken. A bare tuple has no zone of its own, so `tm_isdst` +/// selects the session zone's standard or daylight half, as CPython does. +fn time_fields(value: &Value, name: &str, vm: &mut VM<'_>) -> RunResult { + let (items, own_zone) = time_tuple_parts(value, name, vm)?; + let wall = naive_from_time_tuple(&items)?; + // CPython's `checktm`, which `mktime` skips: a weekday below -1 goes + // negative after its Sunday-first shift, and a year day is 0..=366 with 0 + // read as the first day. Bounding both here also keeps the `%U`/`%W` + // arithmetic in range, so a hostile tuple cannot overflow it. + if items[6] < -1 { + return Err(ExcType::value_error("day of week out of range")); + } + if !(0..=366).contains(&items[7]) { + return Err(ExcType::value_error("day of year out of range")); + } + let isdst = items[8].clamp(-1, 1); + let zone = own_zone.or_else(|| tuple_zone(wall.year(), isdst, vm)); + Ok(TimeFields { + wall, + weekday: items[6], + yearday: items[7].max(1), + isdst, + zone, + }) +} + +/// The nine core integers of a time tuple, plus the zone an 11-field +/// `struct_time` carries. Rejects anything else with CPython's wording. +fn time_tuple_parts(value: &Value, name: &str, vm: &VM<'_>) -> RunResult<([i64; 9], Option)> { + let read = value.read_heap(vm); + let items = match &read { + Some(HeapReadOutput::Tuple(tuple)) => tuple.get(vm.heap).as_slice(), + Some(HeapReadOutput::NamedTuple(tuple)) => tuple.get(vm.heap).items(), + _ => return Err(ExcType::type_error("Tuple or struct_time argument required".to_owned())), + }; + if !matches!(items.len(), 9 | 11) { + return Err(ExcType::illegal_time_tuple(name)); + } + let mut core = [0_i64; 9]; + for (slot, item) in core.iter_mut().zip(items) { + *slot = match item { + Value::Int(n) => *n, + Value::Bool(b) => i64::from(*b), + other => { + return Err(ExcType::type_error(format!( + "'{}' object cannot be interpreted as an integer", + other.py_type_name(vm) + ))); + } + }; + } + // Only Monty's own `struct_time` has the two zone fields; a zone-less one + // (from `strptime`) leaves them `None` and falls back to the session zone. + let zone = match items.get(9..11) { + Some([Value::Int(offset_seconds), name]) => { + i32::try_from(*offset_seconds).ok().map(|offset_seconds| MontyTimeZone { + offset_seconds, + name: name.to_str(vm).ok().map(str::to_owned), + }) + } + _ => None, + }; + Ok((core, zone)) +} + +/// The wall clock a time tuple's first six fields denote, with CPython's +/// per-field `ValueError` for one out of range. +fn naive_from_time_tuple(items: &[i64; 9]) -> RunResult { + const RANGES: [(&str, i64, i64); 5] = [ + ("month", 1, 12), + ("day of month", 1, 31), + ("hour", 0, 23), + ("minute", 0, 59), + ("seconds", 0, 61), + ]; + let mut checked = [0_u32; 5]; + for ((field, low, high), (slot, value)) in RANGES.into_iter().zip(checked.iter_mut().zip(&items[1..6])) { + *slot = u32::try_from(*value) + .ok() + .filter(|_| (low..=high).contains(value)) + .ok_or_else(|| ExcType::value_error(format!("{field} out of range")))?; + } + let [month, day, hour, minute, second] = checked; + let year = i32::try_from(items[0]).map_err(|_| ExcType::value_error("year out of range"))?; + // CPython accepts leap seconds here and folds them into the next minute. + let (second, extra) = if second > 59 { + (59, i64::from(second) - 59) + } else { + (second, 0) + }; + NaiveDate::from_ymd_opt(year, month, day) + .and_then(|date| date.and_hms_opt(hour, minute, second)) + .and_then(|wall| wall.checked_add_signed(TimeDelta::seconds(extra))) + .ok_or_else(|| ExcType::value_error("day of month out of range")) +} + +/// The zone a bare 9-element tuple denotes: the session zone's standard half, +/// or its daylight half when `tm_isdst` is 1. +fn tuple_zone(year: i32, isdst: i64, vm: &VM<'_>) -> Option { + let constants = vm.env.os_policy.timezone.constants(Some(year))?; + Some(if isdst == 1 { + constants.daylight_zone + } else { + constants.standard + }) +} + +/// The instant an optional `secs` argument denotes; `None` means the caller +/// passed nothing and the clock must be read instead. +fn optional_instant(seconds: &Value, vm: &mut VM<'_>) -> RunResult> { + match seconds { + Value::None => sandbox_instant(vm), + value => { + let seconds = clock_seconds(value, vm)?; + instant_from_seconds(seconds).map(Some) + } + } +} + +/// The `secs` argument of `gmtime`/`localtime`/`ctime` as float seconds. +/// +/// Like [`sleep_seconds`] a float passes through and anything else goes through +/// `__index__`, but CPython's `_PyTime_ObjectToTime_t` reports a rejection as a +/// plain non-integer rather than naming floats as acceptable. +fn clock_seconds(value: &Value, vm: &mut VM<'_>) -> RunResult { + match value { + Value::Float(f) => Ok(*f), + _ => match value.py_index_impl(vm)? { + Some(index) => { + let seconds = index_seconds(&index, vm); + index.drop_with(vm); + Ok(seconds) + } + None => Err(ExcType::type_error(format!( + "'{}' object cannot be interpreted as an integer", + value.py_type_name(vm) + ))), + }, + } +} + +/// Epoch seconds as an instant. The whole seconds floor, as CPython's +/// `_PyTime_ObjectToTime_t` does for `gmtime(-1.9)`, and the fraction is kept +/// so the `_ns` clocks see it; the broken-down fields never read it. +fn instant_from_seconds(seconds: f64) -> RunResult { + let floored = seconds.floor(); + if floored.is_nan() { + return Err(ExcType::value_error("Invalid value NaN (not a number)")); + } + // `as` saturates, which would silently clamp rather than raise. + if !(-9.3e18..=9.3e18).contains(&floored) { + return Err(ExcType::timestamp_out_of_range()); + } + #[expect( + clippy::cast_possible_truncation, + reason = "range-checked above, and already floored" + )] + let whole = floored as i64; + #[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "a fraction in 0..1, scaled" + )] + let nanos = (((seconds - floored) * 1e9).round() as u32).min(999_999_999); + DateTime::from_timestamp(whole, nanos) + .map(|utc| utc.naive_utc()) + .filter(|utc| local_wall_clock(*utc, 0).is_some()) + .ok_or_else(ExcType::timestamp_out_of_range) +} + +/// Nanoseconds since the epoch, for the `_ns` clocks. Chrono's range is about +/// 1677..2262, narrower than `datetime`'s, so a fixed clock outside it raises. +fn epoch_nanoseconds(utc: NaiveDateTime) -> RunResult { + utc.and_utc() + .timestamp_nanos_opt() + .ok_or_else(ExcType::timestamp_out_of_range) +} diff --git a/crates/bashkit-monty/src/modules/tomllib/mod.rs b/crates/bashkit-monty/src/modules/tomllib/mod.rs new file mode 100644 index 000000000..ba495c1be --- /dev/null +++ b/crates/bashkit-monty/src/modules/tomllib/mod.rs @@ -0,0 +1,221 @@ +//! Implementation of Python's `tomllib` module: `loads()`, `load()` and +//! `TOMLDecodeError`. +//! +//! Parsing is a port of CPython's pure-Python `tomllib/_parser.py`, kept +//! message-for-message compatible, split by stage: +//! - [`parser`] turns TOML text into a Rust [`parser::TomlTable`] tree +//! - [`value`] converts that tree into Monty values once parsing succeeded +//! +//! Building the tree first keeps the grammar and the table/namespace rules +//! (dotted keys, `[table]` redefinition, frozen inline containers) free of heap +//! borrows; the conversion then allocates each value exactly once. + +mod parser; +mod value; + +use std::borrow::Cow; + +use memchr::{memchr_iter, memrchr}; +use monty_types::ResourceTracker; +use parser::{TomlError, TomlTable}; + +use super::ModuleFunctions; +use crate::{ + args::{ArgValues, FromArgs}, + builtins::Builtins, + bytecode::{CallResult, VM}, + codecs::Codec, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{HeapData, HeapId, HeapReadOutput}, + intern::StaticStrings, + os_dispatch::PostConversionEffect, + types::Module, + value::Value, +}; + +/// Functions exposed by the `tomllib` module. +/// +/// The display form matches the Python-visible function name so reprs look +/// like normal builtins. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "lowercase")] +pub(crate) enum TomllibFunctions { + /// `tomllib.loads(s)` parses TOML text into a dict. + Loads, + /// `tomllib.load(fp)` parses a binary file object into a dict. + Load, +} + +/// Creates the `tomllib` module and allocates it on the heap. +/// +/// The module exposes everything CPython's does: `loads`, `load` and +/// `TOMLDecodeError`. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Tomllib, vm.interns); + module.set_attr( + StaticStrings::Loads, + Value::ModuleFunction(ModuleFunctions::Tomllib(TomllibFunctions::Loads)), + vm, + ); + module.set_attr( + StaticStrings::Load, + Value::ModuleFunction(ModuleFunctions::Tomllib(TomllibFunctions::Load)), + vm, + ); + module.set_attr( + StaticStrings::TomlDecodeError, + Value::Builtin(Builtins::ExcType(ExcType::TomlDecodeError)), + vm, + ); + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a `tomllib` module function call. +/// +/// `load()` may suspend for the host to read the file, so the dispatcher +/// returns a `CallResult`. +pub(super) fn call(vm: &mut VM<'_>, function: TomllibFunctions, args: ArgValues) -> RunResult { + match function { + TomllibFunctions::Loads => call_loads(vm, args).map(CallResult::Value), + TomllibFunctions::Load => call_load(vm, args), + } +} + +/// Argument shape for `tomllib.loads(s, /, *, parse_float=float)`. +/// +/// CPython's `loads` is a pure-Python `def`, so signature errors use +/// `style = def` wording. `parse_float` is not implemented: leaving it off the +/// struct makes the macro reject it as an unexpected keyword. +#[derive(FromArgs)] +#[from_args(name = "loads", style = def)] +struct TomlLoadsArgs { + #[from_args(pos_only)] + s: Value, +} + +/// Implements `tomllib.loads(s)`. +/// +/// Only `str` input is accepted; anything else raises CPython's +/// `Expected str object, not '{type}'` `TypeError`. +fn call_loads(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let TomlLoadsArgs { s } = TomlLoadsArgs::from_args(args, vm)?; + defer_drop!(s, vm); + let table = match s.to_str(vm) { + Ok(source) => parse_document(source, &vm.heap.tracker)?, + Err(_) => return Err(ExcType::toml_loads_type_error(&s.py_type_name(vm))), + }; + value::table_into_value(table, vm) +} + +/// Argument shape for `tomllib.load(fp, /, *, parse_float=float)`; see +/// [`TomlLoadsArgs`] for why `parse_float` is absent. +#[derive(FromArgs)] +#[from_args(name = "load", style = def)] +struct TomlLoadArgs { + #[from_args(pos_only)] + fp: Value, +} + +/// Implements `tomllib.load(fp)` for file objects returned by `open()`. +/// +/// CPython calls `fp.read()` and decodes the bytes. An unread file is loaded +/// with a [`PostConversionEffect::LoadThenCall`] that replays this call, which +/// then finds the buffer in place. Anything that is not a file object raises +/// the `AttributeError` CPython's `fp.read()` would. +fn call_load(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let TomlLoadArgs { fp } = TomlLoadArgs::from_args(args, vm)?; + defer_drop!(fp, vm); + let Value::Ref(file_id) = fp else { + return Err(ExcType::attribute_error(fp.py_type_name(vm), "read")); + }; + let HeapReadOutput::OpenFile(mut file) = vm.heap.read(*file_id) else { + return Err(ExcType::attribute_error(fp.py_type_name(vm), "read")); + }; + file.check_readable(vm)?; + if !file.is_binary(vm) { + return Err(ExcType::toml_load_text_mode_error()); + } + if file.needs_buffer_load(vm) { + let effect = PostConversionEffect::LoadThenCall { + file_id: *file_id, + callable: Value::ModuleFunction(ModuleFunctions::Tomllib(TomllibFunctions::Load)), + args: ArgValues::One(fp.clone_with_heap(vm.heap)), + }; + Ok(file.buffer_load_call(vm, effect)) + } else { + let content = file.read_all(vm)?; + parse_file_content(content, vm).map(CallResult::Value) + } +} + +/// Decodes the `bytes` a binary `read()` produced as UTF-8 (CPython's +/// `b.decode()`) and parses the text. +fn parse_file_content(content: Value, vm: &mut VM<'_>) -> RunResult { + defer_drop!(content, vm); + let bytes = match content { + Value::InternBytes(bytes_id) => vm.interns.get_bytes(*bytes_id), + Value::Ref(heap_id) if let HeapData::Bytes(bytes) = vm.heap.get(*heap_id) => bytes.as_slice(), + other => { + return Err(RunError::internal(format!( + "tomllib.load: binary read returned {}", + other.py_type_name(vm) + ))); + } + }; + let source = Codec::Utf8.decode(bytes, "strict")?; + let table = parse_document(&source, &vm.heap.tracker)?; + value::table_into_value(table, vm) +} + +/// Parses TOML text into its table tree, raising CPython's exception on failure. +/// +/// `\r\n` is normalised to `\n` first, as CPython does, so string values and +/// error positions are computed against the normalised document (which is also +/// the `doc` the exception reports). +fn parse_document(source: &str, tracker: &ResourceTracker) -> RunResult { + let src: Cow<'_, str> = if source.contains("\r\n") { + Cow::Owned(source.replace("\r\n", "\n")) + } else { + Cow::Borrowed(source) + }; + parser::parse(&src, tracker).map_err(|error| toml_error_to_run_error(error, &src)) +} + +/// Converts a parser failure into the Python exception CPython raises for it. +fn toml_error_to_run_error(error: TomlError, doc: &str) -> RunError { + match error { + TomlError::Decode { msg, pos } => { + let (index, line, column, at_end) = error_coordinates(doc, pos); + ExcType::toml_decode_error(&msg, doc, index, line, column, at_end) + } + TomlError::Recursion(msg) => SimpleException::new_msg(ExcType::RecursionError, msg).into(), + TomlError::Run(error) => *error, + } +} + +/// CPython's `(pos, lineno, colno)` for a byte offset into `doc`, plus whether +/// the offset is at or past the end: `pos` counts characters, `lineno` is +/// 1-based and `colno` is the character column, as `TOMLDecodeError.__init__` +/// derives them from `doc`. +/// +/// `byte_pos` may lie past the end of `doc` (an escape cut off by EOF), in +/// which case the overshoot is kept so `pos` matches CPython's. +fn error_coordinates(doc: &str, byte_pos: usize) -> (usize, usize, usize, bool) { + let bytes = doc.as_bytes(); + let clamped = byte_pos.min(bytes.len()); + let prefix = &bytes[..clamped]; + let pos = count_chars(prefix) + (byte_pos - clamped); + let lineno = memchr_iter(b'\n', prefix).count() + 1; + let colno = match memrchr(b'\n', prefix) { + Some(newline) => pos - count_chars(&bytes[..newline]), + None => pos + 1, + }; + (pos, lineno, colno, byte_pos >= bytes.len()) +} + +/// Number of characters in a UTF-8 prefix: every byte that is not a +/// continuation byte starts one. +fn count_chars(bytes: &[u8]) -> usize { + bytes.iter().filter(|&&byte| !matches!(byte, 0x80..=0xBF)).count() +} diff --git a/crates/bashkit-monty/src/modules/tomllib/parser.rs b/crates/bashkit-monty/src/modules/tomllib/parser.rs new file mode 100644 index 000000000..7b7d16f41 --- /dev/null +++ b/crates/bashkit-monty/src/modules/tomllib/parser.rs @@ -0,0 +1,1191 @@ +//! TOML parsing for `tomllib`: a port of CPython's `Lib/tomllib/_parser.py`. +//! +//! The parser walks the UTF-8 bytes of the `\r\n`-normalised source — every +//! structural TOML character is ASCII, so byte positions are always safe to +//! cut at — and builds a [`TomlTable`] tree without touching the heap. Each +//! function mirrors its CPython namesake so messages, the position they are +//! reported at and the order the checks run in stay identical. Positions in a +//! [`TomlError::Decode`] are byte offsets; `super` converts them to character +//! indexes when raising. +//! +//! The tree is allocator-visible but costs far more per element than the +//! source text (`1,` becomes a [`TomlValue`]), so the element loops poll the +//! resource tracker and every array, table and flags map preflights its +//! doubling, turning a huge document into a graceful `MemoryError`. + +use std::{borrow::Cow, collections::HashMap, mem, vec}; + +use chrono::NaiveDate; +use indexmap::{IndexMap, map}; +use monty_types::{ResourceError, ResourceTracker}; +use num_bigint::BigInt; + +use crate::{ + exception_private::RunError, + types::{long_int::check_decimal_digit_count, str::string_repr_fmt}, +}; + +/// CPython caps a dotted key at `sys.getrecursionlimit()` parts (1000 by +/// default) because the key names a recursive structure; Monty uses the +/// default as a fixed limit. +const MAX_KEY_PARTS: usize = 1000; + +/// Nesting depth of inline arrays and tables before `RecursionError`. +/// +/// CPython's recursive descent hits its own recursion limit at about 330 +/// nested inline tables or 500 nested arrays; the parser recurses per level +/// too, with frames large enough in debug builds that this depth is what a +/// 2 MiB thread stack comfortably holds. +const MAX_NESTING: usize = 100; + +/// `Flags::FROZEN`: an inline array or table, immutable from then on. +const FROZEN: u8 = 1; +/// `Flags::EXPLICIT_NEST`: a table created explicitly, which `[table]` syntax +/// may not open again. +const EXPLICIT_NEST: u8 = 2; + +/// Bytes per entry a full [`Flags`] map allocates when it grows: hashbrown +/// rehashes into twice the slots, each a `(String, FlagNode)` and a control byte. +const FLAG_ENTRY_GROWTH: usize = 2 * (mem::size_of::<(String, FlagNode)>() + 1); + +/// Bytes per entry a full [`TomlTable`] allocates when it grows: the +/// `(hash, key, value)` bucket plus two index slots, since the rehashed +/// index table (a `usize` and a control byte per slot) doubles too. +const TABLE_ENTRY_GROWTH: usize = mem::size_of::<(usize, String, TomlValue)>() + 2 * (mem::size_of::() + 1); + +/// A dotted key, one `String` per part. +pub(super) type Key = Vec; + +/// A parsed TOML value, converted to a Monty value by [`super::value`]. +pub(super) enum TomlValue { + Str(String), + Int(TomlInt), + Float(f64), + Bool(bool), + Date(TomlDate), + Time(TomlTime), + /// A local date-time (`offset_seconds` `None`) or an offset date-time. + DateTime { + date: TomlDate, + time: TomlTime, + offset_seconds: Option, + }, + Array(Vec), + Table(TomlTable), +} + +impl TomlValue { + /// Whether this value freezes its namespace: CPython's + /// `isinstance(value, (dict, list))`. + fn is_container(&self) -> bool { + matches!(self, Self::Array(_) | Self::Table(_)) + } +} + +/// A TOML integer: `i64` when it fits, else a big integer. +pub(super) enum TomlInt { + Small(i64), + Big(BigInt), +} + +/// A calendar date already validated against `datetime.date`'s ranges. +#[derive(Clone, Copy)] +pub(super) struct TomlDate { + pub(super) year: i32, + pub(super) month: i32, + pub(super) day: i32, +} + +/// A wall-clock time; the regex that produced it guarantees the ranges. +#[derive(Clone, Copy)] +pub(super) struct TomlTime { + pub(super) hour: i32, + pub(super) minute: i32, + pub(super) second: i32, + pub(super) microsecond: i32, +} + +/// A TOML table in insertion order (CPython's `dict`). +#[derive(Default)] +pub(super) struct TomlTable(pub(super) IndexMap); + +impl TomlTable { + /// Takes the entries out, leaving the `Drop`-implementing shell empty. + pub(super) fn into_entries(mut self) -> IndexMap { + mem::take(&mut self.0) + } +} + +impl Drop for TomlTable { + /// Drops the subtree iteratively: `[a.b.c…]` headers nest tables up to + /// [`MAX_KEY_PARTS`] deep, beyond what recursive drop glue can rely on. + /// The stack holds one iterator per level, so cleanup after a + /// `MemoryError` allocates in proportion to depth, never width. + fn drop(&mut self) { + if self.0.is_empty() { + return; + } + let mut stack = vec![Children::Table(mem::take(&mut self.0).into_values())]; + while let Some(children) = stack.last_mut() { + match children.next() { + Some(TomlValue::Array(items)) => stack.push(Children::Array(items.into_iter())), + Some(TomlValue::Table(mut table)) => { + stack.push(Children::Table(mem::take(&mut table.0).into_values())); + } + Some(_) => {} + None => { + stack.pop(); + } + } + } + } +} + +/// The not-yet-dropped children of one container, for [`TomlTable`]'s drop. +enum Children { + Array(vec::IntoIter), + Table(map::IntoValues), +} + +impl Iterator for Children { + type Item = TomlValue; + + fn next(&mut self) -> Option { + match self { + Self::Array(items) => items.next(), + Self::Table(values) => values.next(), + } + } +} + +/// Why parsing stopped. +pub(super) enum TomlError { + /// `TOMLDecodeError` with CPython's message, at a byte offset into the source. + Decode { msg: String, pos: usize }, + /// `RecursionError`: a key with too many parts, or containers nested too deep. + Recursion(String), + /// An exception a conversion raised, e.g. `int()`'s digit limit (`ValueError`). + /// Boxed to keep the recursive parser's frames small. + Run(Box), +} + +impl From for TomlError { + fn from(error: ResourceError) -> Self { + Self::Run(Box::new(RunError::from(error))) + } +} + +type ParseResult = Result; + +/// Shorthand for raising a `TOMLDecodeError` at `pos`. +fn decode_error(msg: impl Into, pos: usize) -> ParseResult { + Err(TomlError::Decode { msg: msg.into(), pos }) +} + +/// Parses a whole document, one statement (usually one line) at a time. +pub(super) fn parse(src: &str, tracker: &ResourceTracker) -> ParseResult { + let bytes = src.as_bytes(); + let mut out = Output { + data: TomlTable::default(), + flags: Flags::default(), + tracker, + }; + let mut header: Key = Vec::new(); + let mut pos = 0; + let mut statements = 0; + loop { + pos = skip_chars(bytes, pos, is_ws); + let Some(&first) = bytes.get(pos) else { break }; + if first == b'\n' { + pos += 1; + continue; + } + // Every statement but a comment adds to the tree (`[[a]]` a whole table). + check_memory_time_every(out.tracker, statements)?; + statements += 1; + if is_key_initial_char(first) { + pos = key_value_rule(src, pos, &mut out, &header)?; + pos = skip_chars(bytes, pos, is_ws); + } else if first == b'[' { + out.flags.finalize_pending(out.tracker)?; + (pos, header) = if bytes.get(pos + 1) == Some(&b'[') { + create_list_rule(src, pos, &mut out)? + } else { + create_dict_rule(src, pos, &mut out)? + }; + pos = skip_chars(bytes, pos, is_ws); + } else if first != b'#' { + return decode_error("Invalid statement", pos); + } + pos = skip_comment(bytes, pos)?; + let Some(&next) = bytes.get(pos) else { break }; + if next != b'\n' { + return decode_error("Expected newline or end of document after a statement", pos); + } + pos += 1; + } + Ok(out.data) +} + +/// The document being built: its root table plus the namespace flags. +struct Output<'t> { + data: TomlTable, + flags: Flags, + /// Polled per statement and per container element, see the module docs. + tracker: &'t ResourceTracker, +} + +/// `[table]` header: creates (or re-enters) the table the following key/value +/// pairs land in. +fn create_dict_rule(src: &str, pos: usize, out: &mut Output<'_>) -> ParseResult<(usize, Key)> { + let bytes = src.as_bytes(); + let pos = skip_chars(bytes, pos + 1, is_ws); + let (pos, key) = parse_key(src, pos)?; + if out.flags.is(&key, EXPLICIT_NEST) || out.flags.is(&key, FROZEN) { + return decode_error(format!("Cannot declare {} twice", format_key(&key)), pos); + } + out.flags.set(&key, EXPLICIT_NEST, false, out.tracker)?; + if out.data.get_or_create_nest(&key, true, out.tracker)?.is_err() { + return decode_error("Cannot overwrite a value", pos); + } + if bytes.get(pos) != Some(&b']') { + return decode_error("Expected ']' at the end of a table declaration", pos); + } + Ok((pos + 1, key)) +} + +/// `[[array]]` header: appends a new table to the array at `key`. +fn create_list_rule(src: &str, pos: usize, out: &mut Output<'_>) -> ParseResult<(usize, Key)> { + let bytes = src.as_bytes(); + let pos = skip_chars(bytes, pos + 2, is_ws); + let (pos, key) = parse_key(src, pos)?; + if out.flags.is(&key, FROZEN) { + return decode_error(format!("Cannot mutate immutable namespace {}", format_key(&key)), pos); + } + // Free the namespace now that it points to another empty list item, + // but this key precisely is still prohibited from table declaration. + out.flags.unset_all(&key); + out.flags.set(&key, EXPLICIT_NEST, false, out.tracker)?; + if out.data.append_nest_to_list(&key, out.tracker)?.is_err() { + return decode_error("Cannot overwrite a value", pos); + } + if !bytes[pos..].starts_with(b"]]") { + return decode_error("Expected ']]' at the end of an array declaration", pos); + } + Ok((pos + 2, key)) +} + +/// A top-level `key = value` statement under the current `[header]`. +fn key_value_rule(src: &str, pos: usize, out: &mut Output<'_>, header: &[String]) -> ParseResult { + let (pos, key, value) = parse_key_value_pair(src, pos, 0, out.tracker)?; + let (key_stem, key_parent) = key.split_last().expect("parse_key yields at least one part"); + let abs_key_parent: Key = header.iter().chain(key_parent).cloned().collect(); + let Output { data, flags, tracker } = out; + + for i in 1..key.len() { + let cont_key: Key = header.iter().chain(&key[..i]).cloned().collect(); + // Dotted key syntax may not redefine an existing table... + if flags.is(&cont_key, EXPLICIT_NEST) { + return decode_error(format!("Cannot redefine namespace {}", format_key(&cont_key)), pos); + } + // ...and the containers on its path can't be opened with the table + // syntax or dotted key/value syntax in following table sections. + flags.add_pending(cont_key, EXPLICIT_NEST, tracker)?; + } + + if flags.is(&abs_key_parent, FROZEN) { + return decode_error( + format!("Cannot mutate immutable namespace {}", format_key(&abs_key_parent)), + pos, + ); + } + let Ok(nest) = data.get_or_create_nest(&abs_key_parent, true, tracker)? else { + return decode_error("Cannot overwrite a value", pos); + }; + if nest.0.contains_key(key_stem) { + return decode_error("Cannot overwrite a value", pos); + } + // Inline table and array namespaces become recursively immutable. + if value.is_container() { + let full_key: Key = header.iter().chain(&key).cloned().collect(); + flags.set(&full_key, FROZEN, true, tracker)?; + } + nest.insert(key_stem.clone(), value, tracker)?; + Ok(pos) +} + +/// `key = value`, returning the position after the value. +fn parse_key_value_pair( + src: &str, + pos: usize, + depth: usize, + tracker: &ResourceTracker, +) -> ParseResult<(usize, Key, TomlValue)> { + let bytes = src.as_bytes(); + let (pos, key) = parse_key(src, pos)?; + if bytes.get(pos) != Some(&b'=') { + return decode_error("Expected '=' after a key in a key/value pair", pos); + } + let pos = skip_chars(bytes, pos + 1, is_ws); + let (pos, value) = parse_value(src, pos, depth, tracker)?; + Ok((pos, key, value)) +} + +/// A possibly dotted key, with whitespace allowed around the dots. +fn parse_key(src: &str, pos: usize) -> ParseResult<(usize, Key)> { + let bytes = src.as_bytes(); + let (pos, part) = parse_key_part(src, pos)?; + let mut key = vec![part]; + let mut pos = skip_chars(bytes, pos, is_ws); + while bytes.get(pos) == Some(&b'.') { + pos = skip_chars(bytes, pos + 1, is_ws); + let (next, part) = parse_key_part(src, pos)?; + key.push(part); + if key.len() > MAX_KEY_PARTS { + return Err(TomlError::Recursion(format!( + "TOML key has more than the allowed {MAX_KEY_PARTS} parts" + ))); + } + pos = skip_chars(bytes, next, is_ws); + } + Ok((pos, key)) +} + +/// One bare, literal-quoted or basic-quoted key part. +fn parse_key_part(src: &str, pos: usize) -> ParseResult<(usize, String)> { + let bytes = src.as_bytes(); + match bytes.get(pos) { + Some(&first) if is_bare_key_char(first) => { + let end = skip_chars(bytes, pos, is_bare_key_char); + Ok((end, src[pos..end].to_owned())) + } + Some(b'\'') => parse_literal_str(src, pos), + Some(b'"') => parse_basic_str(src, pos + 1, false), + _ => decode_error("Invalid initial character for a key part", pos), + } +} + +/// Any value in a key/value pair or array; `depth` counts enclosing inline +/// containers for the nesting limit. +fn parse_value(src: &str, pos: usize, depth: usize, tracker: &ResourceTracker) -> ParseResult<(usize, TomlValue)> { + let bytes = src.as_bytes(); + let rest = &bytes[pos.min(bytes.len())..]; + // Ordered as in CPython: strings and booleans, containers, then the + // regex-shaped scalars, with numbers after dates since `1979-05-27` would + // otherwise match as an integer. + match rest.first() { + Some(b'"') => { + let (end, text) = if rest.starts_with(b"\"\"\"") { + parse_multiline_str(src, pos, false)? + } else { + parse_basic_str(src, pos + 1, false)? + }; + return Ok((end, TomlValue::Str(text))); + } + Some(b'\'') => { + let (end, text) = if rest.starts_with(b"'''") { + parse_multiline_str(src, pos, true)? + } else { + parse_literal_str(src, pos)? + }; + return Ok((end, TomlValue::Str(text))); + } + Some(b't') if rest.starts_with(b"true") => return Ok((pos + 4, TomlValue::Bool(true))), + Some(b'f') if rest.starts_with(b"false") => return Ok((pos + 5, TomlValue::Bool(false))), + Some(b'[') => return parse_array(src, pos, nested(depth)?, tracker), + Some(b'{') => return parse_inline_table(src, pos, nested(depth)?, tracker), + _ => {} + } + + if let Some((end, date, time)) = match_datetime(bytes, pos) { + if !date.is_valid() { + return decode_error("Invalid date or datetime", pos); + } + let value = match time { + Some((time, offset_seconds)) => TomlValue::DateTime { + date, + time, + offset_seconds, + }, + None => TomlValue::Date(date), + }; + return Ok((end, value)); + } + if let Some((end, time)) = match_time(bytes, pos) { + return Ok((end, TomlValue::Time(time))); + } + if let Some((end, is_float)) = match_number(bytes, pos) { + return parse_number(&src[pos..end], is_float, pos).map(|number| (end, number)); + } + + let special = [ + (&b"inf"[..], f64::INFINITY), + (b"nan", f64::NAN), + (b"-inf", f64::NEG_INFINITY), + (b"+inf", f64::INFINITY), + // `float('-nan')` keeps the sign bit, visible through `math.copysign`. + (b"-nan", -f64::NAN), + (b"+nan", f64::NAN), + ]; + for (literal, value) in special { + if rest.starts_with(literal) { + return Ok((pos + literal.len(), TomlValue::Float(value))); + } + } + decode_error("Invalid value", pos) +} + +/// [`ResourceTracker::check_memory_time_every`] as a parse error. +fn check_memory_time_every(tracker: &ResourceTracker, i: usize) -> ParseResult<()> { + Ok(tracker.check_memory_time_every(i)?) +} + +/// The depth for a container opened at `depth`, or `RecursionError` at the limit. +fn nested(depth: usize) -> ParseResult { + if depth >= MAX_NESTING { + Err(TomlError::Recursion("maximum recursion depth exceeded".to_owned())) + } else { + Ok(depth + 1) + } +} + +/// `[a, b, ...]`, with comments and newlines allowed between elements. +fn parse_array(src: &str, pos: usize, depth: usize, tracker: &ResourceTracker) -> ParseResult<(usize, TomlValue)> { + let bytes = src.as_bytes(); + let mut array = Vec::new(); + let mut pos = skip_comments_and_array_ws(bytes, pos + 1)?; + if bytes.get(pos) == Some(&b']') { + return Ok((pos + 1, TomlValue::Array(array))); + } + loop { + check_memory_time_every(tracker, array.len())?; + let (next, value) = parse_value(src, pos, depth, tracker)?; + // The poll above sees only what is allocated; a doubling of a long + // array is preflighted so it cannot jump straight past the limit. + tracker.check_growth(array.len(), array.capacity(), mem::size_of::())?; + array.push(value); + pos = skip_comments_and_array_ws(bytes, next)?; + match bytes.get(pos) { + Some(b']') => return Ok((pos + 1, TomlValue::Array(array))), + Some(b',') => {} + _ => return decode_error("Unclosed array", pos), + } + pos = skip_comments_and_array_ws(bytes, pos + 1)?; + if bytes.get(pos) == Some(&b']') { + return Ok((pos + 1, TomlValue::Array(array))); + } + } +} + +/// `{k = v, ...}`: single-line, with its own namespace flags since dotted keys +/// inside it may not reopen an inline container. +fn parse_inline_table( + src: &str, + pos: usize, + depth: usize, + tracker: &ResourceTracker, +) -> ParseResult<(usize, TomlValue)> { + let bytes = src.as_bytes(); + let mut table = TomlTable::default(); + let mut flags = Flags::default(); + let mut pos = skip_chars(bytes, pos + 1, is_ws); + if bytes.get(pos) == Some(&b'}') { + return Ok((pos + 1, TomlValue::Table(table))); + } + // Counts pairs, not root entries: dotted keys grow the tree beneath one. + let mut pairs = 0; + loop { + check_memory_time_every(tracker, pairs)?; + pairs += 1; + let (next, key, value) = parse_key_value_pair(src, pos, depth, tracker)?; + pos = next; + let (key_stem, key_parent) = key.split_last().expect("parse_key yields at least one part"); + if flags.is(&key, FROZEN) { + return decode_error(format!("Cannot mutate immutable namespace {}", format_key(&key)), pos); + } + let Ok(nest) = table.get_or_create_nest(key_parent, false, tracker)? else { + return decode_error("Cannot overwrite a value", pos); + }; + if nest.0.contains_key(key_stem) { + return decode_error(format!("Duplicate inline table key {}", repr_str(key_stem)), pos); + } + let is_container = value.is_container(); + nest.insert(key_stem.clone(), value, tracker)?; + pos = skip_chars(bytes, pos, is_ws); + match bytes.get(pos) { + Some(b'}') => return Ok((pos + 1, TomlValue::Table(table))), + Some(b',') => {} + _ => return decode_error("Unclosed inline table", pos), + } + if is_container { + flags.set(&key, FROZEN, true, tracker)?; + } + pos = skip_chars(bytes, pos + 1, is_ws); + } +} + +/// `'...'`: no escapes, ends at the next apostrophe. +fn parse_literal_str(src: &str, pos: usize) -> ParseResult<(usize, String)> { + let start = pos + 1; + let end = skip_until(src.as_bytes(), start, b"'", is_illegal_literal_str_char, true)?; + Ok((end + 1, src[start..end].to_owned())) +} + +/// `"""..."""` or `'''...'''`, with the newline right after the opening +/// delimiter trimmed and up to two extra closing quotes kept as content. +fn parse_multiline_str(src: &str, pos: usize, literal: bool) -> ParseResult<(usize, String)> { + let bytes = src.as_bytes(); + let mut pos = pos + 3; + if bytes.get(pos) == Some(&b'\n') { + pos += 1; + } + let (mut pos, mut result, delim) = if literal { + let end = skip_until(bytes, pos, b"'''", is_illegal_multiline_literal_str_char, true)?; + (end + 3, src[pos..end].to_owned(), b'\'') + } else { + let (end, result) = parse_basic_str(src, pos, true)?; + (end, result, b'"') + }; + // A closing sequence of four or five quotes leaves one or two in the value. + for _ in 0..2 { + if bytes.get(pos) != Some(&delim) { + break; + } + pos += 1; + result.push(char::from(delim)); + } + Ok((pos, result)) +} + +/// The body of a `"..."` or `"""..."""` string, `pos` just past the opening +/// quote(s); resolves escapes and rejects control characters. +fn parse_basic_str(src: &str, pos: usize, multiline: bool) -> ParseResult<(usize, String)> { + let bytes = src.as_bytes(); + let is_illegal = if multiline { + is_illegal_multiline_basic_str_char + } else { + is_illegal_basic_str_char + }; + let mut result = String::new(); + let mut start = pos; + let mut pos = pos; + loop { + let Some(&byte) = bytes.get(pos) else { + return decode_error("Unterminated string", pos); + }; + match byte { + b'"' => { + if !multiline { + result.push_str(&src[start..pos]); + return Ok((pos + 1, result)); + } + if bytes[pos..].starts_with(b"\"\"\"") { + result.push_str(&src[start..pos]); + return Ok((pos + 3, result)); + } + pos += 1; + } + b'\\' => { + result.push_str(&src[start..pos]); + let (next, escaped) = parse_basic_str_escape(src, pos, multiline)?; + result.extend(escaped); + pos = next; + start = pos; + } + byte if is_illegal(byte) => { + return decode_error(format!("Illegal character {}", repr_ctrl_char(byte)), pos); + } + _ => pos += 1, + } + } +} + +/// One backslash escape at `pos`; `None` is the multiline line-ending +/// backslash, which contributes nothing. +fn parse_basic_str_escape(src: &str, pos: usize, multiline: bool) -> ParseResult<(usize, Option)> { + let bytes = src.as_bytes(); + // CPython's `pos += 2` steps over two characters: past the end for a lone + // trailing backslash, and never into the middle of a multibyte one. + let escaped_len = src[pos + 1..].chars().next().map_or(1, char::len_utf8); + let escape = &bytes[pos..(pos + 1 + escaped_len).min(bytes.len())]; + let mut pos = pos + 1 + escaped_len; + if multiline && matches!(escape, b"\\ " | b"\\\t" | b"\\\n") { + // Skip whitespace until the next non-whitespace character or the end + // of the document; anything but a newline before that is an error. + if escape != b"\\\n" { + pos = skip_chars(bytes, pos, is_ws); + let Some(&next) = bytes.get(pos) else { + return Ok((pos, None)); + }; + if next != b'\n' { + return decode_error("Unescaped '\\' in a string", pos); + } + pos += 1; + } + return Ok((skip_chars(bytes, pos, is_ws_or_newline), None)); + } + let replacement = match escape { + b"\\u" => return parse_hex_char(src, pos, 4), + b"\\U" => return parse_hex_char(src, pos, 8), + b"\\b" => '\u{8}', + b"\\t" => '\t', + b"\\n" => '\n', + b"\\f" => '\u{c}', + b"\\r" => '\r', + b"\\\"" => '"', + b"\\\\" => '\\', + _ => return decode_error("Unescaped '\\' in a string", pos), + }; + Ok((pos, Some(replacement))) +} + +/// The `hex_len` digits of a `\u` / `\U` escape, which must name a scalar value. +fn parse_hex_char(src: &str, pos: usize, hex_len: usize) -> ParseResult<(usize, Option)> { + let bytes = src.as_bytes(); + let hex = bytes + .get(pos..pos + hex_len) + .filter(|digits| digits.iter().all(u8::is_ascii_hexdigit)); + let Some(hex) = hex else { + return decode_error("Invalid hex value", pos); + }; + let pos = pos + hex_len; + let code = hex.iter().fold(0u32, |acc, &digit| { + acc * 16 + char::from(digit).to_digit(16).expect("validated hex digit") + }); + // `from_u32` rejects exactly the non-scalar values: surrogates and > U+10FFFF. + match char::from_u32(code) { + Some(c) => Ok((pos, Some(c))), + None => decode_error("Escaped character is not a Unicode scalar value", pos), + } +} + +/// The number token matched by [`match_number`], as `float()` or `int(s, 0)` +/// would convert it (both accept the `_` separators). +fn parse_number(text: &str, is_float: bool, pos: usize) -> ParseResult { + // Allocates only when there are `_` separators to strip. + let digits = if text.contains('_') { + Cow::Owned(text.replace('_', "")) + } else { + Cow::Borrowed(text) + }; + if is_float { + return match digits.parse::() { + Ok(value) => Ok(TomlValue::Float(value)), + Err(_) => decode_error("Invalid value", pos), + }; + } + let (radix, body, negative) = if let Some(hex) = digits.strip_prefix("0x") { + (16, hex, false) + } else if let Some(octal) = digits.strip_prefix("0o") { + (8, octal, false) + } else if let Some(binary) = digits.strip_prefix("0b") { + (2, binary, false) + } else if let Some(magnitude) = digits.strip_prefix('-') { + (10, magnitude, true) + } else { + (10, digits.strip_prefix('+').unwrap_or(&digits), false) + }; + if radix == 10 { + // `int()` refuses decimal literals past `sys.int_info.str_digits_check_threshold`. + check_decimal_digit_count(body.len()).map_err(|error| TomlError::Run(Box::new(error)))?; + } + // Most literals fit `i64`; the rest (and `i64::MIN`'s magnitude) go through `BigInt`. + let int = if let Ok(magnitude) = i64::from_str_radix(body, radix) { + TomlInt::Small(if negative { -magnitude } else { magnitude }) + } else { + let magnitude = BigInt::parse_bytes(body.as_bytes(), radix).expect("match_number validated the digits"); + let value = if negative { -magnitude } else { magnitude }; + match i64::try_from(&value) { + Ok(small) => TomlInt::Small(small), + Err(_) => TomlInt::Big(value), + } + }; + Ok(TomlValue::Int(int)) +} + +/// A `RE_DATETIME` match: its end, the date, and the time with its UTC offset +/// in seconds when the document had them. +type DateTimeMatch = (usize, TomlDate, Option<(TomlTime, Option)>); + +/// `RE_DATETIME` at `pos`: a date, optionally followed by a time and offset. +/// +/// The time and offset groups are optional, so a date followed by something +/// that is almost a time still matches as a bare date, like the regex. +fn match_datetime(bytes: &[u8], pos: usize) -> Option { + let year = bytes + .get(pos..pos + 4) + .filter(|digits| digits.iter().all(u8::is_ascii_digit))? + .iter() + .fold(0, |acc, &digit| acc * 10 + i32::from(digit - b'0')); + if bytes.get(pos + 4) != Some(&b'-') { + return None; + } + let month = match_digit_pair(bytes, pos + 5, |tens, ones| { + (tens == 0 && ones >= 1) || (tens == 1 && ones <= 2) + })?; + if bytes.get(pos + 7) != Some(&b'-') { + return None; + } + let day = match_digit_pair(bytes, pos + 8, |tens, ones| { + (tens == 0 && ones >= 1) || tens == 1 || tens == 2 || (tens == 3 && ones <= 1) + })?; + let date = TomlDate { year, month, day }; + let date_end = pos + 10; + + if !matches!(bytes.get(date_end), Some(b'T' | b't' | b' ')) { + return Some((date_end, date, None)); + } + let Some((time_end, time)) = match_time(bytes, date_end + 1) else { + return Some((date_end, date, None)); + }; + let (end, offset_seconds) = match bytes.get(time_end) { + Some(b'Z' | b'z') => (time_end + 1, Some(0)), + Some(&sign @ (b'+' | b'-')) => { + let hours = match_digit_pair(bytes, time_end + 1, is_hour_pair); + let colon = bytes.get(time_end + 3) == Some(&b':'); + let minutes = match_digit_pair(bytes, time_end + 4, |tens, _| tens <= 5); + match (hours, colon, minutes) { + (Some(hours), true, Some(minutes)) => { + let seconds = hours * 3600 + minutes * 60; + (time_end + 6, Some(if sign == b'-' { -seconds } else { seconds })) + } + _ => (time_end, None), + } + } + _ => (time_end, None), + }; + Some((end, date, Some((time, offset_seconds)))) +} + +/// `RE_LOCALTIME` at `pos`: `HH:MM:SS` with an optional fraction, of which the +/// first six digits are kept. +fn match_time(bytes: &[u8], pos: usize) -> Option<(usize, TomlTime)> { + let hour = match_digit_pair(bytes, pos, is_hour_pair)?; + if bytes.get(pos + 2) != Some(&b':') { + return None; + } + let minute = match_digit_pair(bytes, pos + 3, |tens, _| tens <= 5)?; + if bytes.get(pos + 5) != Some(&b':') { + return None; + } + let second = match_digit_pair(bytes, pos + 6, |tens, _| tens <= 5)?; + let mut end = pos + 8; + let mut microsecond = 0; + if bytes.get(end) == Some(&b'.') && bytes.get(end + 1).is_some_and(u8::is_ascii_digit) { + let digits_start = end + 1; + end = skip_chars(bytes, digits_start, |byte| byte.is_ascii_digit()); + let kept = &bytes[digits_start..(digits_start + 6).min(end)]; + let padding = 10_i32.pow(u32::try_from(6 - kept.len()).expect("at most six digits kept")); + microsecond = kept.iter().fold(0, |acc, &digit| acc * 10 + i32::from(digit - b'0')) * padding; + } + Some(( + end, + TomlTime { + hour, + minute, + second, + microsecond, + }, + )) +} + +/// `[01][0-9]|2[0-3]` as a (tens, ones) predicate. +fn is_hour_pair(tens: u8, ones: u8) -> bool { + tens <= 1 || (tens == 2 && ones <= 3) +} + +/// Two ASCII digits at `pos` whose values satisfy `valid`, as a number. +fn match_digit_pair(bytes: &[u8], pos: usize, valid: impl Fn(u8, u8) -> bool) -> Option { + let tens = bytes.get(pos).filter(|byte| byte.is_ascii_digit())? - b'0'; + let ones = bytes.get(pos + 1).filter(|byte| byte.is_ascii_digit())? - b'0'; + valid(tens, ones).then(|| i32::from(tens) * 10 + i32::from(ones)) +} + +/// `RE_NUMBER` at `pos`: `(end, is_float)`, where `is_float` is CPython's +/// non-empty `floatpart` group. +fn match_number(bytes: &[u8], pos: usize) -> Option<(usize, bool)> { + // Prefixed integers come first in the regex; without a digit after the + // prefix the alternative fails and the plain `0` below matches instead. + if bytes.get(pos) == Some(&b'0') { + let radix_digit: Option bool> = match bytes.get(pos + 1) { + Some(b'x') => Some(|byte| byte.is_ascii_hexdigit()), + Some(b'o') => Some(|byte| matches!(byte, b'0'..=b'7')), + Some(b'b') => Some(|byte| matches!(byte, b'0' | b'1')), + _ => None, + }; + if let Some(is_digit) = radix_digit + && let Some(end) = match_digit_run(bytes, pos + 2, is_digit) + { + return Some((end, false)); + } + } + let mut pos = pos; + if matches!(bytes.get(pos), Some(b'+' | b'-')) { + pos += 1; + } + let mut end = match bytes.get(pos)? { + b'0' => pos + 1, + b'1'..=b'9' => match_digit_run(bytes, pos, |byte| byte.is_ascii_digit())?, + _ => return None, + }; + let mut is_float = false; + if bytes.get(end) == Some(&b'.') + && let Some(fraction_end) = match_digit_run(bytes, end + 1, |byte| byte.is_ascii_digit()) + { + end = fraction_end; + is_float = true; + } + if matches!(bytes.get(end), Some(b'e' | b'E')) { + let mut exponent = end + 1; + if matches!(bytes.get(exponent), Some(b'+' | b'-')) { + exponent += 1; + } + if let Some(exponent_end) = match_digit_run(bytes, exponent, |byte| byte.is_ascii_digit()) { + end = exponent_end; + is_float = true; + } + } + Some((end, is_float)) +} + +/// `D(?:_?D)*` at `pos`: at least one digit, underscores only between digits. +fn match_digit_run(bytes: &[u8], pos: usize, is_digit: impl Fn(u8) -> bool) -> Option { + if !bytes.get(pos).is_some_and(|&byte| is_digit(byte)) { + return None; + } + let mut end = pos + 1; + loop { + match bytes.get(end) { + Some(&byte) if is_digit(byte) => end += 1, + Some(b'_') if bytes.get(end + 1).is_some_and(|&byte| is_digit(byte)) => end += 2, + _ => return Some(end), + } + } +} + +/// Advances past every byte satisfying `pred`. +fn skip_chars(bytes: &[u8], mut pos: usize, pred: impl Fn(u8) -> bool) -> usize { + while bytes.get(pos).is_some_and(|&byte| pred(byte)) { + pos += 1; + } + pos +} + +/// Position of the next `expect` at or after `pos` (the end of input when +/// absent and `error_on_eof` is unset), rejecting any `error_on` byte before it. +fn skip_until( + bytes: &[u8], + pos: usize, + expect: &[u8], + error_on: impl Fn(u8) -> bool, + error_on_eof: bool, +) -> ParseResult { + let found = (pos..=bytes.len().saturating_sub(expect.len())).find(|&i| bytes[i..].starts_with(expect)); + let new_pos = match found { + Some(found) => found, + None if error_on_eof => return decode_error(format!("Expected {}", repr_delimiter(expect)), bytes.len()), + None => bytes.len(), + }; + match bytes[pos..new_pos].iter().position(|&byte| error_on(byte)) { + Some(offset) => decode_error( + format!("Found invalid character {}", repr_ctrl_char(bytes[pos + offset])), + pos + offset, + ), + None => Ok(new_pos), + } +} + +/// Skips a `#` comment up to (not including) the newline. +fn skip_comment(bytes: &[u8], pos: usize) -> ParseResult { + if bytes.get(pos) == Some(&b'#') { + skip_until(bytes, pos + 1, b"\n", is_illegal_comment_char, false) + } else { + Ok(pos) + } +} + +/// Skips the whitespace, newlines and comments allowed between array elements. +fn skip_comments_and_array_ws(bytes: &[u8], mut pos: usize) -> ParseResult { + loop { + let before = pos; + pos = skip_chars(bytes, pos, is_ws_or_newline); + pos = skip_comment(bytes, pos)?; + if pos == before { + return Ok(pos); + } + } +} + +/// `TOML_WS`. +fn is_ws(byte: u8) -> bool { + matches!(byte, b' ' | b'\t') +} + +/// `TOML_WS_AND_NEWLINE`. +fn is_ws_or_newline(byte: u8) -> bool { + matches!(byte, b' ' | b'\t' | b'\n') +} + +/// `BARE_KEY_CHARS`: ASCII letters, digits, `-` and `_`. +fn is_bare_key_char(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_') +} + +/// `KEY_INITIAL_CHARS`: a bare key character or either quote. +fn is_key_initial_char(byte: u8) -> bool { + is_bare_key_char(byte) || matches!(byte, b'"' | b'\'') +} + +/// `ILLEGAL_BASIC_STR_CHARS`: the ASCII controls other than tab. Also the +/// literal-string and comment sets, which CPython defines identically. +fn is_illegal_basic_str_char(byte: u8) -> bool { + (byte < 0x20 && byte != b'\t') || byte == 0x7f +} + +/// `ILLEGAL_MULTILINE_BASIC_STR_CHARS`: the controls other than tab and newline. +fn is_illegal_multiline_basic_str_char(byte: u8) -> bool { + is_illegal_basic_str_char(byte) && byte != b'\n' +} + +/// `ILLEGAL_LITERAL_STR_CHARS`. +fn is_illegal_literal_str_char(byte: u8) -> bool { + is_illegal_basic_str_char(byte) +} + +/// `ILLEGAL_MULTILINE_LITERAL_STR_CHARS`. +fn is_illegal_multiline_literal_str_char(byte: u8) -> bool { + is_illegal_multiline_basic_str_char(byte) +} + +/// `ILLEGAL_COMMENT_CHARS`. +fn is_illegal_comment_char(byte: u8) -> bool { + is_illegal_basic_str_char(byte) +} + +/// Python's `repr()` of a one-character control string, the only characters +/// the `Illegal character` / `Found invalid character` messages report. +fn repr_ctrl_char(byte: u8) -> String { + match byte { + b'\n' => "'\\n'".to_owned(), + b'\r' => "'\\r'".to_owned(), + _ => format!("'\\x{byte:02x}'"), + } +} + +/// Python's `repr()` of a closing delimiter (`'` or `'''`), which it +/// double-quotes because of the apostrophes. +fn repr_delimiter(delimiter: &[u8]) -> String { + format!("\"{}\"", String::from_utf8_lossy(delimiter)) +} + +/// Python's `repr()` of a `str`. +fn repr_str(s: &str) -> String { + let mut out = String::new(); + string_repr_fmt(s, &mut out).expect("writing to a String cannot fail"); + out +} + +/// Python's `repr()` of a key tuple: `('a',)` or `('a', 'b')`. +fn format_key(key: &[String]) -> String { + let mut out = String::from("("); + for (i, part) in key.iter().enumerate() { + if i > 0 { + out.push_str(", "); + } + string_repr_fmt(part, &mut out).expect("writing to a String cannot fail"); + } + if key.len() == 1 { + out.push(','); + } + out.push(')'); + out +} + +impl TomlDate { + /// Whether `datetime.date(year, month, day)` would accept these fields. + fn is_valid(self) -> bool { + (1..=9999).contains(&self.year) + && NaiveDate::from_ymd_opt( + self.year, + u32::try_from(self.month).expect("regex yields 01..12"), + u32::try_from(self.day).expect("regex yields 01..31"), + ) + .is_some() + } +} + +/// Table lookup that could not be satisfied: a value stands where a table or +/// array of tables is needed (CPython's `KeyError` inside `NestedDict`). +struct NestError; + +impl TomlTable { + /// The table at `key`, creating empty tables on the way. With + /// `access_lists`, an array of tables on the path stands for its last table. + /// The outer error is a `MemoryError` from growing a table. + fn get_or_create_nest( + &mut self, + key: &[String], + access_lists: bool, + tracker: &ResourceTracker, + ) -> ParseResult> { + let mut cont = self; + for part in key { + if !cont.0.contains_key(part) { + cont.insert(part.clone(), TomlValue::Table(Self::default()), tracker)?; + } + cont = match cont.0.get_mut(part).expect("inserted above") { + TomlValue::Table(table) => table, + TomlValue::Array(items) if access_lists => match items.last_mut() { + Some(TomlValue::Table(table)) => table, + _ => return Ok(Err(NestError)), + }, + _ => return Ok(Err(NestError)), + }; + } + Ok(Ok(cont)) + } + + /// Appends an empty table to the array at `key`, creating the array when absent. + fn append_nest_to_list(&mut self, key: &[String], tracker: &ResourceTracker) -> ParseResult> { + let (last, parents) = key.split_last().expect("parse_key yields at least one part"); + let Ok(cont) = self.get_or_create_nest(parents, true, tracker)? else { + return Ok(Err(NestError)); + }; + Ok(match cont.0.get_mut(last) { + Some(TomlValue::Array(items)) => { + tracker.check_growth(items.len(), items.capacity(), mem::size_of::())?; + items.push(TomlValue::Table(Self::default())); + Ok(()) + } + Some(_) => Err(NestError), + None => { + let items = vec![TomlValue::Table(Self::default())]; + cont.insert(last.clone(), TomlValue::Array(items), tracker)?; + Ok(()) + } + }) + } + + /// Inserts a new key, preflighting the doubling of a full table: the poll + /// in the element loops sees only what is already allocated. + fn insert(&mut self, key: String, value: TomlValue, tracker: &ResourceTracker) -> ParseResult<()> { + tracker.check_growth(self.0.len(), self.0.capacity(), TABLE_ENTRY_GROWTH)?; + self.0.insert(key, value); + Ok(()) + } +} + +/// Namespace flags keyed by dotted path: which tables were created explicitly +/// and which inline containers are frozen (CPython's `Flags`). +#[derive(Default)] +struct Flags { + root: HashMap, + /// Flags a dotted key/value pair sets on its path once the current + /// `[table]` section ends. + pending: Vec<(Key, u8)>, +} + +/// One key part's flags: those on the part itself, those inherited by +/// everything beneath it, and the parts nested under it. +#[derive(Default)] +struct FlagNode { + flags: u8, + recursive_flags: u8, + nested: HashMap, +} + +impl Drop for FlagNode { + /// Drops the subtree iteratively: it mirrors the table nesting, so it can + /// be [`MAX_KEY_PARTS`] deep, whether the whole tree goes or `unset_all` + /// removes one node. + fn drop(&mut self) { + let mut pending: Vec = self.nested.drain().map(|(_, node)| node).collect(); + while let Some(mut node) = pending.pop() { + pending.extend(node.nested.drain().map(|(_, node)| node)); + } + } +} + +impl Flags { + /// Queues a flag for [`Self::finalize_pending`], preflighting the queue's + /// doubling: a section of many dotted keys grows it by one entry per part. + fn add_pending(&mut self, key: Key, flag: u8, tracker: &ResourceTracker) -> Result<(), ResourceError> { + tracker.check_growth(self.pending.len(), self.pending.capacity(), mem::size_of::<(Key, u8)>())?; + self.pending.push((key, flag)); + Ok(()) + } + + fn finalize_pending(&mut self, tracker: &ResourceTracker) -> Result<(), ResourceError> { + for (key, flag) in mem::take(&mut self.pending) { + self.set(&key, flag, false, tracker)?; + } + Ok(()) + } + + /// Drops every flag at and beneath `key`. + fn unset_all(&mut self, key: &[String]) { + let Some((stem, parents)) = key.split_last() else { + return; + }; + let mut cont = &mut self.root; + for part in parents { + match cont.get_mut(part) { + Some(node) => cont = &mut node.nested, + None => return, + } + } + cont.remove(stem); + } + + fn set( + &mut self, + key: &[String], + flag: u8, + recursive: bool, + tracker: &ResourceTracker, + ) -> Result<(), ResourceError> { + let Some((stem, parents)) = key.split_last() else { + return Ok(()); + }; + let mut cont = &mut self.root; + for part in parents { + cont = &mut flag_node(cont, part, tracker)?.nested; + } + let node = flag_node(cont, stem, tracker)?; + if recursive { + node.recursive_flags |= flag; + } else { + node.flags |= flag; + } + Ok(()) + } + + /// Whether `key` carries `flag`, directly or inherited from an ancestor's + /// recursive flags. The document root has no flags. + fn is(&self, key: &[String], flag: u8) -> bool { + let Some((stem, parents)) = key.split_last() else { + return false; + }; + let mut cont = &self.root; + for part in parents { + let Some(inner) = cont.get(part) else { return false }; + if inner.recursive_flags & flag != 0 { + return true; + } + cont = &inner.nested; + } + cont.get(stem) + .is_some_and(|node| (node.flags | node.recursive_flags) & flag != 0) + } +} + +/// The node for `part`, created if absent after preflighting the rehash a +/// full map would do; a document of many tables grows one map by thousands. +fn flag_node<'m>( + map: &'m mut HashMap, + part: &str, + tracker: &ResourceTracker, +) -> Result<&'m mut FlagNode, ResourceError> { + tracker.check_growth(map.len(), map.capacity(), FLAG_ENTRY_GROWTH)?; + Ok(map.entry(part.to_owned()).or_default()) +} diff --git a/crates/bashkit-monty/src/modules/tomllib/value.rs b/crates/bashkit-monty/src/modules/tomllib/value.rs new file mode 100644 index 000000000..99aabe4c6 --- /dev/null +++ b/crates/bashkit-monty/src/modules/tomllib/value.rs @@ -0,0 +1,191 @@ +//! Conversion of a parsed TOML tree into Monty values. +//! +//! Runs only after [`super::parser`] accepted the whole document, so every +//! allocation here is for a value that will be returned. The walk is iterative +//! with an explicit stack of half-built containers: `[a.b.c…]` headers nest +//! tables as deep as the key-part limit allows, far deeper than Rust recursion +//! could safely follow on a small thread stack. The stack is guarded while it +//! fills, so a memory limit tripped halfway releases what was built, and the +//! per-element poll keeps a huge document from allocating past the soft limit +//! inside this single native call. + +use std::vec; + +use indexmap::map; + +use super::parser::{TomlDate, TomlInt, TomlTable, TomlTime, TomlValue}; +use crate::{ + bytecode::VM, + defer_drop_mut, + exception_private::RunResult, + heap::{ContainsHeap, DropWithContext, HeapData}, + types::{Dict, List, LongInt, TimeZone, date, datetime, str::allocate_string, time}, + value::{VALUE_SIZE, Value}, +}; + +/// Converts the document's root table into the dict `tomllib.loads()` returns. +pub(super) fn table_into_value(table: TomlTable, vm: &mut VM<'_>) -> RunResult { + let stack: Vec = Vec::new(); + defer_drop_mut!(stack, vm); + let mut next = Step::Convert(TomlValue::Table(table)); + loop { + let value = match next { + Step::Convert(node) => match Frame::open(node, vm)? { + Ok(frame) => { + stack.push(frame); + next = Step::Descend; + continue; + } + Err(scalar) => scalar, + }, + Step::Descend => match stack.last_mut().expect("Descend follows a push") { + Frame::List { items, values } => match items.next() { + Some(item) => { + vm.heap.tracker.check_memory_time_every(values.len())?; + next = Step::Convert(item); + continue; + } + None => Frame::finish(stack.pop(), vm), + }, + Frame::Dict { + entries, + dict, + pending_key, + } => match entries.next() { + Some((key, item)) => { + vm.heap.tracker.check_memory_time_every(dict.len())?; + *pending_key = Some(allocate_string(key, vm.heap)); + next = Step::Convert(item); + continue; + } + None => Frame::finish(stack.pop(), vm), + }, + }, + }; + // `value` is complete: hand it to the enclosing container, or return it. + let Some(parent) = stack.last_mut() else { + return Ok(value); + }; + parent.store(value, vm)?; + next = Step::Descend; + } +} + +/// What the conversion loop does next. +enum Step { + /// Turn `node` into a value, opening a frame if it is a container. + Convert(TomlValue), + /// Continue with the next child of the innermost open container. + Descend, +} + +/// A container whose children are still being converted. +enum Frame { + List { + items: vec::IntoIter, + values: Vec, + }, + Dict { + entries: map::IntoIter, + dict: Dict, + /// The key allocated for the child currently being converted. + pending_key: Option, + }, +} + +impl Frame { + /// Opens a frame for a container node, or converts a scalar in place. + fn open(node: TomlValue, vm: &mut VM<'_>) -> RunResult> { + let scalar = match node { + TomlValue::Array(items) => { + vm.heap.tracker.check_allocation(items.len() * VALUE_SIZE)?; + let values = Vec::with_capacity(items.len()); + return Ok(Ok(Self::List { + items: items.into_iter(), + values, + })); + } + TomlValue::Table(table) => { + let entries = table.into_entries(); + // No bulk reservation: `set_json_string_key` preflights each + // capacity doubling against the memory limit as the dict fills. + let dict = Dict::new(); + return Ok(Ok(Self::Dict { + entries: entries.into_iter(), + dict, + pending_key: None, + })); + } + TomlValue::Str(text) => allocate_string(text, vm.heap), + TomlValue::Int(TomlInt::Small(value)) => Value::Int(value), + TomlValue::Int(TomlInt::Big(value)) => LongInt::new(value).into_value(vm.heap), + TomlValue::Float(value) => Value::Float(value), + TomlValue::Bool(value) => Value::Bool(value), + TomlValue::Date(date) => date::allocate_ymd(date.year, date.month, date.day, vm.heap), + TomlValue::Time(time) => { + time::allocate_naive(time.hour, time.minute, time.second, time.microsecond, vm.heap) + } + TomlValue::DateTime { + date, + time, + offset_seconds, + } => allocate_datetime(date, time, offset_seconds, vm)?, + }; + Ok(Err(scalar)) + } + + /// Stores a converted child. Table keys are unique, so no entry is replaced. + fn store(&mut self, value: Value, vm: &mut VM<'_>) -> RunResult<()> { + match self { + Self::List { values, .. } => values.push(value), + Self::Dict { dict, pending_key, .. } => { + let key = pending_key + .take() + .expect("a key is allocated before its value is converted"); + if let Some(replaced) = dict.set_json_string_key(key, value, vm)? { + replaced.drop_with(vm); + } + } + } + Ok(()) + } + + /// Allocates the heap object for a frame whose children are all stored. + fn finish(frame: Option, vm: &mut VM<'_>) -> Value { + match frame.expect("Descend follows a push") { + Self::List { values, .. } => Value::Ref(vm.heap.allocate(HeapData::List(List::new(values)))), + Self::Dict { dict, .. } => Value::Ref(vm.heap.allocate(HeapData::Dict(dict))), + } + } +} + +impl DropWithContext for Frame { + fn drop_with(self, ctx: &mut C) { + match self { + Self::List { values, .. } => values.drop_with(ctx), + Self::Dict { dict, pending_key, .. } => { + dict.drop_with(ctx); + pending_key.drop_with(ctx); + } + } + } +} + +/// A `datetime`, aware when the document gave an offset (`Z` is UTC). +fn allocate_datetime(date: TomlDate, time: TomlTime, offset_seconds: Option, vm: &mut VM<'_>) -> RunResult { + // The regex bounds offsets to ±23:59, inside `timezone()`'s open ±24h range. + let tzinfo = offset_seconds.map(|seconds| TimeZone::new(seconds, None)).transpose()?; + let datetime = datetime::from_components( + date.year, + date.month, + date.day, + time.hour, + time.minute, + time.second, + time.microsecond, + tzinfo, + None, + vm.heap, + )?; + Ok(Value::Ref(vm.heap.allocate(HeapData::DateTime(datetime)))) +} diff --git a/crates/bashkit-monty/src/modules/typing.rs b/crates/bashkit-monty/src/modules/typing.rs new file mode 100644 index 000000000..6b46709b0 --- /dev/null +++ b/crates/bashkit-monty/src/modules/typing.rs @@ -0,0 +1,74 @@ +//! Implementation of the `typing` module. +//! +//! Provides a minimal implementation of Python's `typing` module with: +//! - `TYPE_CHECKING`: Always False (used for conditional imports) +//! - Common type hints as `Marker` values (Any, Optional, List, Dict, etc.) +//! - `Union`, the type behind `int | None` (see `types/union.rs`) +//! +//! These markers exist so code that imports typing constructs works correctly, +//! though Monty doesn't perform static type checking. `Optional[X]` is the one +//! marker that can be subscripted, producing `X | None`. + +use crate::{ + builtins::Builtins, + bytecode::VM, + heap::{HeapData, HeapId}, + intern::StaticStrings, + types::{Module, Type}, + value::{Marker, Value}, +}; + +/// Creates the `typing` module and allocates it on the heap. +/// +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Typing, vm.interns); + + // typing.TYPE_CHECKING - always False + module.set_attr(StaticStrings::TypeChecking, Value::Bool(false), vm); + + // `typing.Union` is the type of `int | None` (one object with + // `types.UnionType` since 3.14), so it is a real type rather than a marker. + module.set_attr( + StaticStrings::UnionType, + Value::Builtin(Builtins::Type(Type::Union)), + vm, + ); + + // Export all typing markers as module attributes + for ss in MARKER_ATTRS { + module.set_attr(*ss, Value::Marker(Marker(*ss)), vm); + } + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Typing marker attributes exported by this module. +/// +/// Each marker wraps its corresponding `StaticStrings` variant as both the +/// attribute name and the marker value. +const MARKER_ATTRS: &[StaticStrings] = &[ + StaticStrings::Any, + StaticStrings::Optional, + StaticStrings::ListType, + StaticStrings::DictType, + StaticStrings::TupleType, + StaticStrings::SetType, + StaticStrings::FrozenSet, + StaticStrings::Callable, + StaticStrings::Type, + StaticStrings::Sequence, + StaticStrings::Mapping, + StaticStrings::Iterable, + StaticStrings::IteratorType, + StaticStrings::Generator, + StaticStrings::ClassVar, + StaticStrings::FinalType, + StaticStrings::Literal, + StaticStrings::TypeVar, + StaticStrings::Generic, + StaticStrings::Protocol, + StaticStrings::Annotated, + StaticStrings::SelfType, + StaticStrings::Never, + StaticStrings::NoReturn, +]; diff --git a/crates/bashkit-monty/src/modules/unicodedata.rs b/crates/bashkit-monty/src/modules/unicodedata.rs new file mode 100644 index 000000000..cc427e7b6 --- /dev/null +++ b/crates/bashkit-monty/src/modules/unicodedata.rs @@ -0,0 +1,353 @@ +//! Implementation of Python's `unicodedata` module. +//! +//! Provides access to the Unicode Character Database: general categories, +//! canonical combining classes, character names, and normalization. Only the +//! widely-used functions are implemented; see `limitations/unicodedata.md` for +//! the full list of divergences from CPython (notably the data-heavy functions +//! `decimal`/`digit`/`numeric`/`bidirectional`/`east_asian_width`/`mirrored`/ +//! `decomposition`, which are intentionally not implemented). +//! +//! ## Implemented functions +//! +//! - `category(chr)` — two-letter general category (e.g. `"Lu"`, `"Nd"`) +//! - `name(chr[, default])` — the Unicode name of a character +//! - `lookup(name)` — the character with a given name +//! - `combining(chr)` — the canonical combining class as an int +//! - `normalize(form, unistr)` — NFC/NFD/NFKC/NFKD normalization +//! - `is_normalized(form, unistr)` — whether a string is already normalized +//! +//! ## Constants +//! +//! `unidata_version` — the Unicode version string. +//! +//! All functions are pure computations that don't require host involvement, so +//! they return `Value` directly (wrapped in `CallResult::Value` by the dispatch +//! in [`super`]). + +use unicode_general_category::{GeneralCategory, get_general_category}; +use unicode_normalization::{UnicodeNormalization, char::canonical_combining_class}; + +use crate::{ + args::{ArgValues, FromArgs, StrArg}, + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult, SimpleException}, + heap::{DropGuard, Heap, HeapData, HeapId}, + intern::StaticStrings, + modules::ModuleFunctions, + string_builder::StringBuilder, + types::{Module, str::allocate_string}, + value::Value, +}; + +/// The Unicode version reported by `unicodedata.unidata_version`. +/// +/// Hard-coded to match CPython 3.14 rather than derived from the backing +/// crates: those crates' data tables may lag or lead this version (e.g. +/// `unicode-normalization` currently ships Unicode 17.0 tables), so reporting +/// their versions would diverge from CPython. See `limitations/unicodedata.md`. +const UNIDATA_VERSION: &str = "16.0.0"; + +/// `unicodedata` module functions — each variant corresponds to a Python-visible function. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize, serde::Deserialize)] +#[strum(serialize_all = "snake_case")] +pub(crate) enum UnicodedataFunctions { + Category, + Name, + Lookup, + Combining, + Normalize, + IsNormalized, +} + +/// Static mapping of attribute names to functions for module creation. +const UNICODEDATA_FUNCTIONS: &[(StaticStrings, UnicodedataFunctions)] = &[ + (StaticStrings::Category, UnicodedataFunctions::Category), + (StaticStrings::Name, UnicodedataFunctions::Name), + (StaticStrings::Lookup, UnicodedataFunctions::Lookup), + (StaticStrings::Combining, UnicodedataFunctions::Combining), + (StaticStrings::Normalize, UnicodedataFunctions::Normalize), + (StaticStrings::IsNormalized, UnicodedataFunctions::IsNormalized), +]; + +/// Creates the `unicodedata` module on the heap. +pub fn create_module(vm: &mut VM<'_>) -> HeapId { + let mut module = Module::new(StaticStrings::Unicodedata, vm.interns); + + for (name, func) in UNICODEDATA_FUNCTIONS { + module.set_attr(*name, Value::ModuleFunction(ModuleFunctions::Unicodedata(*func)), vm); + } + + let version = allocate_string(UNIDATA_VERSION, vm.heap); + module.set_attr(StaticStrings::UnidataVersion, version, vm); + + vm.heap.allocate(HeapData::Module(Box::new(module))) +} + +/// Dispatches a call to a `unicodedata` module function. +/// +/// All functions are pure computations and return `Value` directly. +pub(super) fn call(vm: &mut VM<'_>, function: UnicodedataFunctions, args: ArgValues) -> RunResult { + match function { + UnicodedataFunctions::Category => uni_category(vm, args), + UnicodedataFunctions::Name => uni_name(vm, args), + UnicodedataFunctions::Lookup => uni_lookup(vm, args), + UnicodedataFunctions::Combining => uni_combining(vm, args), + UnicodedataFunctions::Normalize => uni_normalize(vm, args), + UnicodedataFunctions::IsNormalized => uni_is_normalized(vm, args), + } +} + +/// `unicodedata.category(chr)` — the two-letter general category abbreviation. +/// +/// Returns e.g. `"Lu"` (uppercase letter), `"Nd"` (decimal digit), or `"Cn"` +/// for unassigned code points. +fn uni_category(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("category", vm.heap)?; + defer_drop!(value, vm); + let c = single_char(value, "category", None, vm)?; + Ok(allocate_string(category_abbrev(get_general_category(c)), vm.heap)) +} + +/// `unicodedata.name(chr[, default])` — the Unicode name of a character. +/// +/// Raises `ValueError("no such name")` when the character has no name and no +/// `default` is supplied; otherwise returns `default`. +fn uni_name(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let NameArgs { + chr: chr_val, + default: default_val, + } = NameArgs::from_args(args, vm)?; + defer_drop!(chr_val, vm); + let mut default_guard = DropGuard::new(default_val, vm); + let vm = default_guard.ctx(); + let c = single_char(chr_val, "name", Some(1), vm)?; + + match unicode_names2::name(c) { + Some(name) => Ok(allocate_string(name.to_string(), vm.heap)), + None => match default_guard.into_inner() { + Some(default) => Ok(default), + None => Err(SimpleException::new_msg(ExcType::ValueError, "no such name").into()), + }, + } +} + +/// `unicodedata.lookup(name)` — the character with a given Unicode name. +/// +/// Raises `KeyError("undefined character name ''")` when no character has +/// that name. Unlike CPython, named sequences are not resolved. +fn uni_lookup(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("lookup", vm.heap)?; + defer_drop!(value, vm); + let name = value.to_str(vm)?; + match unicode_names2::character(name) { + Some(c) => Ok(allocate_string(c.to_string(), vm.heap)), + None => Err(SimpleException::new_msg(ExcType::KeyError, format!("undefined character name '{name}'")).into()), + } +} + +/// `unicodedata.combining(chr)` — the canonical combining class as an int. +/// +/// Returns `0` for characters with no combining class (the common case). +fn uni_combining(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("combining", vm.heap)?; + defer_drop!(value, vm); + let c = single_char(value, "combining", None, vm)?; + Ok(Value::Int(i64::from(canonical_combining_class(c)))) +} + +/// `unicodedata.normalize(form, unistr)` — normalize a string to NFC/NFD/NFKC/NFKD. +fn uni_normalize(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let NormalizeArgs { form, unistr } = NormalizeArgs::from_args(args, vm)?; + defer_drop!(form, vm); + defer_drop!(unistr, vm); + let form = NormForm::parse(form.as_str(vm))?; + normalize_with(form, unistr.as_str(vm), vm.heap) +} + +/// `unicodedata.is_normalized(form, unistr)` — whether a string is already normalized. +fn uni_is_normalized(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let IsNormalizedArgs { form, unistr } = IsNormalizedArgs::from_args(args, vm)?; + defer_drop!(form, vm); + defer_drop!(unistr, vm); + let normalized = match NormForm::parse(form.as_str(vm))? { + NormForm::Nfc => unicode_normalization::is_nfc(unistr.as_str(vm)), + NormForm::Nfd => unicode_normalization::is_nfd(unistr.as_str(vm)), + NormForm::Nfkc => unicode_normalization::is_nfkc(unistr.as_str(vm)), + NormForm::Nfkd => unicode_normalization::is_nfkd(unistr.as_str(vm)), + }; + Ok(Value::Bool(normalized)) +} + +/// Argument shape for `name(chr, default=..., /)`. +/// +/// Both arguments are positional-only (matching CPython's C signature). `chr` +/// stays a raw `Value` because it needs the bespoke single-character coercion +/// in [`single_char`] (CPython's "must be a unicode character" wording has no +/// `FromArgs` equivalent); `default` is any object returned verbatim when the +/// character has no name. `style = unpack` gives the `PyArg_UnpackTuple` arity +/// wording CPython uses here (`name expected at most 2 arguments, got 3`). +#[derive(FromArgs)] +#[from_args(name = "name", style = unpack, kwarg_error_name = "unicodedata.name")] +struct NameArgs { + #[from_args(pos_only)] + chr: Value, + #[from_args(pos_only, default)] + default: Option, +} + +/// Argument shape for `normalize(form, unistr, /)`. +/// +/// Both arguments are positional-only, zero-copy [`StrArg`]s: `bad_arg` gives +/// the exact `normalize() argument N must be str, not ` type error for +/// both. The form's *value* is validated by [`NormForm::parse`] in the body — +/// CPython type-checks every argument before rejecting an unknown form name, +/// so `normalize('XYZ', 123)` must raise the arg-2 `TypeError`, not the +/// `ValueError`. `style = unpack` (with min == max here) reproduces CPython's +/// `normalize expected 2 arguments, got N` arity error. +#[derive(FromArgs)] +#[from_args(name = "normalize", style = unpack, bad_arg, kwarg_error_name = "unicodedata.normalize")] +struct NormalizeArgs { + #[from_args(pos_only)] + form: StrArg, + #[from_args(pos_only)] + unistr: StrArg, +} + +/// Argument shape for `is_normalized(form, unistr, /)` — see [`NormalizeArgs`]. +#[derive(FromArgs)] +#[from_args(name = "is_normalized", style = unpack, bad_arg, kwarg_error_name = "unicodedata.is_normalized")] +struct IsNormalizedArgs { + #[from_args(pos_only)] + form: StrArg, + #[from_args(pos_only)] + unistr: StrArg, +} + +/// The four Unicode normalization forms accepted by `normalize`/`is_normalized`. +#[derive(Clone, Copy)] +enum NormForm { + Nfc, + Nfd, + Nfkc, + Nfkd, +} + +impl NormForm { + /// Maps a form name to its variant; unknown names raise CPython's + /// `ValueError: invalid normalization form`. Called from the function + /// body — after `FromArgs` has type-checked every argument — because + /// CPython validates the form's *value* only once binding succeeds. + fn parse(name: &str) -> RunResult { + match name { + "NFC" => Ok(Self::Nfc), + "NFD" => Ok(Self::Nfd), + "NFKC" => Ok(Self::Nfkc), + "NFKD" => Ok(Self::Nfkd), + _ => Err(SimpleException::new_msg(ExcType::ValueError, "invalid normalization form").into()), + } + } +} + +/// Normalizes `text` into a freshly allocated Python string. +/// +/// The output length is not bounded by the input (decomposition can expand a +/// single code point into several), so the result is built through +/// [`StringBuilder`] which preflights allocator-backed usage as it grows. +fn normalize_with(form: NormForm, text: &str, heap: &Heap) -> RunResult { + let mut builder = StringBuilder::new(&heap.tracker); + match form { + NormForm::Nfc => { + for c in text.nfc() { + builder.push(c)?; + } + } + NormForm::Nfd => { + for c in text.nfd() { + builder.push(c)?; + } + } + NormForm::Nfkc => { + for c in text.nfkc() { + builder.push(c)?; + } + } + NormForm::Nfkd => { + for c in text.nfkd() { + builder.push(c)?; + } + } + } + builder.finish(heap) +} + +/// Extracts a single `char` from a value that must be a one-character string. +/// +/// Matches CPython's two distinct error shapes: a non-`str` argument yields +/// `"() argument[ N] must be a unicode character, not "`, while a +/// string of the wrong length yields `"(): argument[ N] must be a unicode +/// character, not a string of length "`. `arg_num` supplies the ` N` suffix +/// (only `name()` numbers its argument). +fn single_char(value: &Value, fn_name: &str, arg_num: Option, vm: &VM<'_>) -> RunResult { + let arg_word = match arg_num { + Some(n) => format!("argument {n}"), + None => "argument".to_string(), + }; + if !value.is_str(vm.heap) { + return Err(ExcType::type_error(format!( + "{fn_name}() {arg_word} must be a unicode character, not {}", + value.py_type_name(vm) + ))); + } + let s = value.to_str(vm)?; + let mut chars = s.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) => Ok(c), + _ => Err(ExcType::type_error(format!( + "{fn_name}(): {arg_word} must be a unicode character, not a string of length {}", + s.chars().count() + ))), + } +} + +/// Maps a [`GeneralCategory`] to its two-letter Unicode abbreviation. +/// +/// These abbreviations are the values CPython's `unicodedata.category` returns. +fn category_abbrev(category: GeneralCategory) -> &'static str { + match category { + GeneralCategory::UppercaseLetter => "Lu", + GeneralCategory::LowercaseLetter => "Ll", + GeneralCategory::TitlecaseLetter => "Lt", + GeneralCategory::ModifierLetter => "Lm", + GeneralCategory::OtherLetter => "Lo", + GeneralCategory::NonspacingMark => "Mn", + GeneralCategory::SpacingMark => "Mc", + GeneralCategory::EnclosingMark => "Me", + GeneralCategory::DecimalNumber => "Nd", + GeneralCategory::LetterNumber => "Nl", + GeneralCategory::OtherNumber => "No", + GeneralCategory::ConnectorPunctuation => "Pc", + GeneralCategory::DashPunctuation => "Pd", + GeneralCategory::OpenPunctuation => "Ps", + GeneralCategory::ClosePunctuation => "Pe", + GeneralCategory::InitialPunctuation => "Pi", + GeneralCategory::FinalPunctuation => "Pf", + GeneralCategory::OtherPunctuation => "Po", + GeneralCategory::MathSymbol => "Sm", + GeneralCategory::CurrencySymbol => "Sc", + GeneralCategory::ModifierSymbol => "Sk", + GeneralCategory::OtherSymbol => "So", + GeneralCategory::SpaceSeparator => "Zs", + GeneralCategory::LineSeparator => "Zl", + GeneralCategory::ParagraphSeparator => "Zp", + GeneralCategory::Control => "Cc", + GeneralCategory::Format => "Cf", + GeneralCategory::Surrogate => "Cs", + GeneralCategory::PrivateUse => "Co", + GeneralCategory::Unassigned => "Cn", + // `GeneralCategory` is `#[non_exhaustive]`. Every category in the Unicode + // standard is enumerated above, so this arm is unreachable today; it only + // guards against the crate adding a variant in a future Unicode revision. + _ => "Cn", + } +} diff --git a/crates/bashkit-monty/src/name_map.rs b/crates/bashkit-monty/src/name_map.rs new file mode 100644 index 000000000..b040a5868 --- /dev/null +++ b/crates/bashkit-monty/src/name_map.rs @@ -0,0 +1,196 @@ +//! Ordered registry that maps namespace slots to interned names and vice versa. +//! +//! A `NameMap` is the single source of truth for a scope's name → slot +//! assignment. Slots are allocated sequentially as new names are seen +//! (`ensure_slot`), so the position in the registry IS the `NamespaceId` +//! that the compiler will encode into bytecode. The reverse direction +//! (`name_at`) gives the VM the `StringId` for a slot, which the runtime +//! uses to produce `NameError` / `UnboundLocalError` messages naming the +//! actual variable. +//! +//! Owning both directions in one structure is what fixes the historical +//! foot-gun where a scope kept a `name → slot` hashmap alongside a parallel +//! `namespace_size` counter: the two could drift, and there was no reverse +//! map at all — the VM used the wrong frame's `local_names` to label a +//! global-slot `NameError`. +//! +//! `NameMap` is keyed by [`StringId`] (the interner index), not `String`, +//! because every prepare-time site that allocates a slot already has the +//! `StringId` on hand from the AST. Avoiding `String::clone` per insert is +//! a measurable win for large modules. + +use ahash::AHashMap; + +use crate::{ + intern::StringId, + namespace::NamespaceId, + parse::{CodeRange, ParseError}, +}; + +/// Ordered map from interned names to namespace slots. +/// +/// Slots are dense and assigned in insertion order: the first inserted name +/// gets slot `0`, the second slot `1`, and so on. This means +/// `name_at(slot)` is a `Vec` index lookup and `len()` equals the next slot +/// that would be allocated — there is no separate `namespace_size` +/// counter to keep in sync. +/// +/// Used for module globals, function locals, and any other scope that +/// needs a stable string → bytecode-slot mapping. +/// +/// # Serialization +/// +/// Only `slots` is serialized; `by_name` is reconstructed on deserialization +/// (see [`NameMapWire`]) rather than storing both directions. +#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] +#[serde(into = "NameMapWire", from = "NameMapWire")] +pub(crate) struct NameMap { + /// Name interned at each slot, indexed by `NamespaceId::index()`. + slots: Vec, + /// Reverse lookup so `ensure_slot` is O(1). + by_name: AHashMap, +} + +/// Serialized slots from which both directions of a [`NameMap`] are reconstructed. +#[derive(serde::Serialize, serde::Deserialize)] +struct NameMapWire { + slots: Vec, +} + +impl From for NameMapWire { + fn from(map: NameMap) -> Self { + Self { slots: map.slots } + } +} + +impl From for NameMap { + fn from(wire: NameMapWire) -> Self { + let mut by_name = AHashMap::with_capacity(wire.slots.len()); + for (idx, &name_id) in wire.slots.iter().enumerate() { + let slot = NamespaceId::new(idx).expect("namespace slot exceeds u16"); + // First occurrence wins, matching the live `ensure_slot` / + // `push_aliased_slot` invariant where a function parameter + // shadows any later cell/free-var slot that reuses its + // `StringId`. + by_name.entry(name_id).or_insert(slot); + } + Self { + slots: wire.slots, + by_name, + } + } +} + +impl NameMap { + /// Returns an empty `NameMap` with no slots allocated. + pub fn new() -> Self { + Self::default() + } + + /// Returns an empty `NameMap` with capacity reserved for `cap` slots. + pub fn with_capacity(cap: usize) -> Self { + Self { + slots: Vec::with_capacity(cap), + by_name: AHashMap::with_capacity(cap), + } + } + + /// Number of slots currently allocated. + /// + /// This is the size of the namespace and the slot id that `ensure_slot` + /// would assign to the next inserted name. + pub fn len(&self) -> usize { + self.slots.len() + } + + /// Returns the slot already allocated for `name_id`, if any. + pub fn get(&self, name_id: StringId) -> Option { + self.by_name.get(&name_id).copied() + } + + /// Returns `true` if a slot has been allocated for `name_id`. + pub fn contains(&self, name_id: StringId) -> bool { + self.by_name.contains_key(&name_id) + } + + /// Returns the slot for `name_id`, allocating a new one if absent. + /// + /// `position` is used to anchor the `SyntaxError` raised when the scope + /// would grow past the `u16` slot-index limit (`u16::MAX + 1` slots). + /// Allocation is idempotent: calling `ensure_slot` twice with the same + /// `name_id` returns the same slot. + pub fn ensure_slot(&mut self, name_id: StringId, position: CodeRange) -> Result { + if let Some(&id) = self.by_name.get(&name_id) { + return Ok(id); + } + let id = NamespaceId::new(self.slots.len()).ok_or_else(|| namespace_overflow(position))?; + self.slots.push(name_id); + self.by_name.insert(name_id, id); + Ok(id) + } + + /// Allocates a fresh slot whose reverse-map entry is `name_id`, WITHOUT + /// touching the forward `name → slot` map. + /// + /// Used to back cell variables and free variables, which need a slot in + /// the function's namespace distinct from any same-named parameter slot. + /// For example, `def f(n): return lambda x: x + n` makes `n` both a + /// parameter (slot 0) AND a cell variable (a fresh slot) — at call + /// time the runtime copies `n`'s parameter value into the cell so the + /// returned lambda's closure refers to the cell, not the now-gone stack + /// slot. + /// + /// The slot's name is recorded in the reverse direction (slot → + /// `name_id`) so the VM can label a `NameError` raised against the cell. + /// The forward direction keeps the parameter as the canonical owner so + /// `get(name_id)` still resolves to the param slot. + pub fn push_aliased_slot(&mut self, name_id: StringId, position: CodeRange) -> Result { + let id = NamespaceId::new(self.slots.len()).ok_or_else(|| namespace_overflow(position))?; + self.slots.push(name_id); + Ok(id) + } + + /// Drops every slot at index `len` or above, undoing allocations made since + /// the map had `len` slots. + /// + /// Lets the REPL roll back the names a rejected snippet appended so they + /// don't count against the `u16` slot limit. Names whose canonical slot is + /// below `len` (aliased slots) keep their forward mapping. + pub fn truncate(&mut self, len: usize) { + for name_id in self.slots.drain(len..) { + if self.by_name.get(&name_id).is_some_and(|slot| slot.index() >= len) { + self.by_name.remove(&name_id); + } + } + } + + /// The name at every slot, indexed by `NamespaceId::index()`. + pub fn names(&self) -> &[StringId] { + &self.slots + } + + /// Iterates over `(slot, name)` pairs in slot order. + pub fn iter(&self) -> impl ExactSizeIterator + '_ { + self.slots.iter().enumerate().map(|(i, &name)| { + // `i < slots.len() ≤ u16::MAX + 1` because every push went + // through `ensure_slot`, which checks the `u16` overflow. + let slot = NamespaceId::new(i).expect("slot index fits in NamespaceId by construction"); + (slot, name) + }) + } +} + +/// Builds the `ParseError` raised when a scope's namespace would exceed +/// `NamespaceId`'s `u16` capacity (the bytecode slot operand width). +/// Hoisted so the cold error path stays out of inlined allocator calls. +#[cold] +#[inline(never)] +pub(crate) fn namespace_overflow(position: CodeRange) -> ParseError { + ParseError::syntax( + format!( + "too many distinct names in scope; maximum is {} per scope", + (u16::MAX as usize) + 1 + ), + position, + ) +} diff --git a/crates/bashkit-monty/src/namespace.rs b/crates/bashkit-monty/src/namespace.rs new file mode 100644 index 000000000..0531e75d4 --- /dev/null +++ b/crates/bashkit-monty/src/namespace.rs @@ -0,0 +1,33 @@ +/// Unique identifier for variable slots in namespaces (globals and function locals). +/// +/// Used by the bytecode compiler to emit slot indices for variable access. +/// The VM uses these indices to read/write values in the globals vector +/// or the stack-inlined locals region. +/// +/// Storage is `u16` because every bytecode opcode that takes a namespace +/// slot (`LoadLocal`, `LoadGlobal`, `StoreLocal`, …) encodes the slot in +/// 16 bits. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +pub(crate) struct NamespaceId(u16); + +impl NamespaceId { + /// Creates a `NamespaceId` from a `usize` slot index, returning `None` if + /// the index doesn't fit in `u16`. Callers in the prepare phase wrap the + /// `None` case in a `ParseError::Syntax` so user-input-driven overflows + /// surface as a clean `SyntaxError` rather than a panic at emission time. + pub fn new(index: usize) -> Option { + u16::try_from(index).ok().map(Self) + } + + /// Returns the slot index as the `u16` operand consumed by the bytecode. + #[inline] + pub fn as_u16(self) -> u16 { + self.0 + } + + /// Returns the slot as `usize` for `Vec`/array indexing in the VM. + #[inline] + pub fn index(self) -> usize { + self.0.into() + } +} diff --git a/crates/bashkit-monty/src/object_bridge.rs b/crates/bashkit-monty/src/object_bridge.rs new file mode 100644 index 000000000..36faf8cae --- /dev/null +++ b/crates/bashkit-monty/src/object_bridge.rs @@ -0,0 +1,1161 @@ +//! Interpreter-side bridge for the boundary value types in `monty-types`: +//! export of VM `Value`s into a [`MontyGraph`] arena, import of an arena +//! back into heap values, and the [`MontyType`] ↔ [`Type`] mirror. The +//! types themselves (and their pure methods) are defined in `monty-types`. +//! +//! Export memoizes heap objects per message, so a sub-object reachable twice +//! is one node referenced twice and the arena is O(heap objects) rather than +//! O(paths). Import is one forward pass because a node's children precede it. + +use std::mem; + +use ahash::{AHashMap, AHashSet}; +use monty_types::{ + CallArgs, InvalidInputError, MontyComplex, MontyDate, MontyDateTime, MontyFileHandle, MontyObject, MontyTime, + MontyTimeDelta, MontyTimeZone, MontyType, MontyUuid, + unstable::{self, ClassTypeNode, MontyGraph, MontyNode, NodeId}, +}; + +use crate::{ + builtins::Builtins, + bytecode::VM, + defer_drop, + exception_private::{RunError, SimpleException}, + heap::{DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapReadOutput}, + modules::dataclasses, + types::{ + Complex, HostClass, HostClassType, LongInt, Module, NamedTuple, OpenFile, Path, PyTrait, TimeZone, Type, + allocate_tuple, + bytes::Bytes, + date as date_type, datetime as datetime_type, decimal as decimal_type, + decimal::py as py_decimal, + dict::Dict, + instance::class_name, + list::List, + set::{FrozenSet, Set}, + str::allocate_string, + time as time_type, timedelta as timedelta_type, + }, + value::{EitherStr, Value}, +}; + +/// Crate-internal conversions between a single [`MontyObject`] and a VM `Value`. +/// +/// `MontyObject` is defined in `monty-types`; building one from a heap `Value` +/// (and back) requires the VM, so the conversions stay here as a `pub(crate)` +/// extension trait. Multi-value messages use [`GraphExporter`] and +/// [`MontyGraphExt::to_values`] directly so their values share one arena. +pub(crate) trait MontyObjectExt: Sized { + /// Exports a `Value` into its own arena, taking ownership of the `Value` + /// and dropping it via `drop_with`. + fn export(value: Value, vm: &mut VM<'_>) -> Self; + + /// Imports this value into the heap. Fails with `InvalidInputError` on + /// output-only nodes (`Repr`, `Cycle`), on a sandbox class or instance + /// whose sandbox object no longer exists, and on malformed input; a + /// memory overshoot is caught at the next soft-limit checkpoint, not here. + fn to_value(self, vm: &mut VM<'_>) -> Result; +} + +impl MontyObjectExt for MontyObject { + fn export(value: Value, vm: &mut VM<'_>) -> Self { + let mut exporter = GraphExporter::new(); + let root = exporter.push_owned(value, vm); + unstable::object_from_graph(exporter.finish(vm), root).expect("exported root is valid") + } + + fn to_value(self, vm: &mut VM<'_>) -> Result { + let (graph, root) = unstable::into_graph_parts(self); + let mut values = graph.to_values(vm)?; + // `None` is an immediate, so swapping it in leaves nothing to release. + let root = mem::replace(&mut values[root.index()], Value::None); + values.drop_with(vm); + Ok(root) + } +} + +/// Crate-internal import of a whole arena. +pub(crate) trait MontyGraphExt { + /// Imports every node into the heap, in order, returning one owned + /// `Value` per node (so a root is `values[id.index()]`). The caller owns + /// the vector and must `drop_with` it. Fails as + /// [`MontyObjectExt::to_value`] does, releasing everything built so far. + fn to_values(self, vm: &mut VM<'_>) -> Result, InvalidInputError>; +} + +impl MontyGraphExt for MontyGraph { + fn to_values(self, vm: &mut VM<'_>) -> Result, InvalidInputError> { + let nodes = self.into_nodes(); + // A host-defined class node imports as a type object; a `ClassInstance` + // of it needs the node's data to build a `HostClass`, so keep it by id. + let host_classes: AHashMap> = nodes + .iter() + .enumerate() + .filter_map(|(index, node)| match node { + MontyNode::ClassType(class) if class.host_defined => { + Some((NodeId(u32::try_from(index).expect("arena ids fit u32")), class.clone())) + } + _ => None, + }) + .collect(); + let mut guard = DropGuard::new(Vec::with_capacity(nodes.len()), vm); + let (values, vm) = guard.as_parts_mut(); + for node in nodes { + let value = import_node(node, values, &host_classes, vm)?; + values.push(value); + } + Ok(guard.into_inner()) + } +} + +/// Builds the arena for one outgoing message: the final value, or every +/// argument of a call. One exporter per message is what lets an object +/// reachable from two arguments cross once. +pub(crate) struct GraphExporter { + /// The arena under construction. + graph: MontyGraph, + /// The node of every finished heap object, reused on a second reference. + memo: AHashMap, + /// Objects on the current descent; a reference back to one becomes a + /// [`MontyNode::Cycle`] leaf rather than infinite recursion. + in_progress: AHashSet, + /// A reference to every memoized object, released by [`finish`](Self::finish): + /// a user `__repr__` run by [`repr_node`] can free an exported object + /// mid-message, and a new object in the reused slot would inherit its node. + pinned: Vec, +} + +impl GraphExporter { + pub(crate) fn new() -> Self { + Self { + graph: MontyGraph::new(), + memo: AHashMap::new(), + in_progress: AHashSet::new(), + pinned: Vec::new(), + } + } + + /// Exports an owned value, dropping it, and returns its node. + pub(crate) fn push_owned(&mut self, value: Value, vm: &mut VM<'_>) -> NodeId { + let id = self.push(&value, vm); + value.drop_with(vm); + id + } + + /// Appends a node the caller built; nothing is memoized. + pub(crate) fn push_node(&mut self, node: MontyNode) -> NodeId { + self.graph.push(node) + } + + /// The finished arena, releasing the pins on the memoized objects. + pub(crate) fn finish(self, vm: &mut VM<'_>) -> MontyGraph { + self.pinned.drop_with(vm); + self.graph + } + + /// Records `id`'s node in the memo and pins the object until `finish`. + fn memoize(&mut self, id: HeapId, node_id: NodeId, vm: &VM<'_>) { + vm.heap.inc_ref(id); + self.pinned.push(Value::Ref(id)); + self.memo.insert(id, node_id); + } + + /// Exports a borrowed value and returns its node. Non-`Ref` values need + /// only the interner; heap objects go through [`push_ref`](Self::push_ref). + pub(crate) fn push(&mut self, value: &Value, vm: &mut VM<'_>) -> NodeId { + // Check depth limit before processing + let Ok(mut guard) = vm.recursion_guard() else { + return self.push_node(MontyNode::Repr("".to_owned())); + }; + let vm = &mut *guard; + + let interns = vm.interns; + let node = match value { + Value::Undefined => panic!("Undefined found while exporting a value"), + Value::Ellipsis => MontyNode::Ellipsis, + Value::NotImplemented => MontyNode::NotImplemented, + Value::None => MontyNode::None, + Value::Bool(b) => MontyNode::Bool(*b), + Value::Int(i) => MontyNode::Int(*i), + Value::Float(f) => MontyNode::Float(*f), + Value::InternString(string_id) => MontyNode::String(interns.get_str(*string_id).to_owned()), + Value::InternBytes(bytes_id) => MontyNode::Bytes(interns.get_bytes(*bytes_id).to_owned()), + Value::InternLongInt(li_id) => MontyNode::BigInt(interns.get_long_int(*li_id).clone()), + Value::Ref(id) => return self.push_ref(*id, value, vm), + Value::Builtin(Builtins::Type(Type::Instance(class_id))) => return self.sandbox_class_node(*class_id, vm), + Value::Builtin(Builtins::Type(t)) => match MontyType::from_internal_static(*t) { + Some(ty) => MontyNode::Type(ty), + None => repr_node(value, vm), + }, + Value::Builtin(Builtins::ExcType(e)) => MontyNode::Type(MontyType::Exception(*e)), + Value::Builtin(Builtins::Function(f)) => MontyNode::BuiltinFunction(*f), + #[cfg(feature = "memory-model-checks")] + Value::Dereferenced => panic!("Dereferenced found while exporting a value"), + _ => repr_node(value, vm), + }; + self.push_node(node) + } + + /// Exports a heap object through the memo: a finished object is reused, one + /// still being exported is a cycle, anything else is converted then recorded. + /// `vm.heap.read(id)` yields a `HeapRead` that keeps the entry alive without + /// borrowing `vm.heap`, so the conversion can recurse. + fn push_ref(&mut self, id: HeapId, value: &Value, vm: &mut VM<'_>) -> NodeId { + if let Some(node_id) = self.memo.get(&id) { + return *node_id; + } + // A host class's type object *is* its shared class node. + if matches!(vm.heap.get(id), HeapData::HostClassType(_)) { + return self.host_class_node(id, vm); + } + if self.in_progress.contains(&id) { + let placeholder = match vm.heap.get(id) { + // A deque exports as a list, so it takes a list's placeholder + // (as its repr does too). + HeapData::List(_) | HeapData::Deque(_) => "[...]", + HeapData::Tuple(_) | HeapData::NamedTuple(_) => "(...)", + HeapData::Dict(_) => "{...}", + _ => "...", + }; + return self.push_node(MontyNode::Cycle(placeholder.to_owned())); + } + self.in_progress.insert(id); + let node_id = match vm.heap.read(id) { + // Cells are internal closure implementation details — export the + // contents directly without a wrapper node. + HeapReadOutput::Cell(cell) => { + let inner = cell.get(vm.heap).0.clone_with_heap(vm.heap); + defer_drop!(inner, vm); + self.push(inner, vm) + } + output => { + let node = self.convert_heap_object(id, output, value, vm); + self.push_node(node) + } + }; + self.in_progress.remove(&id); + self.memoize(id, node_id, vm); + node_id + } + + /// Converts one heap object into its node, pushing container children first. + /// Recursing can run a user `__repr__` ([`repr_node`] on e.g. a + /// `functools.partial` bound to an instance), so mutable containers clone + /// every child before recursing: the clones keep the children alive and the + /// iteration valid if that `__repr__` mutates the container. Immutable + /// containers (tuple, namedtuple, frozenset) cannot change length, so they + /// clone per item. + fn convert_heap_object<'h>( + &mut self, + id: HeapId, + output: HeapReadOutput<'h>, + value: &Value, + vm: &mut VM<'h>, + ) -> MontyNode { + match output { + HeapReadOutput::Str(s) => MontyNode::String(s.get(vm.heap).as_str().to_owned()), + HeapReadOutput::Bytes(b) => MontyNode::Bytes(b.get(vm.heap).as_slice().to_owned()), + HeapReadOutput::List(list) => { + // Snapshot before recursing: a nested `__repr__` may mutate this list. + let children: Vec = list + .get(vm.heap) + .as_slice() + .iter() + .map(|item| item.clone_with_heap(vm.heap)) + .collect(); + defer_drop!(children, vm); + MontyNode::List(self.push_all(children, vm)) + } + // A deque exports as a host list: there is no host-side deque + // *value* type, so it degrades to the nearest structural one + // rather than to a repr string, matching how defaultdict and + // Counter degrade to `dict`. `maxlen` does not survive, and the + // host cannot round-trip it back into a deque. + HeapReadOutput::Deque(deque) => { + // Snapshot before recursing: a deque is mutable, so a nested + // `__repr__` may shorten it and invalidate index-based access. + let children: Vec = deque + .get(vm.heap) + .iter() + .map(|item| item.clone_with_heap(vm.heap)) + .collect(); + defer_drop!(children, vm); + MontyNode::List(self.push_all(children, vm)) + } + HeapReadOutput::Tuple(tuple) => { + let len = tuple.get(vm.heap).as_slice().len(); + let mut items = Vec::with_capacity(len); + for i in 0..len { + let item = tuple.get(vm.heap).as_slice()[i].clone_with_heap(vm.heap); + defer_drop!(item, vm); + items.push(self.push(item, vm)); + } + MontyNode::Tuple(items) + } + HeapReadOutput::NamedTuple(nt) => { + let type_name = nt.get(vm.heap).name(vm.interns).to_owned(); + let field_names = nt + .get(vm.heap) + .field_names() + .iter() + .map(|fname| fname.as_str(vm.interns).to_owned()) + .collect::>(); + let len = nt.get(vm.heap).len(); + let mut values = Vec::with_capacity(len); + for i in 0..len { + let item = nt.get(vm.heap).as_vec()[i].clone_with_heap(vm.heap); + defer_drop!(item, vm); + values.push(self.push(item, vm)); + } + MontyNode::NamedTuple { + type_name, + field_names, + values, + } + } + HeapReadOutput::Dict(dict) => { + // Snapshot before recursing: a nested `__repr__` may mutate this dict. + let children = snapshot_dict_pairs(dict.get(vm.heap), vm.heap); + defer_drop!(children, vm); + MontyNode::Dict(self.push_pairs(children, vm)) + } + HeapReadOutput::Set(set) => { + // Snapshot before recursing: a nested `__repr__` may mutate this set. + let children: Vec = { + let set_ref = set.get(vm.heap); + set_ref.iter().map(|v| v.clone_with_heap(vm.heap)).collect() + }; + defer_drop!(children, vm); + MontyNode::Set(self.push_all(children, vm)) + } + HeapReadOutput::FrozenSet(fs) => { + // Snapshot like the set branch, so the walk never holds a position. + let children: Vec = { + let storage = fs.get(vm.heap).storage(); + storage.iter().map(|v| v.clone_with_heap(vm.heap)).collect() + }; + defer_drop!(children, vm); + MontyNode::FrozenSet(self.push_all(children, vm)) + } + HeapReadOutput::Cell(_) | HeapReadOutput::HostClassType(_) => { + unreachable!("cells and host class types are routed by push_ref") + } + HeapReadOutput::Date(d) => { + let (year, month, day) = date_type::to_ymd(*d.get(vm.heap)); + MontyNode::Date(MontyDate { + year, + month: u8::try_from(month).expect("month is always 1..=12"), + day: u8::try_from(day).expect("day is always 1..=31"), + }) + } + HeapReadOutput::DateTime(dt) => match datetime_type::to_monty_datetime(dt.get(vm.heap)) { + Some(datetime) => MontyNode::DateTime(datetime), + None => repr_node(value, vm), + }, + HeapReadOutput::Time(t) => { + let time = t.get(vm.heap); + let (hour, minute, second, microsecond, fold) = time.to_components(); + let tz = time_type::attached_timezone(time, vm.heap); + MontyNode::Time(MontyTime { + hour, + minute, + second, + microsecond, + offset_seconds: tz.as_ref().map(|tz| tz.offset_seconds), + timezone_name: tz.and_then(|tz| tz.name), + fold, + }) + } + HeapReadOutput::TimeDelta(td) => { + let (days, seconds, microseconds) = timedelta_type::components(td.get(vm.heap)); + MontyNode::TimeDelta(MontyTimeDelta { + days, + seconds, + microseconds, + }) + } + // The canonical string, with an upper-case exponent whatever the context's + // `capitals`, so the host parses back the exact value. + HeapReadOutput::Decimal(d) => MontyNode::Decimal(d.get(vm.heap).to_sci_string(false, true)), + HeapReadOutput::TimeZone(tz) => { + let tz_ref = tz.get(vm.heap); + MontyNode::TimeZone(MontyTimeZone { + offset_seconds: tz_ref.offset_seconds, + name: tz_ref.name.clone(), + }) + } + HeapReadOutput::Exception(exc) => { + let exc_ref = exc.get(vm.heap); + MontyNode::Exception { + exc_type: exc_ref.exc_type(), + arg: exc_ref.arg().map(ToString::to_string), + } + } + HeapReadOutput::HostClass(hc) => { + let (class_id, instance_id) = { + let hc_ref = hc.get(vm.heap); + (hc_ref.class_id(), hc_ref.instance_id()) + }; + let class_type = self.host_class_node(class_id, vm); + // Snapshot before recursing: attrs are mutable via `setattr`. + let children = snapshot_dict_pairs(hc.get(vm.heap).attrs(), vm.heap); + defer_drop!(children, vm); + MontyNode::ClassInstance { + class_type, + instance_id, + attrs: self.push_pairs(children, vm), + } + } + // Sandbox-defined class instances cross out structured rather + // than as a repr string, so hosts get name + attrs + dataclass-ness, + // plus worker-generated uuids (stored on the heap objects, so + // stable across crossings and dump/restore). + HeapReadOutput::Instance(inst) => { + let class_id = inst.get(vm.heap).class(); + let instance_id = vm.heap.boundary_uuid(id); + let class_type = self.sandbox_class_node(class_id, vm); + // Snapshot before recursing: attrs are mutable via `setattr`. + let children = snapshot_dict_pairs(inst.get(vm.heap).attrs(), vm.heap); + defer_drop!(children, vm); + MontyNode::ClassInstance { + class_type, + instance_id, + attrs: self.push_pairs(children, vm), + } + } + // Iterators are internal objects — represent as a fixed type + // string rather than recursing. + HeapReadOutput::ListIterator(_) => MontyNode::Repr("".to_owned()), + HeapReadOutput::TupleIterator(_) => MontyNode::Repr("".to_owned()), + HeapReadOutput::StringIterator(iter) => { + MontyNode::Repr(format!("<{} object>", iter.py_type(vm).name(vm.heap, vm.interns))) + } + HeapReadOutput::BytesIterator(_) => MontyNode::Repr("".to_owned()), + HeapReadOutput::RangeIterator(_) => MontyNode::Repr("".to_owned()), + HeapReadOutput::DictKeyIterator(_) => MontyNode::Repr("".to_owned()), + HeapReadOutput::DictItemIterator(_) => MontyNode::Repr("".to_owned()), + HeapReadOutput::DictValueIterator(_) => MontyNode::Repr("".to_owned()), + HeapReadOutput::SetIterator(_) => MontyNode::Repr("".to_owned()), + HeapReadOutput::CallableIterator(_) => MontyNode::Repr("".to_owned()), + HeapReadOutput::DirScan(scan) => MontyNode::Repr(scan.get(vm.heap).boundary_repr()), + // A placeholder despite the real in-sandbox repr (`count(0)`), + // which would recurse into `repeat`'s arbitrary object. + HeapReadOutput::Itertools(iter) => { + MontyNode::Repr(format!("<{} object>", iter.py_type(vm).name(vm.heap, vm.interns))) + } + HeapReadOutput::LongInt(li) => MontyNode::BigInt(li.get(vm.heap).inner().clone()), + HeapReadOutput::Complex(c) => { + let c = c.get(vm.heap); + MontyNode::Complex(MontyComplex { + real: c.real, + imag: c.imag, + }) + } + // A host module crosses back with its id and attrs; a bundled one + // has no host identity and crosses as its repr. + HeapReadOutput::Module(m) => match m.get(vm.heap).id() { + Some(id) => { + let name = m.get(vm.heap).name_str(vm.interns).to_owned(); + let children = snapshot_dict_pairs(m.get(vm.heap).attrs(), vm.heap); + defer_drop!(children, vm); + MontyNode::Module { + name, + id, + attrs: self.push_pairs(children, vm), + } + } + None => MontyNode::Repr(format!("", m.get(vm.heap).name_str(vm.interns))), + }, + HeapReadOutput::Coroutine(coro) => { + let func_id = coro.get(vm.heap).func_id; + let func = vm.interns.get_function(func_id); + let name = vm.interns.get_str(func.name.name_id); + MontyNode::Repr(format!("")) + } + HeapReadOutput::GatherFuture(gather) => { + MontyNode::Repr(format!("", gather.get(vm.heap).item_count())) + } + HeapReadOutput::Path(path) => MontyNode::Path(path.get(vm.heap).as_str().to_owned()), + // File objects carry no heap refs (leaf type) — no recursion. + // This is how `file.read()`/`write()` deliver the open file + // to the host as the first OS-call argument. + HeapReadOutput::OpenFile(file) => { + let file = file.get(vm.heap); + MontyNode::FileHandle(MontyFileHandle { + path: file.path().to_owned(), + mode: *file.file_mode(), + position: file.position(), + }) + } + HeapReadOutput::ExtFunction(function) => MontyNode::Function { + name: function.get(vm.heap).as_str().to_owned(), + docstring: None, + }, + _ => repr_node(value, vm), + } + } + + /// The class node of a sandbox-defined class, generating and storing its + /// boundary uuid on first crossing so repeated crossings (and dump/restore) + /// observe the same id. Sandbox classes never send attrs, so the node has + /// no children and is memoized by `class_id`. + /// + /// # Panics + /// If `class_id` does not refer to a `Class` heap entry — every producer of a + /// class id guarantees it does, so this is a programmer-error tripwire. + fn sandbox_class_node(&mut self, class_id: HeapId, vm: &mut VM<'_>) -> NodeId { + if let Some(node_id) = self.memo.get(&class_id) { + return *node_id; + } + let node = MontyNode::ClassType(Box::new(ClassTypeNode { + name: class_name(class_id, vm.heap, vm.interns).into_owned(), + id: vm.heap.boundary_uuid(class_id), + host_defined: false, + is_dataclass: dataclasses::is_dataclass_class(class_id, vm), + attrs: Vec::new(), + })); + let node_id = self.push_node(node); + self.memoize(class_id, node_id, vm); + node_id + } + + /// The class node of a host-defined class (`type_id` is its `HostClassType` + /// entry), with its eager class attrs so an echoed type round-trips. + /// Memoized so every instance of the class and the type object itself share + /// one node; a class reached again while its own attrs are still being + /// exported gets an attr-less duplicate, since a `ClassInstance` must point + /// at a class node, never a `Cycle` leaf. + fn host_class_node(&mut self, type_id: HeapId, vm: &mut VM<'_>) -> NodeId { + if let Some(node_id) = self.memo.get(&type_id) { + return *node_id; + } + let HeapReadOutput::HostClassType(ty) = vm.heap.read(type_id) else { + unreachable!("host class ids always point at a HostClassType entry"); + }; + let class_type = ty.get(vm.heap).class_type(vm.interns); + let attrs = if self.in_progress.insert(type_id) { + let children = snapshot_dict_pairs(ty.get(vm.heap).attrs(), vm.heap); + defer_drop!(children, vm); + let attrs = self.push_pairs(children, vm); + self.in_progress.remove(&type_id); + attrs + } else { + Vec::new() + }; + let node_id = self.push_node(MontyNode::ClassType(Box::new(ClassTypeNode { + name: class_type.name, + id: class_type.id, + host_defined: true, + is_dataclass: class_type.is_dataclass, + attrs, + }))); + if !self.in_progress.contains(&type_id) { + self.memoize(type_id, node_id, vm); + } + node_id + } + + /// Exports a snapshot of container children, cloned and guarded by the + /// caller (see [`convert_heap_object`](Self::convert_heap_object)). + fn push_all(&mut self, children: &[Value], vm: &mut VM<'_>) -> Vec { + children.iter().map(|child| self.push(child, vm)).collect() + } + + /// Exports a guarded snapshot of dict entries — the pair-wise counterpart + /// of [`push_all`](Self::push_all). + fn push_pairs(&mut self, children: &[(Value, Value)], vm: &mut VM<'_>) -> Vec<(NodeId, NodeId)> { + children + .iter() + .map(|(key, value)| { + let key = self.push(key, vm); + let value = self.push(value, vm); + (key, value) + }) + .collect() + } +} + +/// Crate-internal export of call arguments: one arena for every argument. +pub(crate) trait CallArgsExt { + /// Appends an owned positional argument. + fn export_arg(&mut self, exporter: &mut GraphExporter, value: Value, vm: &mut VM<'_>); + /// Appends an owned keyword argument. + fn export_kwarg(&mut self, exporter: &mut GraphExporter, key: Value, value: Value, vm: &mut VM<'_>); +} + +impl CallArgsExt for CallArgs { + fn export_arg(&mut self, exporter: &mut GraphExporter, value: Value, vm: &mut VM<'_>) { + let id = exporter.push_owned(value, vm); + unstable::call_args_parts_mut(self).1.push(id); + } + + fn export_kwarg(&mut self, exporter: &mut GraphExporter, key: Value, value: Value, vm: &mut VM<'_>) { + let key = exporter.push_owned(key, vm); + let value = exporter.push_owned(value, vm); + unstable::call_args_parts_mut(self).2.push((key, value)); + } +} + +/// Crate-internal bridge between [`MontyType`] and the runtime [`Type`]. +/// +/// `MontyType` lives in `monty-types` (it is pure data), but mapping it to and +/// from the runtime `Type` needs heap/intern access, so the conversions stay +/// here as a `pub(crate)` extension trait. +pub(crate) trait MontyTypeExt: Sized { + fn to_internal(&self) -> Type; + + fn from_internal_static(ty: Type) -> Option; +} + +impl MontyTypeExt for MontyType { + /// The internal runtime [`Type`] this variant mirrors. Every variant has + /// one: a class is never a `MontyType` (it crosses as a `ClassType` node), + /// so a `Type` leaf always names a builtin. + /// + /// Keep in lockstep with [`from_internal_static`](Self::from_internal_static); + /// both matches are exhaustive so the compiler enforces totality. + fn to_internal(&self) -> Type { + match self { + Self::Ellipsis => Type::Ellipsis, + Self::NotImplementedType => Type::NotImplementedType, + Self::Type => Type::Type, + Self::NoneType => Type::NoneType, + Self::Bool => Type::Bool, + Self::Int => Type::Int, + Self::Float => Type::Float, + Self::Complex => Type::Complex, + Self::Range => Type::Range, + Self::Slice => Type::Slice, + Self::Date => Type::Date, + Self::DateTime => Type::DateTime, + Self::Time => Type::Time, + Self::TimeDelta => Type::TimeDelta, + Self::TimeZone => Type::TimeZone, + Self::Str => Type::Str, + Self::Bytes => Type::Bytes, + Self::List => Type::List, + Self::Deque => Type::Deque, + Self::ListIterator => Type::ListIterator, + Self::TupleIterator => Type::TupleIterator, + Self::StrAsciiIterator => Type::StrAsciiIterator, + Self::StrIterator => Type::StrIterator, + Self::BytesIterator => Type::BytesIterator, + Self::RangeIterator => Type::RangeIterator, + Self::DictKeyIterator => Type::DictKeyIterator, + Self::DictItemIterator => Type::DictItemIterator, + Self::DictValueIterator => Type::DictValueIterator, + Self::SetIterator => Type::SetIterator, + Self::CallableIterator => Type::CallableIterator, + Self::ItertoolsPairwise => Type::ItertoolsPairwise, + Self::ItertoolsCompress => Type::ItertoolsCompress, + Self::ItertoolsIslice => Type::ItertoolsIslice, + Self::ItertoolsChain => Type::ItertoolsChain, + Self::ItertoolsCycle => Type::ItertoolsCycle, + Self::ItertoolsTakeWhile => Type::ItertoolsTakeWhile, + Self::ItertoolsDropWhile => Type::ItertoolsDropWhile, + Self::ItertoolsFilterFalse => Type::ItertoolsFilterFalse, + Self::ItertoolsStarMap => Type::ItertoolsStarMap, + Self::ItertoolsAccumulate => Type::ItertoolsAccumulate, + Self::ItertoolsBatched => Type::ItertoolsBatched, + Self::ItertoolsZipLongest => Type::ItertoolsZipLongest, + Self::ItertoolsCombinations => Type::ItertoolsCombinations, + Self::ItertoolsCombinationsWithReplacement => Type::ItertoolsCombinationsWithReplacement, + Self::ItertoolsPermutations => Type::ItertoolsPermutations, + Self::ItertoolsProduct => Type::ItertoolsProduct, + Self::ItertoolsGroupBy => Type::ItertoolsGroupBy, + Self::ItertoolsGrouper => Type::ItertoolsGrouper, + Self::ItertoolsTee => Type::ItertoolsTee, + Self::ItertoolsTeeDataObject => Type::ItertoolsTeeDataObject, + Self::ItertoolsCount => Type::ItertoolsCount, + Self::ItertoolsRepeat => Type::ItertoolsRepeat, + Self::Partial => Type::Partial, + Self::GenericAlias => Type::GenericAlias, + Self::Union => Type::Union, + Self::LruCacheWrapper => Type::LruCacheWrapper, + Self::Tuple => Type::Tuple, + Self::NamedTuple => Type::NamedTuple, + Self::Dict => Type::Dict, + Self::DictKeys => Type::DictKeys, + Self::DictItems => Type::DictItems, + Self::DictValues => Type::DictValues, + Self::Set => Type::Set, + Self::FrozenSet => Type::FrozenSet, + Self::Exception(exc_type) => Type::Exception(*exc_type), + Self::Function => Type::Function, + Self::BuiltinFunction => Type::BuiltinFunction, + Self::Cell => Type::Cell, + Self::Iterator => Type::Iterator, + Self::Coroutine => Type::Coroutine, + Self::Module => Type::Module, + Self::TextIOWrapper => Type::TextIOWrapper, + Self::BufferedReader => Type::BufferedReader, + Self::BufferedWriter => Type::BufferedWriter, + Self::BufferedRandom => Type::BufferedRandom, + Self::SpecialForm => Type::SpecialForm, + Self::Path => Type::Path, + Self::Property => Type::Property, + Self::Object => Type::Object, + Self::RePattern => Type::RePattern, + Self::ReMatch => Type::ReMatch, + Self::Field => Type::DataclassField, + Self::DataclassParams => Type::DataclassParams, + Self::Decimal => Type::Decimal, + } + } + + /// Mirrors a runtime [`Type`] without heap access; a type with no boundary + /// form returns `None` and crosses as a repr. + /// + /// # Panics + /// On `Instance` and `HostClass`, which have no `MontyType`: the exporter + /// routes a sandbox class to [`GraphExporter::sandbox_class_node`] first. + fn from_internal_static(ty: Type) -> Option { + Some(match ty { + Type::Ellipsis => Self::Ellipsis, + Type::NotImplementedType => Self::NotImplementedType, + Type::Type => Self::Type, + Type::NoneType => Self::NoneType, + Type::Bool => Self::Bool, + Type::Int => Self::Int, + Type::Float => Self::Float, + Type::Complex => Self::Complex, + Type::Range => Self::Range, + Type::Slice => Self::Slice, + Type::Date => Self::Date, + Type::DateTime => Self::DateTime, + Type::Time => Self::Time, + Type::TimeDelta => Self::TimeDelta, + Type::TimeZone => Self::TimeZone, + Type::Str => Self::Str, + Type::Bytes => Self::Bytes, + Type::List => Self::List, + Type::Deque => Self::Deque, + // No dedicated host-side deque-iterator type; it crosses as the + // generic `iterator`, like any iterator without a MontyType variant. + Type::DequeIterator => Self::Iterator, + Type::ListIterator => Self::ListIterator, + Type::TupleIterator => Self::TupleIterator, + Type::StrAsciiIterator => Self::StrAsciiIterator, + Type::StrIterator => Self::StrIterator, + Type::BytesIterator => Self::BytesIterator, + Type::RangeIterator => Self::RangeIterator, + Type::DictKeyIterator => Self::DictKeyIterator, + Type::DictItemIterator => Self::DictItemIterator, + Type::DictValueIterator => Self::DictValueIterator, + Type::SetIterator => Self::SetIterator, + Type::CallableIterator => Self::CallableIterator, + Type::ItertoolsPairwise => Self::ItertoolsPairwise, + Type::ItertoolsCompress => Self::ItertoolsCompress, + Type::ItertoolsIslice => Self::ItertoolsIslice, + Type::ItertoolsChain => Self::ItertoolsChain, + Type::ItertoolsCycle => Self::ItertoolsCycle, + Type::ItertoolsTakeWhile => Self::ItertoolsTakeWhile, + Type::ItertoolsDropWhile => Self::ItertoolsDropWhile, + Type::ItertoolsFilterFalse => Self::ItertoolsFilterFalse, + Type::ItertoolsStarMap => Self::ItertoolsStarMap, + Type::ItertoolsAccumulate => Self::ItertoolsAccumulate, + Type::ItertoolsBatched => Self::ItertoolsBatched, + Type::ItertoolsZipLongest => Self::ItertoolsZipLongest, + Type::ItertoolsCombinations => Self::ItertoolsCombinations, + Type::ItertoolsCombinationsWithReplacement => Self::ItertoolsCombinationsWithReplacement, + Type::ItertoolsPermutations => Self::ItertoolsPermutations, + Type::ItertoolsProduct => Self::ItertoolsProduct, + Type::ItertoolsGroupBy => Self::ItertoolsGroupBy, + Type::ItertoolsGrouper => Self::ItertoolsGrouper, + Type::ItertoolsTee => Self::ItertoolsTee, + Type::ItertoolsTeeDataObject => Self::ItertoolsTeeDataObject, + Type::ItertoolsCount => Self::ItertoolsCount, + Type::ItertoolsRepeat => Self::ItertoolsRepeat, + Type::Partial => Self::Partial, + Type::GenericAlias => Self::GenericAlias, + Type::Union => Self::Union, + Type::LruCacheWrapper => Self::LruCacheWrapper, + Type::Random + | Type::HashlibHash + | Type::HashlibHashXof + | Type::Blake2b + | Type::Blake2s + | Type::MissingType + | Type::DirEntry + | Type::ScandirIterator + | Type::WalkGenerator + | Type::CsvReader + | Type::CsvWriter + | Type::CsvDictReader + | Type::CsvDictWriter + | Type::CsvDialect + | Type::DecimalContext + | Type::DecimalSignalDict + | Type::DecimalContextManager => return None, + Type::Decimal => Self::Decimal, + Type::Tuple => Self::Tuple, + Type::NamedTuple => Self::NamedTuple, + Type::Dict => Self::Dict, + // No host-side defaultdict/Counter type; both degrade to `dict`, + // consistent with their values crossing as `MontyNode::Dict`. + Type::DefaultDict | Type::Counter => Self::Dict, + Type::DictKeys => Self::DictKeys, + Type::DictItems => Self::DictItems, + Type::DictValues => Self::DictValues, + Type::Set => Self::Set, + Type::FrozenSet => Self::FrozenSet, + Type::Instance(_) => unreachable!("Type::Instance requires heap access — exported as a class node"), + // The interpreter-internal placeholder never becomes a value: + // `type(x)` on a host instance materializes a `HostClassType`. + Type::HostClass => { + unreachable!("Type::HostClass has no boundary mirror — host instances cross as class nodes") + } + Type::Exception(exc_type) => Self::Exception(exc_type), + Type::Function => Self::Function, + Type::BuiltinFunction => Self::BuiltinFunction, + Type::Cell => Self::Cell, + Type::Iterator => Self::Iterator, + Type::Coroutine => Self::Coroutine, + Type::Module => Self::Module, + Type::TextIOWrapper => Self::TextIOWrapper, + Type::BufferedReader => Self::BufferedReader, + Type::BufferedWriter => Self::BufferedWriter, + Type::BufferedRandom => Self::BufferedRandom, + Type::SpecialForm => Self::SpecialForm, + Type::Path => Self::Path, + Type::Property => Self::Property, + Type::Object => Self::Object, + Type::RePattern => Self::RePattern, + Type::ReMatch => Self::ReMatch, + Type::DataclassField => Self::Field, + Type::DataclassParams => Self::DataclassParams, + }) + } +} + +/// Imports one node whose children are already in `built` (every child id is +/// lower, so they always are). A child used twice becomes a shared heap +/// object: the sandbox sees the identity the host sent. `host_classes` holds +/// the host-defined class nodes, by id, for instances of them. +fn import_node( + node: MontyNode, + built: &[Value], + host_classes: &AHashMap>, + vm: &mut VM<'_>, +) -> Result { + match node { + MontyNode::Ellipsis => Ok(Value::Ellipsis), + MontyNode::NotImplemented => Ok(Value::NotImplemented), + MontyNode::None => Ok(Value::None), + MontyNode::Bool(b) => Ok(Value::Bool(b)), + MontyNode::Int(i) => Ok(Value::Int(i)), + MontyNode::BigInt(bi) => Ok(LongInt::new(bi).into_value(vm.heap)), + MontyNode::Float(f) => Ok(Value::Float(f)), + MontyNode::Complex(c) => Ok(Complex::new(c.real, c.imag).into_value(vm.heap)), + MontyNode::String(s) => Ok(allocate_string(s, vm.heap)), + MontyNode::Bytes(b) => Ok(Value::Ref(vm.heap.allocate(HeapData::Bytes(Bytes::new(b))))), + MontyNode::List(ids) => { + let values = clone_children(&ids, built, vm); + Ok(Value::Ref(vm.heap.allocate(HeapData::List(List::new(values))))) + } + MontyNode::Tuple(ids) => { + let values = clone_children(&ids, built, vm); + Ok(allocate_tuple(values.into(), vm.heap)) + } + MontyNode::NamedTuple { + type_name, + field_names, + values, + } => { + // `NamedTuple::new` asserts equal lengths; malformed host input + // (e.g. untrusted serialized data) must error, not panic. + if field_names.len() != values.len() { + return Err(InvalidInputError::invalid_type( + "NamedTuple field_names and values must have the same length", + )); + } + let values = clone_children(&values, built, vm); + let field_name_strs: Vec = field_names.into_iter().map(Into::into).collect(); + let nt = NamedTuple::new(type_name, field_name_strs, values); + Ok(Value::Ref(vm.heap.allocate(HeapData::NamedTuple(Box::new(nt))))) + } + MontyNode::Dict(pairs) => { + let pairs = clone_pairs(&pairs, built, vm); + let dict = + Dict::from_pairs(pairs, vm).map_err(|_| InvalidInputError::invalid_type("unhashable dict keys"))?; + Ok(Value::Ref(vm.heap.allocate(HeapData::Dict(dict)))) + } + MontyNode::Set(ids) => { + let set = import_set(&ids, built, vm, "unhashable set element")?; + Ok(Value::Ref(vm.heap.allocate(HeapData::Set(set)))) + } + MontyNode::FrozenSet(ids) => { + let set = import_set(&ids, built, vm, "unhashable frozenset element")?; + let frozenset = FrozenSet::from_set(set); + Ok(Value::Ref(vm.heap.allocate(HeapData::FrozenSet(frozenset)))) + } + MontyNode::Date(date) => { + let value = date_type::from_ymd(date.year, i32::from(date.month), i32::from(date.day)) + .map_err(|_| InvalidInputError::invalid_type("date"))?; + Ok(Value::Ref(vm.heap.allocate(HeapData::Date(value)))) + } + MontyNode::DateTime(datetime) => { + let MontyDateTime { + year, + month, + day, + hour, + minute, + second, + microsecond, + offset_seconds, + timezone_name, + } = datetime; + if offset_seconds.is_none() && timezone_name.is_some() { + return Err(InvalidInputError::invalid_type("datetime")); + } + let tzinfo = offset_seconds + .map(|offset| TimeZone::new(offset, timezone_name)) + .transpose() + .map_err(|_| InvalidInputError::invalid_type("datetime"))?; + let value = datetime_type::from_components( + year, + i32::from(month), + i32::from(day), + i32::from(hour), + i32::from(minute), + i32::from(second), + i32::try_from(microsecond).map_err(|_| InvalidInputError::invalid_type("datetime"))?, + tzinfo, + None, + vm.heap, + ) + .map_err(|_| InvalidInputError::invalid_type("datetime"))?; + Ok(Value::Ref(vm.heap.allocate(HeapData::DateTime(value)))) + } + MontyNode::Time(time) => { + let MontyTime { + hour, + minute, + second, + microsecond, + offset_seconds, + timezone_name, + fold, + } = time; + if offset_seconds.is_none() && timezone_name.is_some() { + return Err(InvalidInputError::invalid_type("time")); + } + let tzinfo = offset_seconds + .map(|offset| TimeZone::new(offset, timezone_name)) + .transpose() + .map_err(|_| InvalidInputError::invalid_type("time"))?; + let value = time_type::from_boundary_components( + i32::from(hour), + i32::from(minute), + i32::from(second), + i32::try_from(microsecond).map_err(|_| InvalidInputError::invalid_type("time"))?, + i32::from(fold), + tzinfo, + vm.heap, + ) + .map_err(|_| InvalidInputError::invalid_type("time"))?; + Ok(Value::Ref(vm.heap.allocate(HeapData::Time(value)))) + } + MontyNode::TimeDelta(delta) => { + let delta = timedelta_type::new(delta.days, delta.seconds, delta.microseconds) + .map_err(|_| InvalidInputError::invalid_type("timedelta"))?; + Ok(Value::Ref(vm.heap.allocate(HeapData::TimeDelta(delta)))) + } + // The host's text is untrusted: it must parse as `Decimal(text)` would, + // a malformed literal or out-of-range exponent being rejected rather than + // turned into a NaN. + MontyNode::Decimal(text) => match decimal_type::parse::parse_str(&text) { + Ok(Ok(decimal)) => Ok(py_decimal::decimal_value(decimal, vm)), + Ok(Err(_)) | Err(_) => Err(InvalidInputError::invalid_type("Decimal")), + }, + MontyNode::TimeZone(tz) => { + if tz.offset_seconds == 0 && tz.name.is_none() { + Ok(vm.heap.get_timezone_utc()) + } else { + let tz = TimeZone::new(tz.offset_seconds, tz.name) + .map_err(|_| InvalidInputError::invalid_type("timezone"))?; + Ok(Value::Ref(vm.heap.allocate(HeapData::TimeZone(tz)))) + } + } + MontyNode::Exception { exc_type, arg } => { + let exc = SimpleException::new(exc_type, arg); + Ok(Value::Ref(vm.heap.allocate(HeapData::Exception(exc)))) + } + // A sandbox class the host hands back resolves to the class object + // itself; a host class resolves to its single `HostClassType` entry, + // and calling it (or a classmethod on it) suspends to the host, whose + // own policy decides. + MontyNode::ClassType(class) => match vm.heap.resolve_boundary_uuid(&class.id) { + Some(class_id) if matches!(vm.heap.get(class_id), HeapData::Class(_)) => { + vm.heap.inc_ref(class_id); + Ok(Value::Ref(class_id)) + } + _ if class.host_defined => { + let attrs = clone_pairs(&class.attrs, built, vm); + intern_host_class_type(class.name, class.id, class.is_dataclass, attrs, vm).map(Value::Ref) + } + _ => Err(InvalidInputError::invalid_type(format!( + "sandbox class '{}' (id {}) no longer exists", + class.name, class.id + ))), + }, + // A sandbox instance the host hands back resolves to the original + // object by uuid (identity survives the round trip); anything else + // is host-backed, whatever its class id resolved to as a type object. + MontyNode::ClassInstance { + class_type, + instance_id, + attrs, + } => match vm.heap.resolve_boundary_uuid(&instance_id) { + Some(id) if matches!(vm.heap.get(id), HeapData::Instance(_)) => { + // TODO: apply `attrs` to the instance so host-side edits + // are visible; for now the payload is ignored. + vm.heap.inc_ref(id); + Ok(Value::Ref(id)) + } + _ if host_classes.contains_key(&class_type) => { + let class = &host_classes[&class_type]; + let pairs = clone_pairs(&attrs, built, vm); + let dict = Dict::from_pairs(pairs, vm) + .map_err(|_| InvalidInputError::invalid_type("unhashable class instance attr keys"))?; + // Guarded while the class type interns (its attrs can fail + // too); `HostClass::new` then takes both. + let mut dict_guard = DropGuard::new(dict, vm); + let (_, vm) = dict_guard.as_parts_mut(); + let class_attrs = clone_pairs(&class.attrs, built, vm); + let class_id = + intern_host_class_type(class.name.clone(), class.id, class.is_dataclass, class_attrs, vm)?; + let (dict, vm) = dict_guard.into_parts(); + let hc = HostClass::new(instance_id, class_id, dict); + Ok(Value::Ref(vm.heap.allocate(HeapData::HostClass(Box::new(hc))))) + } + _ => { + let Value::Ref(class_id) = built[class_type.index()] else { + unreachable!("class nodes always import as heap references"); + }; + Err(InvalidInputError::invalid_type(format!( + "sandbox instance of '{}' (id {instance_id}) no longer exists", + class_name(class_id, vm.heap, vm.interns) + ))) + } + }, + // A host module is a real module object: attribute errors are raised + // in the sandbox, nothing routes back to the host by identity. + MontyNode::Module { name, id, attrs } => { + let pairs = clone_pairs(&attrs, built, vm); + let dict = Dict::from_pairs(pairs, vm) + .map_err(|_| InvalidInputError::invalid_type("unhashable module attr keys"))?; + let module = Module::host(name, id, dict); + Ok(Value::Ref(vm.heap.allocate(HeapData::Module(Box::new(module))))) + } + MontyNode::Path(s) => Ok(Value::Ref(vm.heap.allocate(HeapData::Path(Path::new(s))))), + MontyNode::FileHandle(handle) => { + let file = OpenFile::with_state(handle.path, handle.mode, handle.position); + Ok(Value::Ref(vm.heap.allocate(HeapData::OpenFile(Box::new(file))))) + } + MontyNode::Type(t) => Ok(Value::Builtin(Builtins::Type(t.to_internal()))), + MontyNode::BuiltinFunction(f) => Ok(Value::Builtin(Builtins::Function(f))), + MontyNode::Function { name, .. } => Ok(vm.heap.get_ext_function(&name)), + MontyNode::Repr(_) => Err(InvalidInputError::invalid_type("'Repr' is not a valid input value")), + MontyNode::Cycle(_) => Err(InvalidInputError::invalid_type("'Cycle' is not a valid input value")), + } +} + +/// Owned clones of already-imported children. +fn clone_children(ids: &[NodeId], built: &[Value], vm: &VM<'_>) -> Vec { + ids.iter() + .map(|id| built[id.index()].clone_with_heap(vm.heap)) + .collect() +} + +/// Owned clones of already-imported `(key, value)` children. +fn clone_pairs(pairs: &[(NodeId, NodeId)], built: &[Value], vm: &VM<'_>) -> Vec<(Value, Value)> { + pairs + .iter() + .map(|(key, value)| { + ( + built[key.index()].clone_with_heap(vm.heap), + built[value.index()].clone_with_heap(vm.heap), + ) + }) + .collect() +} + +/// Builds a `Set` from already-imported elements, dropping the partially-built +/// set (and every value already added to it) if any element fails to hash. +fn import_set( + ids: &[NodeId], + built: &[Value], + vm: &mut VM<'_>, + unhashable_msg: &'static str, +) -> Result { + let mut guard = DropGuard::new(Set::new(), vm); + let (set, vm) = guard.as_parts_mut(); + for id in ids { + let value = built[id.index()].clone_with_heap(vm.heap); + set.add(value, vm) + .map_err(|_| InvalidInputError::invalid_type(unhashable_msg))?; + } + Ok(guard.into_inner()) +} + +/// Resolves a host-defined class to the sandbox's single `HostClassType` +/// entry for its uuid, creating it on first sight, and returns an owned +/// reference. A re-send overwrites `name` and `is_dataclass` (the host is +/// authoritative) and, when its eager class attrs are non-empty, replaces +/// them; an empty set leaves them alone. +fn intern_host_class_type( + name: String, + type_id: MontyUuid, + is_dataclass: bool, + attr_pairs: Vec<(Value, Value)>, + vm: &mut VM<'_>, +) -> Result { + let attrs = + Dict::from_pairs(attr_pairs, vm).map_err(|_| InvalidInputError::invalid_type("unhashable class attr keys"))?; + let name = EitherStr::Heap(name); + match vm.heap.resolve_host_type(&type_id) { + Some(class_id) => { + vm.heap.inc_ref(class_id); + let HeapReadOutput::HostClassType(ty) = vm.heap.read(class_id) else { + unreachable!("host_type_index points at a non-host-class-type entry"); + }; + let replaced = (!attrs.is_empty()).then_some(attrs); + let old_attrs = ty.update_from_wire(name, is_dataclass, replaced, vm.heap); + old_attrs.drop_with(vm); + Ok(class_id) + } + None => Ok(vm + .heap + .allocate_host_type(HostClassType::new(name, type_id, is_dataclass, attrs))), + } +} + +/// Clones every `(key, value)` pair out of a dict (or dataclass attrs) so +/// recursive conversion cannot be invalidated by user code mutating it. +fn snapshot_dict_pairs(dict: &Dict, heap: &Heap) -> Vec<(Value, Value)> { + dict.iter() + .map(|(key, value)| (key.clone_with_heap(heap), value.clone_with_heap(heap))) + .collect() +} + +/// Converts a value to its repr node, falling back to a descriptive error +/// message if `py_repr` fails (e.g. INT_MAX_STR_DIGITS). +fn repr_node(value: &Value, vm: &mut VM<'_>) -> MontyNode { + match value.py_repr(vm) { + Ok(s) => { + // `py_repr` yields a heap `str` `Value`; extract its text and drop it. + defer_drop!(s, vm); + MontyNode::Repr(s.to_str(vm).map(str::to_owned).unwrap_or_default()) + } + Err(e) => { + let ty = value.py_type_name(vm); + let msg = match &e { + RunError::Internal(s) => s.to_string(), + RunError::Exc(exc) | RunError::UncatchableExc(exc) => exc.exc.to_string(), + }; + MontyNode::Repr(format!("<{ty} object, error on repr(): {msg}>")) + } + } +} diff --git a/crates/bashkit-monty/src/os_dispatch.rs b/crates/bashkit-monty/src/os_dispatch.rs new file mode 100644 index 000000000..3f9bf279b --- /dev/null +++ b/crates/bashkit-monty/src/os_dispatch.rs @@ -0,0 +1,894 @@ +//! Interpreter-side plumbing for OS-level operations. +//! +//! [`OsFunctionCall`] itself (and its typed arg structs) lives in +//! `monty-types` so host crates can match on it without linking the +//! interpreter; it is re-exported here. Type methods and builtins return one +//! as [`CallResult::OsCall`](crate::bytecode::CallResult::OsCall); the VM +//! yields [`FrameExit::OsCall`](crate::bytecode::FrameExit::OsCall) so the +//! host decides whether to permit it. The interpreter itself never performs +//! I/O. This module keeps the `pathlib.Path` method dispatcher that builds +//! the calls from VM values, plus [`PendingEffect`] — the VM-side hook that +//! post-processes an OS-call result on resume. +//! +//! # Adding a new OS call +//! +//! Add a variant carrying a struct in `monty-types` (reuse +//! [`PathStringDataArgs`] etc. if the shape matches, derive `ToArgs` on the +//! struct, update [`OsFunctionCall::name`] and the other inherent methods), +//! add a matching typed arm to `monty.proto`'s `OsCall` and `monty-proto`'s +//! conversions, then wire the new variant into the fs/ dispatcher and any +//! host backends. + +use std::{borrow::Cow, mem}; + +use ahash::AHashSet; +use monty_types::{ + ExcType, MkdirCallArgs, MontyObject, MontyPath, OsFunctionCall, PathBytesDataArgs, PathStringDataArgs, + RenameCallArgs, ResourceTracker, normalize_virtual_path, + unstable::{self, MontyNode}, +}; + +use crate::{ + args::{ArgValues, FromArgs, LaxBool}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcTypeExt, RunError, RunResult, SimpleException}, + heap::{ContainsHeap, DropWithContext, Heap, HeapData, HeapId}, + intern::{Interns, StaticStrings}, + modules::{ + os::{PathArgError, check_mode}, + os_path::{ + StatField, expand_user_reply, expand_vars_reply, lexists_reply, realpath_strict_reply, resolved_path_reply, + samefile_first_reply, samefile_second_reply, stat_field_reply, + }, + random::RandomRetry, + time::ClockReading, + }, + types::{Path, Type, dir_scan::ScanEffect, file::FileName, random::RandomTarget}, + value::Value, + virtual_path::posix_join, +}; + +impl DropWithContext for OsFunctionCall { + // Owned args (String/Vec/bool/MontyPath/MontyObject) hold no live + // heap references, so a plain drop is correct. + fn drop_with(self, _heap: &mut C) { + drop(self); + } +} + +/// Work the VM must perform on the result of a paused OS call when it +/// resumes, instead of pushing the raw host value onto the operand stack. +/// +/// The two stages are separate types because they run on different data: +/// [`Pre`](Self::Pre) on the raw [`MontyObject`] before heap conversion, +/// [`Post`](Self::Post) on the converted [`Value`] after it. Rides inside the +/// suspension value — [`CallResult::OsCallWithEffect`], then +/// [`FrameExit::OsCall`](crate::bytecode::FrameExit) — and is armed on the +/// VM's single slot (one call in flight per task) only once the call reaches +/// the host, where a `resume` becomes guaranteed; anything discarding the +/// suspension calls [`release_pending_effect`] instead. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum PendingEffect { + /// Reshapes the host's reply before it is converted to a heap value. + Pre(PreConversionEffect), + /// Applies the converted value to VM state, possibly pinning a file. + Post(PostConversionEffect), + /// Builds a walk, scandir or glob result from a `Path.scan` reply — or + /// from the `OSError` it answered with (see [`ScanEffect::absorbs`]). + Scan(ScanEffect), +} + +impl PendingEffect { + /// Operations whose result `VM::resume` must postprocess before execution + /// continues, named for the `RuntimeError` a host gets for answering them + /// with a future (which bypasses `resume`). + pub(crate) fn immediate_result_name(&self) -> Option<&'static str> { + match self { + Self::Pre(effect) => Some(effect.operation_name()), + Self::Scan(effect) => Some(effect.operation_name()), + Self::Post(PostConversionEffect::OpenName { .. }) => Some("open"), + // The parse answers the `json.load` call; a future would hand Python the text. + Self::Post(PostConversionEffect::JsonLoad { .. }) => Some("json.load"), + Self::Post(PostConversionEffect::SeedRandom { .. }) => Some("os.urandom"), + // `time.sleep` blocks by definition, so a future would leave the + // sandbox running before the wait it asked for finished. + Self::Post(PostConversionEffect::DiscardResult) => Some("time.sleep"), + // The reading still has to become a `struct_time` or a string, which + // a future defers past the point the sandbox needs it. + Self::Post(PostConversionEffect::ClockReading { .. }) => Some("time.time"), + // The load answers a `ForIter` or `next()` that is waiting for the + // buffer; a future would land on the stack where the file is expected. + Self::Post(PostConversionEffect::BufferLoad { .. } | PostConversionEffect::FileNext { .. }) => { + Some("file iteration") + } + // The replayed call expects its argument loaded; a future would stand in for the call's result. + Self::Post(PostConversionEffect::LoadThenCall { .. }) => Some("file loading"), + // A future strands these instead: the awaited value is the raw host reply. + Self::Post(PostConversionEffect::BufferStore { .. } | PostConversionEffect::WritePosition { .. }) => None, + // `asyncio.sleep` wants the future: `resume_with_result` moves the + // result onto the pending awaitable instead. + Self::Post(PostConversionEffect::SleepResult { .. }) => None, + } + } + + /// Discards an effect that will never be applied, releasing whatever it + /// held across the host yield (see [`PostConversionEffect::release`]). + pub(crate) fn release(self, heap: &mut impl ContainsHeap) { + match self { + Self::Pre(_) => {} + Self::Post(effect) => effect.release(heap), + Self::Scan(effect) => effect.release(heap), + } + } +} + +impl From for PendingEffect { + fn from(effect: PreConversionEffect) -> Self { + Self::Pre(effect) + } +} + +impl From for PendingEffect { + fn from(effect: PostConversionEffect) -> Self { + Self::Post(effect) + } +} + +impl From for PendingEffect { + fn from(effect: ScanEffect) -> Self { + Self::Scan(effect) + } +} + +/// Reshapes the raw host reply before heap conversion: plain data in, plain +/// data out, so no variant holds a heap reference and none needs cleanup. +// TODO: Consider separating effects from caller names so functions can share result handling. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum PreConversionEffect { + /// `os.listdir`: reduce the host's `Iterdir` result (a list of child + /// paths) to the list of bare entry names. + ListdirNames, + /// Return the destination path after Path.rename succeeds. + RenamePath { target: String }, + /// Return the destination path after Path.replace succeeds. + ReplacePath { target: String }, + /// Suppress a missing-file exception only when requested by Path.unlink. + Unlink { missing_ok: bool }, + /// `os.chdir`: the target was sent to the host as a `Path.stat` call; + /// normalize and adopt `path` once the reply proves it is a directory. + Chdir { + /// Unnormalized absolute target, retained until the host validates it. + path: String, + /// The path as the caller spelled it, for `NotADirectoryError` (CPython + /// reports the argument, not the resolved path). + spelled: String, + }, + /// Rebuild directory entries beneath the caller's original `Path`. + IterdirPaths { path: String }, + /// `os.urandom(size)`: the reply must be `bytes` of exactly `size`, so a + /// handler cannot hand the sandbox more than it asked (and preflighted) for. + UrandomLength { size: usize }, + /// `os.path.getsize` and friends: keep one field of a `Path.stat` reply. + StatField(StatField), + /// `os.path.realpath`: the `Path.resolve` reply arrives as a path; the + /// function returns `str`. Under `strict` the reply is then checked with + /// `Path.exists` ([`RealpathStrict`](Self::RealpathStrict)). + ResolvedPath { strict: bool }, + /// `os.path.realpath(strict=True)`: a `False` from `Path.exists` on the + /// resolved path is `FileNotFoundError`; `True` yields the path. + RealpathStrict { resolved: String }, + /// `os.path.lexists`: a `False` from `Path.exists` is not final — a + /// dangling symlink exists too — so `Path.is_symlink` decides next. + Lexists { path: String }, + /// `os.path.samefile`: the first `Path.stat` reply is in; stat `second` + /// next. `second` is already extracted so its converter error is raised + /// only now, after the first stat succeeded, in CPython's order. + SamefileFirst { + first: String, + second: Result, + }, + /// `os.path.samefile`: both stats are in; compare them. The identity is + /// `(st_ino, st_dev)` as decimal text, an equality key that fits any int. + SamefileSecond { + first: String, + first_identity: (String, String), + second: String, + }, + /// `os.path.expanduser`: splice the `os.getenv('HOME')` reply in front of + /// `tail`, the path after its leading `~`; `None` leaves the path as written. + ExpandUser { + #[serde(with = "serde_bytes")] + tail: Vec, + /// Whether the argument was `bytes`, so the result is too. + is_bytes: bool, + }, + /// `os.path.expandvars`: substitute `$var` / `${var}` in `path` from the + /// `os.environ` reply. + ExpandVars { + #[serde(with = "serde_bytes")] + path: Vec, + /// Whether the argument was `bytes`, so the result is too. + is_bytes: bool, + }, +} + +impl PreConversionEffect { + /// Applies the effect to the host's reply, yielding the value the VM + /// imports and pushes, or the next call of a multi-step operation; + /// `Chdir` adopts the directory as a side effect. + pub(crate) fn reshape(self, value: MontyObject, vm: &mut VM<'_>) -> Result { + let reply = match self { + Self::ListdirNames => listdir_names(value), + Self::RenamePath { target } | Self::ReplacePath { target } => Ok(MontyObject::path(target)), + Self::Unlink { .. } => Ok(MontyObject::none()), + Self::IterdirPaths { path } => iterdir_paths(value, &path, &vm.heap.tracker), + Self::UrandomLength { size } => urandom_reply(value, size), + Self::Chdir { path, spelled } => { + check_chdir_stat(&value, &spelled)?; + vm.env.cwd = Cow::Owned(normalize_virtual_path(&path).into_owned()); + Ok(MontyObject::none()) + } + Self::StatField(field) => stat_field_reply(&value, field), + Self::ResolvedPath { strict } => return resolved_path_reply(&value, strict), + Self::RealpathStrict { resolved } => realpath_strict_reply(&value, resolved), + Self::Lexists { path } => return lexists_reply(&value, path), + Self::SamefileFirst { first, second } => return samefile_first_reply(&value, first, second), + Self::SamefileSecond { + first, + first_identity, + second, + } => samefile_second_reply(&value, &first, &first_identity, &second, &vm.env.cwd), + Self::ExpandUser { tail, is_bytes } => expand_user_reply(&value, &tail, is_bytes), + Self::ExpandVars { path, is_bytes } => expand_vars_reply(&value, &path, is_bytes, &vm.heap.tracker), + }; + reply.map(Reshaped::Value) + } + + /// The Python operation this effect completes, for error messages. + fn operation_name(&self) -> &'static str { + match self { + Self::ListdirNames => "os.listdir", + Self::RenamePath { .. } => "Path.rename", + Self::ReplacePath { .. } => "Path.replace", + Self::Unlink { .. } => "Path.unlink", + Self::Chdir { .. } => "os.chdir", + Self::IterdirPaths { .. } => "Path.iterdir", + Self::UrandomLength { .. } => "os.urandom", + Self::StatField(field) => field.function(), + Self::ResolvedPath { .. } | Self::RealpathStrict { .. } => "os.path.realpath", + Self::Lexists { .. } => "os.path.lexists", + Self::SamefileFirst { .. } | Self::SamefileSecond { .. } => "os.path.samefile", + Self::ExpandUser { .. } => "os.path.expanduser", + Self::ExpandVars { .. } => "os.path.expandvars", + } + } +} + +/// What a [`PreConversionEffect`] makes of the host's reply: the value the +/// VM pushes, or the next call of an operation that needs several (the +/// VM suspends again instead of resuming Python, as if the function had +/// yielded it itself). +pub(crate) enum Reshaped { + /// The operation is complete; push this. + Value(MontyObject), + /// Suspend again with this call, `effect` armed for its reply. + Call { + call: OsFunctionCall, + effect: Option, + }, +} + +/// A `Path.stat` reply's field by name, so a host's stat result is accepted +/// whatever its field order; `None` for anything but a named tuple with it. +pub(crate) fn stat_result_field<'a>(value: &'a MontyObject, name: &str) -> Option<&'a MontyNode> { + match unstable::root_node(value) { + MontyNode::NamedTuple { + field_names, values, .. + } => field_names + .iter() + .position(|field| field == name) + .and_then(|index| values.get(index)) + .map(|id| unstable::node(unstable::child(value.as_ref(), *id))), + _ => None, + } +} + +/// A `Path.exists` / `Path.is_symlink` reply as a bool, refusing anything else. +pub(crate) fn bool_reply(value: &MontyObject, operation: &str) -> Result { + match unstable::root_node(value) { + MontyNode::Bool(answer) => Ok(*answer), + _ => Err(invalid_reply(operation, "a bool", value)), + } +} + +/// The `RuntimeError` for a host reply of the wrong shape: `invalid return +/// type: {operation} requires the host to return {expected}, got {type}`. +pub(crate) fn invalid_reply(operation: &str, expected: &str, value: &MontyObject) -> RunError { + SimpleException::new_msg( + ExcType::RuntimeError, + format!( + "invalid return type: {operation} requires the host to return {expected}, got {}", + value.as_ref().type_name() + ), + ) + .into() +} + +/// Applies the converted host value to VM state. The file variants and +/// `SeedRandom`'s instance target own a reference to their heap object across +/// the host yield (see `inc_ref_for_pending_oscall`) and `SleepResult` owns its +/// value; each is released exactly once — on apply, or via [`Self::release`] +/// when the effect is discarded. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum PostConversionEffect { + /// Store a full-file read result into the file buffer, then compute the + /// pending read/seek slice (see `types/file.rs`). + BufferStore { file_id: HeapId }, + /// [`BufferStore`](Self::BufferStore), then parse the rest of the file as + /// JSON: `json.load(fp)` on a file whose buffer is not loaded yet. + JsonLoad { file_id: HeapId }, + /// Store a full-file read result into the file buffer and push nothing: + /// the `ForIter` that found the file unloaded re-dispatches against it. + BufferLoad { file_id: HeapId }, + /// Store a full-file read result into the file buffer, then answer + /// `next(file, default)`: the first line, `default` at EOF, or + /// `StopIteration`. Owns `default`'s reference across the yield. + FileNext { file_id: HeapId, default: Option }, + /// Advance the file's logical position by the successful write result. + WritePosition { + /// File whose position is updated. + file_id: HeapId, + /// Position before the write was dispatched, used to restore state if + /// the host raises before returning a count. + previous_position: u64, + /// Known file length before dispatch, restored on host exception. + previous_length: u64, + /// Length of the text as passed to `write()` when newline translation + /// lengthened the payload: CPython reports that, not what reached the file. + #[serde(default)] + text_length: Option, + /// Answer `None` instead of the count: `csv.writer.writerows()` writes + /// its lines in one host call but returns nothing. + #[serde(default)] + result_none: bool, + }, + /// Load an unread file's buffer, then replay `callable(args)`, whose first + /// argument the file is (`csv.reader(f)`, `tomllib.load(f)`): the consumer + /// never sees an unloaded file. Owns the callable and the arguments across the yield. + LoadThenCall { + file_id: HeapId, + callable: Value, + args: ArgValues, + }, + /// Preserve `open()`'s filename while the returned handle supplies the I/O target, + /// and apply the `newline` argument, whose value CPython validates after the open. + OpenName { + name: FileName, + #[serde(default)] + newline: Option, + }, + /// Seed a `random` generator from the host's `os.urandom` reply, then + /// answer `None` (`seed()`) or re-run the draw that found it unseeded + /// (`retry`, which owns the call's arguments across the yield). + SeedRandom { + target: RandomTarget, + retry: Option, + }, + /// Drop the host's answer and evaluate to `None` (`time.sleep`, whose + /// CPython return value is always `None`). + DiscardResult, + /// Turn the host's `time.time` answer into what the `time` function that + /// asked for it returns — a `struct_time`, a formatted string or + /// nanoseconds. Holds no heap reference, so nothing to release. + ClockReading { reading: ClockReading }, + /// Drop the host's answer and produce `result` from an awaitable, so + /// `asyncio.sleep(delay, result)` is awaitable whether the host answered + /// immediately (a settled awaitable) or with a future (the pending + /// awaitable takes `result` over; see `ExternalFuture::sleep_result`). + /// Owns `result`'s reference; released by [`release_pending_effect`]. + SleepResult { result: Value }, +} + +impl PostConversionEffect { + /// Releases what the effect held across the yield: the pinned heap object + /// (a file handle, or a `random.Random` instance), any stashed arguments + /// and a sleep's result. The single place that knows which variants carry a refcount. + pub(crate) fn release(self, heap: &mut impl ContainsHeap) { + match self { + Self::BufferStore { file_id } + | Self::JsonLoad { file_id } + | Self::BufferLoad { file_id } + | Self::WritePosition { file_id, .. } => { + heap.heap_mut().dec_ref(file_id); + } + Self::FileNext { file_id, default } => { + heap.heap_mut().dec_ref(file_id); + default.drop_with(heap); + } + Self::LoadThenCall { + file_id, + callable, + args, + } => { + heap.heap_mut().dec_ref(file_id); + callable.drop_with(heap); + args.drop_with(heap); + } + Self::OpenName { .. } | Self::DiscardResult | Self::ClockReading { .. } => {} + Self::SleepResult { result } => result.drop_with(heap), + Self::SeedRandom { target, retry } => { + if let RandomTarget::Instance(id) = target { + heap.heap_mut().dec_ref(id); + } + retry.drop_with(heap); + } + } + } +} + +/// Releases an effect that will never be resumed, dropping the heap pin, +/// arguments or sleep result it carried (see `inc_ref_for_pending_oscall`). +/// +/// Reached via the owner's `drop_with`, or `Drop for VM` once the effect is +/// armed and no owning value remains. +pub(crate) fn release_pending_effect(effect: Option, heap: &mut impl ContainsHeap) { + if let Some(effect) = effect { + effect.release(heap); + } +} + +/// Resolves every relative path in `call` against `cwd` (see [`posix_join`]). +/// +/// Runs at the VM's single OS-call exit, so builtins and `Path` methods can +/// hand over paths exactly as the user wrote them. Absolute and empty paths +/// are left untouched, not copied. +pub(crate) fn resolve_call_paths(call: &mut OsFunctionCall, cwd: &str) { + for path in call.fs_paths_mut() { + if !path.is_empty() && !path.starts_with('/') { + *path = MontyPath::new(posix_join(cwd, path)); + } + } +} + +/// Checks a host `Path.stat` reply for `os.chdir` — the resume half of +/// [`PreConversionEffect::Chdir`], run on the raw [`MontyObject`] before heap +/// import like [`listdir_names`]. +/// +/// A directory `st_mode` passes and the caller normalizes and adopts the path (`os.chdir` +/// returns `None`); a file raises `NotADirectoryError` naming `spelled`, the +/// path as the caller wrote it. Hosts that answered `Path.stat` with +/// something other than a stat result get the same `RuntimeError` shape as +/// `os.listdir`. +pub(crate) fn check_chdir_stat(value: &MontyObject, spelled: &str) -> Result<(), RunError> { + const S_IFMT: i64 = 0o170_000; + const S_IFDIR: i64 = 0o040_000; + // Anything without an integer `st_mode` is refused. + match stat_result_field(value, "st_mode") { + Some(MontyNode::Int(mode)) if mode & S_IFMT == S_IFDIR => Ok(()), + Some(MontyNode::Int(_)) => Err(ExcType::not_a_directory_error(spelled)), + _ => Err(invalid_reply("os.chdir", "a stat result", value)), + } +} + +/// Reduces a host `Iterdir` result (list of virtual child paths) to the list +/// of bare entry names `os.listdir` returns — the resume half of +/// [`PreConversionEffect::ListdirNames`]. +/// +/// Runs on the raw [`MontyObject`] before heap import (see `VM::resume`), +/// so it needs no refcount handling; entries are renamed in place with no new +/// allocations. Virtual paths are always POSIX, so the name is the substring +/// after the last `/`. Hosts answering the `Path.iterdir` callback themselves +/// may return `str` entries instead of paths — both work. +pub(crate) fn listdir_names(value: MontyObject) -> Result { + directory_entries(value, None) +} + +/// Accepts an `os.urandom` reply only as `bytes` of the requested length. +fn urandom_reply(value: MontyObject, size: usize) -> Result { + match unstable::root_node(&value) { + MontyNode::Bytes(bytes) if bytes.len() == size => Ok(value), + MontyNode::Bytes(bytes) => Err(urandom_reply_error(Ok(bytes.len()), size)), + _ => Err(urandom_reply_error(Err(value.as_ref().type_name()), size)), + } +} + +/// The `RuntimeError` for an `os.urandom` reply that is not `bytes` of +/// `expected` length: `Ok(len)` for `bytes` of the wrong length, `Err(type)` +/// for any other type. Shared with `random`'s seeding path so the contract +/// and its wording stay identical. +pub(crate) fn urandom_reply_error(actual: Result, expected: usize) -> RunError { + let message = match actual { + Ok(len) => format!("'os.urandom' returned {len} bytes, expected {expected}"), + Err(type_name) => format!("'os.urandom' must return bytes, not {type_name}"), + }; + SimpleException::new_msg(ExcType::RuntimeError, message).into() +} + +/// Rebuilds host entries using the caller's original relative or absolute directory path. +/// +/// The joins repeat the receiver once per host entry, so their total is +/// preflighted against `tracker` in one shot before any is built. +pub(crate) fn iterdir_paths( + value: MontyObject, + path: &str, + tracker: &ResourceTracker, +) -> Result { + directory_entries(value, Some((path, tracker))) +} + +/// Reduces host paths to entry names, joining them onto the `Path.iterdir()` +/// receiver when one is given (with the tracker its joins are charged to). +fn directory_entries(value: MontyObject, receiver: Option<(&str, &ResourceTracker)>) -> Result { + let invalid = |type_name: &str| -> RunError { + let operation = if receiver.is_some() { + "Path.iterdir" + } else { + "os.listdir" + }; + SimpleException::new_msg( + ExcType::RuntimeError, + format!("invalid return type: {operation} requires the host to return a list of paths, got {type_name}"), + ) + .into() + }; + let MontyNode::List(ids) = unstable::root_node(&value) else { + return Err(invalid(value.as_ref().type_name())); + }; + let ids = ids.clone(); + let (mut graph, root) = unstable::into_graph_parts(value); + let directory = match receiver { + Some((path, tracker)) => { + // Each joined path adds the receiver and a separator on top of the entry. + tracker.check_allocation(ids.len().saturating_mul(path.len() + 1))?; + Some(Path::new(path.to_owned())) + } + None => None, + }; + // An entry the host listed twice is one shared node: rewrite it once. + let mut seen = AHashSet::new(); + for id in ids { + if !seen.insert(id) { + continue; + } + if !matches!(graph.node(id), MontyNode::Path(_) | MontyNode::String(_)) { + return Err(invalid(graph.type_name(id))); + } + let node = graph.node_mut(id); + let (MontyNode::Path(entry) | MontyNode::String(entry)) = node else { + unreachable!("checked above"); + }; + if let Some(sep) = entry.rfind('/') { + entry.drain(..=sep); + } + *node = if let Some(directory) = &directory { + MontyNode::Path(directory.joinpath(entry)) + } else { + MontyNode::String(mem::take(entry)) + }; + } + Ok(unstable::object_from_graph(graph, root).expect("root unchanged")) +} + +// ============================================================================= +// Path-method dispatcher (used by `types/path.rs`). +// ============================================================================= + +/// Pre-flight check for [`build_path_os_call`]: lets the caller decide whether +/// to commit ownership of the path/args to the builder. +#[must_use] +pub(crate) fn is_path_os_method(method: StaticStrings) -> bool { + matches!( + method, + StaticStrings::Exists + | StaticStrings::IsFile + | StaticStrings::IsDir + | StaticStrings::IsSymlink + | StaticStrings::ReadText + | StaticStrings::ReadBytes + | StaticStrings::StatMethod + | StaticStrings::Iterdir + | StaticStrings::Resolve + | StaticStrings::Absolute + | StaticStrings::Unlink + | StaticStrings::Rmdir + | StaticStrings::WriteText + | StaticStrings::AppendText + | StaticStrings::WriteBytes + | StaticStrings::AppendBytes + | StaticStrings::Mkdir + | StaticStrings::Rename + | StaticStrings::Replace + ) +} + +/// Builds a host request and its resume action for a `pathlib.Path` OS method. +/// Owns `args` and cleans up its references on every error path. +pub(crate) fn build_path_os_call( + method: StaticStrings, + path: MontyPath, + args: ArgValues, + vm: &mut VM<'_>, +) -> RunResult { + // Simple "no extra args" path operations are bundled into one arm to avoid + // 12 near-identical case lines. + macro_rules! path_only { + ($name:literal, $variant:ident) => {{ + args.check_zero_args($name, vm.heap)?; + OsFunctionCall::$variant(path) + }}; + } + + let call = match method { + StaticStrings::Exists => path_only!("exists", Exists), + StaticStrings::IsFile => path_only!("is_file", IsFile), + StaticStrings::IsDir => path_only!("is_dir", IsDir), + StaticStrings::IsSymlink => path_only!("is_symlink", IsSymlink), + StaticStrings::ReadText => path_only!("read_text", ReadText), + StaticStrings::ReadBytes => path_only!("read_bytes", ReadBytes), + StaticStrings::StatMethod => { + let PathStatArgs { + receiver, + follow_symlinks, + } = PathStatArgs::from_args(args.prepend(Value::None), vm)?; + receiver.drop_with(vm); + if !follow_symlinks.bool() { + return Err(ExcType::not_implemented_os_arg(Some("stat"), "follow_symlinks")); + } + OsFunctionCall::Stat(path) + } + StaticStrings::Iterdir => { + args.check_zero_args("iterdir", vm.heap)?; + return Ok(CallResult::OsCallWithEffect { + effect: PreConversionEffect::IterdirPaths { + path: path.as_str().to_owned(), + } + .into(), + call: OsFunctionCall::Iterdir(path), + }); + } + StaticStrings::Unlink => return build_path_unlink(path, args, vm), + StaticStrings::Resolve => path_only!("resolve", Resolve), + StaticStrings::Absolute => path_only!("absolute", Absolute), + StaticStrings::Rmdir => path_only!("rmdir", Rmdir), + StaticStrings::WriteText => { + OsFunctionCall::WriteText(extract_str_data("write_text", path, args, vm.heap, vm.interns)?) + } + StaticStrings::AppendText => { + OsFunctionCall::AppendText(extract_str_data("append_text", path, args, vm.heap, vm.interns)?) + } + StaticStrings::WriteBytes => { + OsFunctionCall::WriteBytes(extract_bytes_data("write_bytes", path, args, vm.heap, vm.interns)?) + } + StaticStrings::AppendBytes => { + OsFunctionCall::AppendBytes(extract_bytes_data("append_bytes", path, args, vm.heap, vm.interns)?) + } + StaticStrings::Mkdir => OsFunctionCall::Mkdir(extract_mkdir_args(path, args, vm)?), + StaticStrings::Rename | StaticStrings::Replace => { + let args = extract_rename_args(path, args, method == StaticStrings::Replace, vm)?; + let target = args.dst.as_str().to_owned(); + let effect = if method == StaticStrings::Replace { + PreConversionEffect::ReplacePath { target } + } else { + PreConversionEffect::RenamePath { target } + }; + + return Ok(CallResult::OsCallWithEffect { + call: OsFunctionCall::Rename(args), + effect: effect.into(), + }); + } + _ => { + args.drop_with(vm.heap); + unreachable!("is_path_os_method gates the call"); + } + }; + Ok(CallResult::OsCall(call)) +} + +/// Extracts the `data` arg for `write_text` / `append_text`. Error wording +/// matches the legacy `fs/` dispatcher so existing tests stay green. +fn extract_str_data( + method: &'static str, + path: MontyPath, + args: ArgValues, + heap: &mut Heap, + interns: &Interns, +) -> RunResult { + let data = arg_or_missing_data(method, args, heap)?; + // Only `str`: a path-like is not text, so CPython refuses `Path` and `DirEntry` here. + let data_str = data.to_str_heap(heap, interns).ok().map(str::to_owned); + + // CPython names the type by its `__name__`: no module (`DirEntry`, not + // `posix.DirEntry`), but a class's own name (`Point` for a named tuple). + let type_name = data.py_type_name_heap(heap, interns); + let py_type = type_name + .rsplit_once('.') + .map_or(&*type_name, |(_, name)| name) + .to_owned(); + data.drop_with(heap); + + match data_str { + Some(data) => Ok(PathStringDataArgs { path, data }), + None => Err(ExcType::type_error(format!("data must be str, not {py_type}"))), + } +} + +/// Extracts the `data` arg for `write_bytes` / `append_bytes` — binary +/// companion to [`extract_str_data`]. +fn extract_bytes_data( + method: &'static str, + path: MontyPath, + args: ArgValues, + heap: &mut Heap, + interns: &Interns, +) -> RunResult { + let data = arg_or_missing_data(method, args, heap)?; + let bytes = value_to_owned_bytes(&data, heap, interns); + + let py_type = data.py_type_name_heap(heap, interns); + data.drop_with(heap); + + match bytes { + Some(data) => Ok(PathBytesDataArgs { path, data }), + None => Err(ExcType::type_error(format!( + "memoryview: a bytes-like object is required, not '{py_type}'" + ))), + } +} + +/// Path.mkdir binds a receiver slot so arity errors include self. +#[derive(FromArgs)] +#[from_args(name = "Path.mkdir", style = def)] +struct PathMkdirArgs { + #[from_args(pos_only)] + receiver: Value, + #[from_args(default = Value::Int(0o777))] + mode: Value, + #[from_args(default = LaxBool::new(false))] + parents: LaxBool, + #[from_args(default = LaxBool::new(false))] + exist_ok: LaxBool, +} + +/// Extracts `mode`/`parents`/`exist_ok` for `mkdir`, rejecting unknown or +/// excessive arguments before the host sees the OS call. +fn extract_mkdir_args(path: MontyPath, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let PathMkdirArgs { + receiver, + mode, + parents, + exist_ok, + } = PathMkdirArgs::from_args(args.prepend(Value::None), vm)?; + receiver.drop_with(vm); + defer_drop!(mode, vm); + check_mode(mode, vm)?; + Ok(MkdirCallArgs { + path, + parents: parents.bool(), + exist_ok: exist_ok.bool(), + }) +} + +/// Keyword-only options shared with os.stat. +#[derive(FromArgs)] +#[from_args(name = "Path.stat", style = def)] +struct PathStatArgs { + #[from_args(pos_only)] + receiver: Value, + #[from_args(kw_only, default = LaxBool::new(true))] + follow_symlinks: LaxBool, +} + +#[derive(FromArgs)] +#[from_args(name = "Path.rename", style = def)] +struct PathRenameArgs { + #[from_args(pos_only)] + receiver: Value, + target: Value, +} + +#[derive(FromArgs)] +#[from_args(name = "Path.replace", style = def)] +struct PathReplaceArgs { + #[from_args(pos_only)] + receiver: Value, + target: Value, +} + +fn extract_rename_args(src: MontyPath, args: ArgValues, replace: bool, vm: &mut VM<'_>) -> RunResult { + let (receiver, target) = if replace { + let PathReplaceArgs { receiver, target } = PathReplaceArgs::from_args(args.prepend(Value::None), vm)?; + (receiver, target) + } else { + let PathRenameArgs { receiver, target } = PathRenameArgs::from_args(args.prepend(Value::None), vm)?; + (receiver, target) + }; + receiver.drop_with(vm); + defer_drop!(target, vm); + if let Some(dst) = value_to_owned_string(target, vm.heap, vm.interns) { + Ok(RenameCallArgs { + src, + dst: MontyPath::new(dst), + }) + } else { + // pathlib delegates to os.rename/replace; bytes paths remain unsupported in Monty. + let accepted = if target.py_type_heap(vm.heap) == Type::Bytes { + "string or os.PathLike" + } else { + "string, bytes or os.PathLike" + }; + Err(ExcType::type_error_os_path( + if replace { "replace" } else { "rename" }, + "dst", + accepted, + &target.py_type_name_heap(vm.heap, vm.interns), + )) + } +} + +#[derive(FromArgs)] +#[from_args(name = "Path.unlink", style = def)] +struct PathUnlinkArgs { + #[from_args(pos_only)] + receiver: Value, + #[from_args(default = LaxBool::new(false))] + missing_ok: LaxBool, +} + +fn build_path_unlink(path: MontyPath, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let PathUnlinkArgs { receiver, missing_ok } = PathUnlinkArgs::from_args(args.prepend(Value::None), vm)?; + receiver.drop_with(vm); + Ok(CallResult::OsCallWithEffect { + call: OsFunctionCall::Unlink(path), + effect: PreConversionEffect::Unlink { + missing_ok: missing_ok.bool(), + } + .into(), + }) +} + +/// Pulls the single `data` arg out of `args`, raising the CPython-style +/// `missing 1 required positional argument: 'data'` error when absent. +fn arg_or_missing_data(method: &'static str, args: ArgValues, heap: &mut Heap) -> RunResult { + if matches!(args, ArgValues::Empty) { + return Err(ExcType::type_error(format!( + "Path.{method}() missing 1 required positional argument: 'data'" + ))); + } + args.get_one_arg(method, heap) +} + +/// Owned `String` if `value` is a `str`, `Path` or `DirEntry`, else `None`. Caller drops +/// the source value afterwards. Also used by the `os` module's path-taking +/// functions (`modules/os.rs`). +pub(crate) fn value_to_owned_string(value: &Value, heap: &Heap, interns: &Interns) -> Option { + value_as_path_str(value, heap, interns).map(str::to_owned) +} + +/// The text of a `str`, `Path` or `DirEntry` `value`, borrowed, else `None`: +/// what [`value_to_owned_string`] copies, for sizing the copy first. +pub(crate) fn value_as_path_str<'a>(value: &Value, heap: &'a Heap, interns: &'a Interns) -> Option<&'a str> { + match value { + Value::InternString(id) => Some(interns.get_str(*id)), + Value::Ref(id) => match heap.get(*id) { + HeapData::Str(s) => Some(s.as_str()), + HeapData::Path(p) => Some(p.as_str()), + HeapData::DirScan(scan) => scan.fspath(), + _ => None, + }, + _ => None, + } +} + +/// Owned `Vec` if `value` is a `bytes` (interned or heap), else `None`. +pub(crate) fn value_to_owned_bytes(value: &Value, heap: &Heap, interns: &Interns) -> Option> { + match value { + Value::InternBytes(id) => Some(interns.get_bytes(*id).to_owned()), + Value::Ref(id) => match heap.get(*id) { + HeapData::Bytes(b) => Some(b.as_slice().to_owned()), + _ => None, + }, + _ => None, + } +} diff --git a/crates/bashkit-monty/src/parse.rs b/crates/bashkit-monty/src/parse.rs new file mode 100644 index 000000000..05442fdc6 --- /dev/null +++ b/crates/bashkit-monty/src/parse.rs @@ -0,0 +1,3084 @@ +use std::{borrow::Cow, cmp::Ordering, fmt}; + +use ahash::AHashSet; +use monty_types::{FormatComplex, FormatFloat, MontyException, StackFrame, StringRepr, bytes_repr}; +use num_bigint::BigInt; +use num_traits::{Num, ToPrimitive}; +use ruff_python_ast::{ + self as ast, BoolOp, CmpOp, ConversionFlag as RuffConversionFlag, ElifElseClause, Expr as AstExpr, + InterpolatedStringElement, Keyword, Number, Operator as AstOperator, ParameterWithDefault, Pattern as AstPattern, + Singleton, Stmt, UnaryOp, + name::Name, + token::TokenKind, + visitor::{Visitor, walk_expr}, +}; +use ruff_python_parser::{Mode, parse_expression, parse_module}; +use ruff_text_size::{Ranged, TextRange, TextSize}; + +use crate::{ + args::{ArgExprs, CallArg, CallKwarg, Kwarg}, + exception_private::{ExcType, ExcTypeExt, RunError, SimpleException}, + expressions::{ + AssignTarget, Callable, CmpOperator, Comprehension, DictItem, Expr, ExprLoc, Identifier, ImportName, Literal, + MatchCase, Node, Operator, Pattern, SequenceItem, Submodule, UnpackTarget, + }, + fstring::{ConversionFlag, FStringPart, FormatSpec, ParsedFormatSpec, encode_format_spec}, + intern::{CompileInterns, StringId}, + source_map::{SourceMap, StackFrameExt}, + source_nesting::{ast_depth_exceeded, nesting_bound_exceeded}, + stringize::stringize_annotation, + types::long_int::{INT_MAX_STR_DIGITS, bigint_cmp_f64, check_bigint_str_digits_limit}, + value::EitherStr, +}; + +/// Maximum nesting depth for AST structures during parsing. +/// Matches CPython's limit of ~200 for nested parentheses. +/// This prevents stack overflow from deeply nested structures like `((((x,),),),)`. +/// +/// ruff itself no longer limits recursion, so this is Monty's single limit: +/// enforced approximately by the pre-parse scan (`source_nesting`) on sources +/// over `CompileOptions::source_scan_threshold`, and exactly by this converter. +#[cfg(not(debug_assertions))] +pub const MAX_NESTING_DEPTH: u16 = 200; +/// In debug builds, we use a lower limit because stack frames are much larger +/// (no inlining, debug info, etc.). The limit is set conservatively to prevent +/// stack overflow while still catching the error before the recursion limit. +#[cfg(debug_assertions)] +pub const MAX_NESTING_DEPTH: u16 = 30; + +/// Caps dotted-import components to bound quadratic storage for interned path prefixes. +pub const MAX_IMPORT_COMPONENTS: usize = 32; + +/// `from __future__ import ...` features whose semantics Monty already provides, +/// so importing them is a no-op rather than an error. +/// +/// All but the last are inert in CPython too, having become mandatory by 3.7. +/// `annotations` is still meaningful there, and a no-op here only because Monty +/// stringizes unconditionally (see `limitations/typing.md`) — what it asks for. +const SUPPORTED_FUTURES: [&str; 9] = [ + "nested_scopes", + "generators", + "division", + "absolute_import", + "with_statement", + "print_function", + "unicode_literals", + "generator_stop", + "annotations", +]; + +/// `from __future__ import ...` features Monty does not implement, rejected +/// rather than silently ignored. `barry_as_FLUFL` (PEP 401) makes `<>` the +/// inequality operator and `!=` a `SyntaxError`; Monty parses neither +/// differently. With [`SUPPORTED_FUTURES`] this must cover CPython's +/// `all_feature_names` — a name in neither is reported as undefined. +const UNSUPPORTED_FUTURES: [&str; 1] = ["barry_as_FLUFL"]; + +/// A parameter in a function signature with optional default value. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ParsedParam { + /// The parameter name. + pub name: StringId, + /// The default value expression (evaluated at definition time). + pub default: Option, +} + +/// A parsed function signature with all parameter types. +/// +/// This intermediate representation captures the structure of Python function +/// parameters before name resolution. Default value expressions are stored +/// as unevaluated AST and will be evaluated during the prepare phase. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub struct ParsedSignature { + /// Positional-only parameters (before `/`). + pub pos_args: Vec, + /// Positional-or-keyword parameters. + pub args: Vec, + /// Variable positional parameter (`*args`). + pub var_args: Option, + /// Keyword-only parameters (after `*` or `*args`). + pub kwargs: Vec, + /// Variable keyword parameter (`**kwargs`). + pub var_kwargs: Option, +} + +impl ParsedSignature { + /// Returns an iterator over all parameter names in the signature. + /// + /// Order: pos_args, args, var_args, kwargs, var_kwargs + pub fn param_names(&self) -> impl Iterator + '_ { + self.pos_args + .iter() + .map(|p| p.name) + .chain(self.args.iter().map(|p| p.name)) + .chain(self.var_args.iter().copied()) + .chain(self.kwargs.iter().map(|p| p.name)) + .chain(self.var_kwargs.iter().copied()) + } + + /// Returns an iterator over every default-value expression in the signature. + /// + /// Defaults are evaluated at *definition* time in the **enclosing** scope, + /// not inside the function being defined. Closure analysis relies on this: + /// a name referenced by a default (e.g. `def inner(b=a)`) is a capture of + /// the enclosing scope, so the cell-var pre-pass must scan these as well as + /// the body (see `collect_cell_vars_from_node`). `*args`/`**kwargs` never + /// carry defaults, so they are not included. + pub fn default_exprs(&self) -> impl Iterator + '_ { + self.pos_args + .iter() + .chain(self.args.iter()) + .chain(self.kwargs.iter()) + .filter_map(|p| p.default.as_ref()) + } +} + +/// A raw (unprepared) function definition from the parser. +/// +/// Contains the function name, signature, and body as parsed AST nodes. +/// During the prepare phase, this is transformed into `PreparedFunctionDef` +/// with resolved names and scope information. +#[derive(Debug, Clone)] +pub struct RawFunctionDef { + /// The function name identifier (not yet resolved to a namespace index). + pub name: Identifier, + /// The parsed function signature with parameter names and default expressions. + pub signature: ParsedSignature, + /// The unprepared function body (names not yet resolved). + pub body: Vec, + /// Whether this is an async function (`async def`). + pub is_async: bool, +} + +/// Type alias for parsed AST nodes (output of the parser). +/// +/// This uses `Node` where function definitions contain their +/// full unprepared body. After the prepare phase, this becomes `PreparedNode` +/// (aka `Node`). +pub type ParseNode = Node; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Try { + pub body: Vec, + pub handlers: Vec>, + pub or_else: Vec, + pub finally: Vec, +} + +/// A parsed exception handler (except clause). +/// +/// Represents `except ExcType as name:` or bare `except:` clauses. +/// The exception type and variable binding are both optional. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ExceptHandler { + /// Exception type(s) to catch. None = bare except (catches all). + pub exc_type: Option, + /// Variable name for `except X as e:`. None = no binding. + pub name: Option, + /// Handler body statements. + pub body: Vec, +} + +/// The `SyntaxError` an `eval()` / `exec()` snippet raises at runtime: +/// `msg (, line N)`, as CPython's `SyntaxError.__str__` renders it. +pub(crate) fn syntax_error_in_snippet(msg: &str, position: CodeRange, source: &str) -> RunError { + let (start, _, _) = SourceMap::new(source).resolve_range(position); + SimpleException::new_msg(ExcType::SyntaxError, format!("{msg} (, line {})", start.line)).into() +} + +/// Builds a [`CodeRange`] from an interned filename and a ruff range. +/// +/// Free rather than a `Parser` method so a syntax error raised before the parser +/// exists can be located the same way [`Parser::convert_range`] does. +fn code_range(filename: StringId, range: TextRange) -> CodeRange { + CodeRange { + filename, + start_byte: range.start().into(), + end_byte: range.end().into(), + } +} + +/// Parses code into a private interner overlay, discarded if any compilation stage fails. +pub(crate) fn parse_with_interner( + code: &str, + filename: &str, + interner: &mut CompileInterns<'_>, +) -> Result, ParseError> { + // Interned up front so a syntax error can be located without a `Parser`, + // leaving the parser to be built once, fully populated, after parsing. + let filename_id = interner.intern(filename); + // Module sources are scanned for nesting by their entry points + // (`MontyRun::new`, the REPL feeds), not here. + parse_module_with_filename_id(code, filename_id, interner, usize::MAX) +} + +/// [`parse_with_interner`] for a filename already interned — an `exec()` +/// snippet, whose `` id is fresh per call so tracebacks can tell the +/// snippets apart. +pub(crate) fn parse_module_with_filename_id( + code: &str, + filename_id: StringId, + interner: &mut CompileInterns<'_>, + source_scan_threshold: usize, +) -> Result, ParseError> { + check_source_nesting(code, Mode::Module, filename_id, source_scan_threshold)?; + let parsed = + parse_module(code).map_err(|e| ParseError::syntax(e.error.to_string(), code_range(filename_id, e.range())))?; + // Harvested before `into_syntax` drops the token stream. + let class_keyword_offsets = parsed + .tokens() + .iter() + .filter(|token| token.kind() == TokenKind::Class) + .map(Ranged::start) + .collect(); + let mut parser = Parser::new(code, filename_id, interner, class_keyword_offsets); + parser.parse_statements(parsed.into_syntax().body) +} + +/// Parses `code` as a single expression, as `eval()` does. +/// +/// `filename_id` is the snippet's fresh `` id (see +/// [`parse_module_with_filename_id`]). +pub(crate) fn parse_expression_with_interner( + code: &str, + filename_id: StringId, + interner: &mut CompileInterns<'_>, + source_scan_threshold: usize, +) -> Result { + check_source_nesting(code, Mode::Expression, filename_id, source_scan_threshold)?; + let parsed = parse_expression(code) + .map_err(|e| ParseError::syntax(e.error.to_string(), code_range(filename_id, e.range())))?; + // No `class` keywords can occur in a bare expression. + let mut parser = Parser::new(code, filename_id, interner, Vec::new()); + parser.parse_expression(*parsed.into_syntax().body) +} + +/// [`check_source_nesting`] for a host vetting a snippet before compiling it, +/// producing the `SyntaxError` the compile would raise. +pub(crate) fn source_nesting_exception( + code: &str, + script_name: &str, + source_scan_threshold: usize, +) -> Result<(), MontyException> { + // The filename id is a compiler concern; the exception names the file itself. + check_source_nesting(code, Mode::Module, StringId::default(), source_scan_threshold) + .map_err(|e| e.into_python_exc(script_name, code)) +} + +/// [`source_nesting_exception`] for a source about to be type-checked, which +/// also rejects any expression nested deeper than [`MAX_NESTING_DEPTH`]. +/// +/// The compiler bounds expression depth itself, but ty walks the whole AST +/// first — annotations the compiler drops included — and a flat source such +/// as `1+1+...` builds one deep enough to overflow the stack. +/// +/// # Errors +/// The `SyntaxError: Source is too deeply nested` located in the source. +pub fn type_check_nesting_exception( + code: &str, + script_name: &str, + source_scan_threshold: usize, +) -> Result<(), MontyException> { + source_nesting_exception(code, script_name, source_scan_threshold)?; + match ast_depth_exceeded(code, MAX_NESTING_DEPTH) { + Some(range) => Err( + ParseError::syntax("Source is too deeply nested", code_range(StringId::default(), range)) + .into_python_exc(script_name, code), + ), + None => Ok(()), + } +} + +/// Rejects a source over `source_scan_threshold` bytes whose estimated parser +/// nesting exceeds [`MAX_NESTING_DEPTH`] before ruff can grow its stack on it. +/// +/// Same message as the converter's exact check, so either path reads alike. +fn check_source_nesting( + code: &str, + mode: Mode, + filename_id: StringId, + source_scan_threshold: usize, +) -> Result<(), ParseError> { + if code.len() > source_scan_threshold + && let Some(range) = nesting_bound_exceeded(code, mode, MAX_NESTING_DEPTH) + { + Err(ParseError::syntax( + "Source is too deeply nested", + code_range(filename_id, range), + )) + } else { + Ok(()) + } +} + +/// Parser for converting ruff AST to Monty's intermediate ParseNode representation. +/// +/// Holds references to the source code and the caller's string interner for names. +/// The filename is interned once at construction and reused for all CodeRanges. +pub struct Parser<'a, 'i> { + code: &'a str, + /// Interned filename ID, used for all CodeRanges created by this parser. + filename_id: StringId, + /// Intern table for names (variables, functions, etc). + interner: &'a mut CompileInterns<'i>, + /// Remaining nesting depth budget for recursive structures. + /// Starts at MAX_NESTING_DEPTH and decrements on each nested level. + /// When it reaches zero, we return a "Source is too deeply nested" syntax error. + depth_remaining: u16, + /// Ascending source offsets of every `class` keyword, taken from the lexer. + /// + /// Ruff's AST is abstract — a `StmtClassDef` *is* a class statement, so it + /// never records where `class` sat, and its range starts at the first + /// decorator. CPython locates a statement at its keyword, so a decorated + /// class's traceback frame needs the concrete position. Read only by + /// [`Parser::class_keyword_range`]. + class_keyword_offsets: Vec, +} + +impl<'a, 'i> Parser<'a, 'i> { + fn new( + code: &'a str, + filename_id: StringId, + interner: &'a mut CompileInterns<'i>, + class_keyword_offsets: Vec, + ) -> Self { + Self { + code, + filename_id, + interner, + depth_remaining: MAX_NESTING_DEPTH, + class_keyword_offsets, + } + } + + fn parse_statements( + &mut self, + statements: impl IntoIterator, + ) -> Result, ParseError> { + // Explicit pre-allocation matters here — `.map(..).collect::, _>>()` + // does NOT pre-size the output. Collecting into `Result, _>` runs the + // iterator through `iter::try_process`'s `Shunt` adapter (so an `Err` can + // short-circuit), and `Shunt`'s `size_hint` lower bound is 0 — which loses + // the `TrustedLen` specialization that would otherwise forward the source + // iterator's length. Each `Stmt` maps to exactly one `ParseNode`. + // + // Accepting `IntoIterator` lets callers + // pass either `Vec` or ruff's `ThinVec` without an intermediate copy. + let iter = statements.into_iter(); + let mut out = Vec::with_capacity(iter.len()); + for stmt in iter { + out.push(self.parse_statement(stmt)?); + } + Ok(out) + } + + /// Folds a flat list of `elif`/`else` clauses into a right-nested `Node::If` tree. + /// + /// Ruff hands us the clauses as a flat `Vec`, but the prepared AST and the + /// bytecode compiler both walk the resulting tree recursively. Each `elif` + /// clause is therefore counted against the same depth budget that bounds + /// explicitly nested source constructs — without this, a long flat chain + /// would produce an AST far deeper than [`MAX_NESTING_DEPTH`] and overflow + /// the host's native stack during the prepare or compile phases. + /// + /// The depth budget consumed during the fold is restored on success so + /// sibling statements are not penalized. On parse errors the budget is + /// left decremented; this is harmless because the parser aborts entirely + /// and `depth_remaining` is never consulted again. + fn parse_elif_else_clauses(&mut self, clauses: Vec) -> Result, ParseError> { + let mut tail: Vec = Vec::new(); + let mut levels: u16 = 0; + for clause in clauses.into_iter().rev() { + match clause.test { + Some(test) => { + // Account for the extra nesting level this clause adds to + // the result tree. + self.decr_depth_remaining(|| test.range())?; + levels += 1; + let test = self.parse_expression(test)?; + let body = self.parse_statements(clause.body)?; + let or_else = tail; + tail = vec![Node::If { test, body, or_else }]; + } + None => { + tail = self.parse_statements(clause.body)?; + } + } + } + self.depth_remaining += levels; + Ok(tail) + } + + /// Parses an exception handler (except clause). + /// + /// Handles `except:`, `except ExcType:`, and `except ExcType as name:` forms. + fn parse_except_handler( + &mut self, + handler: ruff_python_ast::ExceptHandler, + ) -> Result, ParseError> { + let ruff_python_ast::ExceptHandler::ExceptHandler(h) = handler; + let exc_type = match h.type_ { + Some(expr) => Some(self.parse_expression(*expr)?), + None => None, + }; + let name = h.name.map(|n| self.identifier(&n.id, n.range)); + let body = self.parse_statements(h.body)?; + Ok(ExceptHandler { exc_type, name, body }) + } + + /// Parses `match SUBJECT:` and its `case` clauses into [`Node::Match`]. + fn parse_match(&mut self, m: ast::StmtMatch) -> Result { + let position = self.convert_range(m.range); + let subject = self.parse_expression(*m.subject)?; + let cases = m + .cases + .into_iter() + .map(|case| self.parse_match_case(case)) + .collect::, _>>()?; + Ok(Node::Match { + subject, + cases, + position, + }) + } + + /// Parses one `case PATTERN [if GUARD]:` clause. + fn parse_match_case(&mut self, case: ast::MatchCase) -> Result, ParseError> { + let position = self.convert_range(case.pattern.range()); + let pattern = self.parse_pattern(case.pattern)?; + let guard = match case.guard { + Some(guard) => Some(self.parse_expression(*guard)?), + None => None, + }; + let body = self.parse_statements(case.body)?; + Ok(MatchCase { + pattern, + guard, + body, + position, + }) + } + + /// Parses a pattern, charging each nesting level against the depth budget + /// like [`Self::parse_expression`], so a deeply nested pattern cannot + /// overflow the host stack in the prepare and compile passes. + fn parse_pattern(&mut self, pattern: AstPattern) -> Result { + self.decr_depth_remaining(|| pattern.range())?; + let result = self.parse_pattern_impl(pattern); + self.depth_remaining += 1; + result + } + + /// Converts one Ruff pattern, raising the shape errors CPython's compiler + /// raises: two starred names, duplicate constant mapping keys and repeated + /// class attributes. Context-dependent errors (duplicate captures, + /// unreachable irrefutable patterns, mismatched alternatives) belong to the + /// bytecode compiler. + fn parse_pattern_impl(&mut self, pattern: AstPattern) -> Result { + match pattern { + AstPattern::MatchValue(p) => Ok(Pattern::Value(self.parse_expression(*p.value)?)), + AstPattern::MatchSingleton(p) => { + let literal = match p.value { + Singleton::None => Literal::None, + Singleton::True => Literal::Bool(true), + Singleton::False => Literal::Bool(false), + }; + let position = self.convert_range(p.range); + Ok(Pattern::Singleton(ExprLoc::new(position, Expr::Literal(literal)))) + } + AstPattern::MatchSequence(p) => { + let position = self.convert_range(p.range); + let patterns = self.parse_patterns(p.patterns)?; + let stars = patterns.iter().filter(|p| matches!(p, Pattern::Star { .. })).count(); + if stars > 1 { + Err(ParseError::syntax( + "multiple starred names in sequence pattern", + position, + )) + } else { + Ok(Pattern::Sequence { patterns, position }) + } + } + AstPattern::MatchMapping(p) => { + let position = self.convert_range(p.range); + check_subpattern_count(p.keys.len(), "mapping", position)?; + let keys = p + .keys + .into_iter() + .map(|key| self.parse_expression(key)) + .collect::, _>>()?; + self.check_duplicate_mapping_keys(&keys, position)?; + let patterns = self.parse_patterns(p.patterns)?; + let rest = p.rest.map(|name| self.identifier(&name.id, name.range)); + Ok(Pattern::Mapping { + keys, + patterns, + rest, + position, + }) + } + AstPattern::MatchClass(p) => { + let position = self.convert_range(p.range); + check_subpattern_count( + p.arguments.patterns.len() + p.arguments.keywords.len(), + "class", + position, + )?; + let cls = self.parse_expression(*p.cls)?; + let patterns = self.parse_patterns(p.arguments.patterns)?; + let mut kwd_attrs: Vec = Vec::with_capacity(p.arguments.keywords.len()); + let mut kwd_patterns = Vec::with_capacity(p.arguments.keywords.len()); + for keyword in p.arguments.keywords { + let attr = self.interner.intern(&keyword.attr.id); + let pattern = self.parse_pattern(keyword.pattern)?; + // CPython anchors the diagnostic on the repeated keyword's sub-pattern. + if kwd_attrs.contains(&attr) { + return Err(ParseError::syntax( + format!("attribute name repeated in class pattern: {}", keyword.attr.id), + pattern.position(), + )); + } + kwd_attrs.push(attr); + kwd_patterns.push(pattern); + } + Ok(Pattern::Class { + cls, + patterns, + kwd_attrs, + kwd_patterns, + position, + }) + } + AstPattern::MatchStar(p) => Ok(Pattern::Star { + name: p.name.map(|name| self.identifier(&name.id, name.range)), + position: self.convert_range(p.range), + }), + AstPattern::MatchAs(p) => { + let position = self.convert_range(p.range); + let pattern = match p.pattern { + Some(inner) => Some(Box::new(self.parse_pattern(*inner)?)), + None => None, + }; + let name = p.name.map(|name| self.identifier(&name.id, name.range)); + Ok(Pattern::As { + pattern, + name, + position, + }) + } + AstPattern::MatchOr(p) => Ok(Pattern::Or { + patterns: self.parse_patterns(p.patterns)?, + position: self.convert_range(p.range), + }), + } + } + + fn parse_patterns(&mut self, patterns: impl IntoIterator) -> Result, ParseError> { + patterns.into_iter().map(|p| self.parse_pattern(p)).collect() + } + + /// Rejects a mapping pattern that checks one constant key twice (`{1: a, 1: b}`), + /// as CPython's compiler does. Keys compare by Python equality, so `1`, `1.0` + /// and `True` collide; dotted-name keys are runtime values and are not checked. + /// The pairwise scan is bounded by [`check_subpattern_count`]; each key is + /// folded once beforehand, so it never re-clones a big integer per pair. + fn check_duplicate_mapping_keys(&self, keys: &[ExprLoc], position: CodeRange) -> Result<(), ParseError> { + let folded: Vec> = keys + .iter() + .filter_map(|key| ConstantKey::of(key, self.interner)) + .map(|key| FoldedKey { + key, + number: key.number(self.interner), + }) + .collect(); + for (i, constant) in folded.iter().enumerate() { + if folded[..i].iter().any(|seen| seen.py_eq(constant)) { + let constant = constant.key; + // CPython's compiler raises `ValueError` formatting a key past the digit limit. + let msg = match constant.repr(self.interner) { + Some(repr) => format!("mapping pattern checks duplicate key ({repr})"), + None => format!( + "Exceeds the limit ({INT_MAX_STR_DIGITS} digits) for integer string conversion; use \ + sys.set_int_max_str_digits() to increase the limit" + ), + }; + return Err(ParseError::syntax(msg, position)); + } + } + Ok(()) + } + + fn parse_statement(&mut self, statement: Stmt) -> Result { + self.decr_depth_remaining(|| statement.range())?; + let result = self.parse_statement_impl(statement); + self.depth_remaining += 1; + result + } + + fn parse_statement_impl(&mut self, statement: Stmt) -> Result { + match statement { + Stmt::FunctionDef(function) => { + let (def, decorators) = self.parse_function_def(function)?; + Ok(Node::FunctionDef { def, decorators }) + } + Stmt::ClassDef(c) => self.parse_class_def(c), + Stmt::Return(ast::StmtReturn { value, .. }) => Ok(Node::Return(match value { + Some(value) => Some(self.parse_expression(*value)?), + None => None, + })), + Stmt::Delete(d) => Err(ParseError::not_implemented( + "the 'del' statement", + self.convert_range(d.range), + )), + Stmt::TypeAlias(t) => Err(ParseError::not_implemented("type aliases", self.convert_range(t.range))), + Stmt::Assign(ast::StmtAssign { + mut targets, + value, + range, + .. + }) => { + // Ruff represents chained assignments (`a = b = 1`) as a single + // `StmtAssign` with multiple targets. For the common single-target + // case we produce the existing per-shape nodes so the hot path stays + // flat; only chained assignments are lowered into `Node::ChainAssign`. + match targets.len() { + 0 => Err(ParseError::syntax( + "Assignment with no targets".to_string(), + self.convert_range(range), + )), + 1 => { + let target = targets.pop().expect("len == 1"); + self.parse_assignment(target, *value) + } + _ => self.parse_chained_assignment(targets, *value), + } + } + Stmt::AugAssign(ast::StmtAugAssign { target, op, value, .. }) => { + let op = convert_op(op); + let value = self.parse_expression(*value)?; + match *target { + AstExpr::Subscript(ast::ExprSubscript { + value: object, + slice, + range, + .. + }) => Ok(Node::SubscriptOpAssign { + target: self.parse_expression(*object)?, + index: self.parse_expression(*slice)?, + op, + value, + target_position: self.convert_range(range), + }), + AstExpr::Attribute(ast::ExprAttribute { + value: object, + attr, + range, + .. + }) => Ok(Node::AttrOpAssign { + object: self.parse_expression(*object)?, + attr: EitherStr::Interned(self.interner.intern(attr.id())), + op, + value, + target_position: self.convert_range(range), + }), + other => Ok(Node::OpAssign { + target: self.parse_identifier(other)?, + op, + value, + }), + } + } + Stmt::AnnAssign(ast::StmtAnnAssign { target, value, .. }) => match value { + Some(value) => self.parse_assignment(*target, *value), + None => Ok(Node::Pass), + }, + Stmt::For(ast::StmtFor { + is_async, + target, + iter, + body, + orelse, + range, + .. + }) => { + if is_async { + return Err(ParseError::not_implemented( + "async for loops", + self.convert_range(range), + )); + } + Ok(Node::For { + target: self.parse_unpack_target_root(*target)?, + iter: self.parse_expression(*iter)?, + body: self.parse_statements(body)?, + or_else: self.parse_statements(orelse)?, + }) + } + Stmt::While(ast::StmtWhile { test, body, orelse, .. }) => Ok(Node::While { + test: self.parse_expression(*test)?, + body: self.parse_statements(body)?, + or_else: self.parse_statements(orelse)?, + }), + Stmt::If(ast::StmtIf { + test, + body, + elif_else_clauses, + .. + }) => { + let test = self.parse_expression(*test)?; + let body = self.parse_statements(body)?; + let or_else = self.parse_elif_else_clauses(elif_else_clauses)?; + Ok(Node::If { test, body, or_else }) + } + Stmt::With(ast::StmtWith { + is_async, + items, + body, + range, + .. + }) => { + if is_async { + return Err(ParseError::not_implemented( + "async context managers (async with)", + self.convert_range(range), + )); + } + if items.is_empty() { + return Err(ParseError::syntax( + "with statement requires at least one context manager", + self.convert_range(range), + )); + } + // Multi-item `with a() as x, b() as y:` is desugared into nested + // `with` blocks at parse time: the outer `with` runs `a()` and + // wraps an inner `with` running `b()`, which wraps the user body. + // CPython evaluates context exprs left-to-right and exits them + // right-to-left, which is exactly the nested-block semantics — + // so the lowering is faithful and avoids needing multi-context + // support in the compiler / VM. + let position = self.convert_range(range); + let body = self.parse_statements(body)?; + let mut parsed_items: Vec<(ExprLoc, Option)> = items + .into_iter() + .map(|item| -> Result<_, ParseError> { + let context = self.parse_expression(item.context_expr)?; + let target = match item.optional_vars { + Some(expr) => Some(self.parse_unpack_target_root(*expr)?), + None => None, + }; + Ok((context, target)) + }) + .collect::>()?; + // Fold from the innermost outward: the last item wraps the user + // body; each outer item wraps the freshly-built inner `with`. + // + // Each synthetic nesting level must be charged against the parser + // depth budget so a flat `with a, b, c, ...:` statement cannot + // bypass `MAX_NESTING_DEPTH` and produce an AST that later + // overflows the host stack during prepare/compile. The budget is + // restored on success to avoid penalizing sibling statements, in + // the same pattern used by `parse_elif_else_clauses`. + let (last_context, last_target) = parsed_items.pop().expect("checked non-empty above"); + let mut node = Node::With { + context: last_context, + target: last_target, + body, + position, + }; + let mut levels: u16 = 0; + while let Some((context, target)) = parsed_items.pop() { + self.decr_depth_remaining(|| range)?; + levels += 1; + node = Node::With { + context, + target, + body: vec![node], + position, + }; + } + self.depth_remaining += levels; + Ok(node) + } + Stmt::Match(m) => self.parse_match(m), + Stmt::Raise(ast::StmtRaise { exc, .. }) => { + // TODO add cause to Node::Raise + let expr = match exc { + Some(expr) => Some(self.parse_expression(*expr)?), + None => None, + }; + Ok(Node::Raise(expr)) + } + Stmt::Try(ast::StmtTry { + body, + handlers, + orelse, + finalbody, + is_star, + range, + .. + }) => { + if is_star { + Err(ParseError::not_implemented( + "exception groups (try*/except*)", + self.convert_range(range), + )) + } else { + let body = self.parse_statements(body)?; + let handlers = handlers + .into_iter() + .map(|h| self.parse_except_handler(h)) + .collect::, _>>()?; + let or_else = self.parse_statements(orelse)?; + let finally = self.parse_statements(finalbody)?; + Ok(Node::Try(Try { + body, + handlers, + or_else, + finally, + })) + } + } + Stmt::Assert(ast::StmtAssert { test, msg, .. }) => { + let test = self.parse_expression(*test)?; + let msg = match msg { + Some(m) => Some(self.parse_expression(*m)?), + None => None, + }; + Ok(Node::Assert { test, msg }) + } + Stmt::Import(ast::StmtImport { names, range, .. }) => { + let position = self.convert_range(range); + let import_names = names + .iter() + .map(|alias_node| { + let (module_name, submodules) = self.import_path(&alias_node.name, position)?; + // `import a.b` loads `a.b` but binds `a`; an alias binds `a.b` itself. + let binds_top_level = alias_node.asname.is_none() && !submodules.is_empty(); + // The binding name is the alias if present, otherwise the module + // name (or its top-level package when dotted). + let binding_name = alias_node + .asname + .as_ref() + .map_or(module_name, |n| self.interner.intern(&n.id)); + let binding = Identifier::new(binding_name, position); + Ok(ImportName { + module_name, + submodules, + binds_top_level, + binding, + }) + }) + .collect::>()?; + Ok(Node::Import { names: import_names }) + } + Stmt::ImportFrom(ast::StmtImportFrom { + module, + names, + level, + range, + .. + }) => { + let position = self.convert_range(range); + // Compiler directives, not real imports: they bind nothing and lower + // to a no-op, so real-world modules import cleanly. Anything Monty + // does not implement is rejected rather than quietly failing to do + // what it says. `level == 0` keeps `from .__future__ import x` an + // ordinary relative import, falling through to the `ImportError`. + if level == 0 && module.as_ref().is_some_and(|m| m.as_str() == "__future__") { + return match names + .iter() + .find(|a| a.asname.is_some() || !SUPPORTED_FUTURES.contains(&a.name.id.as_str())) + { + Some(alias) if UNSUPPORTED_FUTURES.contains(&alias.name.id.as_str()) => { + Err(ParseError::not_implemented( + format!("the '{}' future feature", alias.name.id), + self.convert_range(alias.range), + )) + } + // Name checks come first so an aliased unknown feature is + // reported as undefined, as CPython does. + Some(alias) if !SUPPORTED_FUTURES.contains(&alias.name.id.as_str()) => Err(ParseError::syntax( + format!("future feature {} is not defined", alias.name.id), + self.convert_range(alias.range), + )), + // A known feature, so the alias is what selected it. An + // alias asks to bind a name and a no-op binds nothing, so + // accepting it would fail exactly the way this branch + // exists to prevent — the `NameError` would surface later, + // far from the import. + Some(alias) => Err(ParseError::not_implemented( + "aliasing a `__future__` feature", + self.convert_range(alias.range), + )), + None => Ok(Node::Pass), + }; + } + // We only support absolute imports (level 0) + if level != 0 { + return Err(ParseError::import_error( + "attempted relative import with no known parent package", + position, + )); + } + // Module name is required for absolute imports + let (module_name, submodules) = match module { + Some(m) => self.import_path(&m, position)?, + None => { + return Err(ParseError::import_error( + "attempted relative import with no known parent package", + position, + )); + } + }; + // Parse the imported names + let names = names + .iter() + .map(|alias| { + // Check for star import which is not supported + if alias.name.as_str() == "*" { + return Err(ParseError::not_supported( + "Wildcard imports (`from ... import *`) are not supported", + position, + )); + } + let name = self.interner.intern(&alias.name); + // The binding name is the alias if provided, otherwise the import name + let binding_name = alias.asname.as_ref().map_or(name, |n| self.interner.intern(&n.id)); + // Create an unresolved identifier (namespace slot will be set during prepare) + let binding = Identifier::new(binding_name, position); + Ok((name, binding)) + }) + .collect::, _>>()?; + Ok(Node::ImportFrom { + module_name, + submodules, + names, + position, + }) + } + Stmt::Global(ast::StmtGlobal { names, range, .. }) => { + let names = names + .iter() + .map(|id| self.interner.intern(&self.code[id.range])) + .collect(); + Ok(Node::Global { + position: self.convert_range(range), + names, + }) + } + Stmt::Nonlocal(ast::StmtNonlocal { names, range, .. }) => { + let names = names + .iter() + .map(|id| self.interner.intern(&self.code[id.range])) + .collect(); + Ok(Node::Nonlocal { + position: self.convert_range(range), + names, + }) + } + Stmt::Expr(ast::StmtExpr { value, .. }) => self.parse_expression(*value).map(Node::Expr), + Stmt::Pass(_) => Ok(Node::Pass), + Stmt::Break(b) => Ok(Node::Break { + position: self.convert_range(b.range), + }), + Stmt::Continue(c) => Ok(Node::Continue { + position: self.convert_range(c.range), + }), + Stmt::IpyEscapeCommand(i) => Err(ParseError::not_implemented( + "IPython escape commands", + self.convert_range(i.range), + )), + } + } + + /// Parses a `def` into a [`RawFunctionDef`] plus its decorators. + /// + /// Shared by the top-level `Stmt::FunctionDef` arm and by class-body method + /// parsing in [`parse_class_def`](Self::parse_class_def). The decorators are + /// returned separately because they belong to the statement, not the function + /// (see [`Node::FunctionDef`]); the class-body path rejects decorated methods + /// before calling here, so it always receives an empty list. + fn parse_function_def( + &mut self, + function: ast::StmtFunctionDef, + ) -> Result<(RawFunctionDef, Vec), ParseError> { + let decorators = self.parse_decorators(function.decorator_list)?; + + let params = &function.parameters; + + // Parse positional-only parameters (before /) + let pos_args = self.parse_params_with_defaults(¶ms.posonlyargs)?; + + // Parse positional-or-keyword parameters + let args = self.parse_params_with_defaults(¶ms.args)?; + + // Parse *args + let var_args = params.vararg.as_ref().map(|p| self.interner.intern(&p.name.id)); + + // Parse keyword-only parameters (after * or *args) + let kwargs = self.parse_params_with_defaults(¶ms.kwonlyargs)?; + + // Parse **kwargs + let var_kwargs = params.kwarg.as_ref().map(|p| self.interner.intern(&p.name.id)); + + let signature = ParsedSignature { + pos_args, + args, + var_args, + kwargs, + var_kwargs, + }; + + let name = self.identifier(&function.name.id, function.name.range); + // Parse function body recursively + let body = self.parse_statements(function.body)?; + let is_async = function.is_async; + + Ok(( + RawFunctionDef { + name, + signature, + body, + is_async, + }, + decorators, + )) + } + + /// Parses decorator expressions in source order. + /// + /// They are ordinary expressions evaluated in the enclosing scope; the + /// compiler emits the applying calls after building the decorated value. + /// Shared by [`parse_function_def`](Self::parse_function_def) and + /// [`parse_class_def`](Self::parse_class_def). + fn parse_decorators( + &mut self, + decorators: impl IntoIterator, + ) -> Result, ParseError> { + decorators + .into_iter() + .map(|d| self.parse_expression(d.expression)) + .collect() + } + + /// Parses a `class Foo: ...` definition into a [`Node::ClassDef`]. + /// + /// The class body is modelled as a synthetic zero-argument function (like + /// CPython's class-body code object): the class statements are collected in + /// source order into a [`RawFunctionDef`] that, when prepared and compiled, + /// runs in its own scope and returns the assembled `Class`. Methods become + /// nested `FunctionDef`s; class variables become `Assign`s with arbitrary + /// expressions (`name = ` / `name: T = `). Every member name is + /// recorded in `members`, in source order, for namespace assembly. + /// + /// `pass` and `...` are ignored; a leading docstring becomes a `__doc__` + /// member, and annotated names a stringized `__annotations__`. Class + /// decorators are supported (enclosing scope, applied bottom-up); + /// inheritance, function/method decorators, and anything else in the body + /// are rejected as not-implemented, reserving the syntax for later. + fn parse_class_def(&mut self, class: ast::StmtClassDef) -> Result { + let position = self.class_keyword_range(&class); + let decorators = self.parse_decorators(class.decorator_list)?; + // `class.arguments` carries base classes and metaclass keywords. + if let Some(arguments) = &class.arguments { + // CPython rejects the repeat before it would consider the metaclass. + self.check_repeated_keywords(&arguments.keywords)?; + if !arguments.args.is_empty() || !arguments.keywords.is_empty() { + return Err(ParseError::not_implemented( + "class inheritance and metaclasses", + position, + )); + } + } + + let name = self.identifier(&class.name.id, class.name.range); + // The class-body statements (in source order) and the member names they + // bind. Both methods and class vars are ordinary bindings of the body + // scope; `members` records the order so the compiler can assemble the + // namespace dict from the body's locals. + let mut body = Vec::new(); + let mut members = Vec::new(); + // `(name, "source text")` pairs assembled into `__annotations__` below; + // always stringized (PEP 563). See `limitations/typing.md`. + let mut annotations: Vec = Vec::new(); + + // CPython stores the class docstring as a real `__doc__` entry in the + // class dict (`None` when absent), so synthesize a `__doc__ = ` binding as the first class-body statement — `Foo.__doc__` and + // `obj.__doc__` then work through ordinary namespace lookup. An explicit + // `__doc__ = ...` later in the body overwrites it, as in CPython. + let doc_target = Identifier::new(self.interner.intern("__doc__"), self.convert_range(class.name.range)); + let mut doc_value = ExprLoc::new(self.convert_range(class.name.range), Expr::Literal(Literal::None)); + + for (i, stmt) in class.body.into_iter().enumerate() { + match stmt { + Stmt::FunctionDef(function) => { + if !function.decorator_list.is_empty() { + return Err(ParseError::not_implemented( + "method decorators (classmethod/staticmethod/property)", + self.convert_range(function.range), + )); + } + // Parameter defaults evaluate in the class-body scope, so a + // walrus target there would become a class member (see + // `reject_class_body_walrus`); walrus in the method *body* + // binds in the method scope and is fine. + for param in function.parameters.iter_non_variadic_params() { + if let Some(default) = ¶m.default { + self.reject_class_body_walrus(default)?; + } + } + let (method, decorators) = self.parse_function_def(function)?; + // Rejected above, so a decorated method never reaches the + // class namespace — where a decorator's return value, not a + // function, would end up bound as the member. + debug_assert!(decorators.is_empty(), "method decorators are rejected above"); + members.push(method.name); + body.push(Node::FunctionDef { + def: method, + decorators, + }); + } + // `name = ` — a class-level variable. + Stmt::Assign(ast::StmtAssign { + targets, value, range, .. + }) => { + let [ + AstExpr::Name(ast::ExprName { + id, range: name_range, .. + }), + ] = targets.as_slice() + else { + return Err(ParseError::not_implemented( + "complex class variable targets (only `name = ` is allowed)", + self.convert_range(range), + )); + }; + let ident = self.identifier(id, *name_range); + self.parse_class_var(ident, *value, &mut members, &mut body)?; + } + // `name: T [= ]` — an annotated class-level name. The + // annotation is recorded (stringized) in `__annotations__`; a + // value additionally makes it a class variable. A bare `name: T` + // records the annotation but binds no value (matching CPython). + Stmt::AnnAssign(ast::StmtAnnAssign { + target, + mut annotation, + value, + range, + .. + }) => { + if let AstExpr::Name(ast::ExprName { + id, range: name_range, .. + }) = *target + { + let ident = self.identifier(&id, name_range); + annotations.push(self.parse_class_annotation(ident, &mut annotation)?); + if let Some(value) = value { + self.parse_class_var(ident, *value, &mut members, &mut body)?; + } + } else if value.is_some() { + // Complex target with a value (`x.y: T = v`) is unsupported; + // a bare complex annotation (`x.y: T`) stores nothing in + // CPython either, so it is ignored. CPython does still + // evaluate the target expression (`undefined.attr: T` raises + // `NameError`) where Monty drops it — see + // `limitations/typing.md`. + return Err(ParseError::not_implemented( + "complex class variable targets (only `name = ` is allowed)", + self.convert_range(range), + )); + } + } + // `pass` and `...` (the common `class C: ...` stub idiom) are + // no-ops. A leading string literal is the class docstring and + // becomes the synthesized `__doc__` value; later bare string + // literals are no-ops. + Stmt::Pass(_) => {} + Stmt::Expr(ast::StmtExpr { value, .. }) + if matches!(*value, AstExpr::StringLiteral(_) | AstExpr::EllipsisLiteral(_)) => + { + if i == 0 && matches!(*value, AstExpr::StringLiteral(_)) { + doc_value = self.parse_expression(*value)?; + } + } + other => { + return Err(ParseError::not_implemented( + "class bodies containing anything other than methods and simple class variables", + self.convert_range(other.range()), + )); + } + } + } + + // The synthesized `__doc__` binding runs first (like CPython's docstring + // store); the namespace assembly loads final local values, so an explicit + // `__doc__` member still wins. + members.insert(0, doc_target); + body.insert( + 0, + Node::Assign { + target: doc_target, + object: doc_value, + }, + ); + + // Last statement so the values are assembled after all members exist. + // Always present (empty dict) to match `Cls.__annotations__ == {}`. + let annotations_target = Identifier::new(self.interner.intern("__annotations__"), position); + let body_binds_annotations = members.iter().any(|m| m.name_id == annotations_target.name_id); + if body_binds_annotations && !annotations.is_empty() { + // Being last, the synthetic assignment would clobber the body's own + // binding and lose these entries. CPython stores into whatever the name + // holds instead — merging into a dict, `TypeError` otherwise. + return Err(ParseError::not_implemented( + "assigning `__annotations__` in a class body with annotated names", + position, + )); + } + // With nothing to store, the body's own binding stands — synthesizing an + // empty dict over it would break class bodies CPython accepts. + if !body_binds_annotations { + members.push(annotations_target); + body.push(Node::Assign { + target: annotations_target, + object: ExprLoc::new(position, Expr::Dict(annotations)), + }); + } + + // Wrap the body statements in a synthetic zero-arg function. The class + // name's `name_id` is reused for nicer tracebacks; this function is never + // registered in any scope (`prepare_class_def` prepares it directly, + // without binding a function name). + let body = RawFunctionDef { + name, + signature: ParsedSignature::default(), + body, + is_async: false, + }; + + Ok(Node::ClassDef { + name, + body, + members, + decorators, + position, + }) + } + + /// The range of a `class` statement from the `class` keyword, excluding + /// decorators: ruff's `StmtClassDef::range` starts at the first decorator + /// where CPython starts at the keyword, which would otherwise show decorator + /// lines in a class-body traceback frame. + /// + /// The keyword is located from the lexer's tokens rather than by searching the + /// source text, so a `class` inside a comment or a decorator's string argument + /// cannot be mistaken for it. Offsets are ascending, so this class's keyword is + /// simply the first one at or after its final decorator. + fn class_keyword_range(&self, class: &ast::StmtClassDef) -> CodeRange { + let start = match class.decorator_list.last() { + // Undecorated: ruff's range already starts at the keyword. + None => class.range.start().into(), + Some(last_decorator) => { + let after_decorators = last_decorator.range.end(); + let index = self.class_keyword_offsets.partition_point(|&o| o < after_decorators); + // Bounded by the name so a malformed lookup cannot borrow a later + // class's keyword; the fallback is unreachable (a decorated class + // always has a keyword in this window) but avoids a panic path. + self.class_keyword_offsets + .get(index) + .filter(|&&offset| offset < class.name.range.start()) + .map_or_else(|| class.range.start().into(), |&offset| offset.into()) + } + }; + CodeRange { + filename: self.filename_id, + start_byte: start, + end_byte: class.range.end().into(), + } + } + + /// Builds the `'name': 'annotation'` pair for one annotated class-body name. + /// + /// The annotation is stringized rather than evaluated (see + /// `limitations/typing.md`); [`stringize_annotation`] owns rendering it back + /// to the text CPython would store. + /// + /// The annotation never reaches [`Parser::parse_expression`], so the depth + /// check guarding stringization's two recursive passes is made here. + fn parse_class_annotation(&mut self, ident: Identifier, annotation: &mut AstExpr) -> Result { + self.check_expression_depth(annotation)?; + let ann_range = annotation.range(); + let ann_id = self.interner.intern(&stringize_annotation(annotation)); + Ok(DictItem::Pair( + ExprLoc::new(ident.position, Expr::Literal(Literal::Str(ident.name_id))), + ExprLoc::new(self.convert_range(ann_range), Expr::Literal(Literal::Str(ann_id))), + )) + } + + /// Parses a class-variable value and records the binding: rejects class-scope + /// walrus, parses the value expression, and appends the member / `Assign` pair + /// shared by the `Assign` and `AnnAssign` class-body arms. + fn parse_class_var( + &mut self, + ident: Identifier, + value: AstExpr, + members: &mut Vec, + body: &mut Vec, + ) -> Result<(), ParseError> { + self.reject_class_body_walrus(&value)?; + let object = self.parse_expression(value)?; + members.push(ident); + body.push(Node::Assign { target: ident, object }); + Ok(()) + } + + /// Rejects `:=` that binds in a class-body scope (in class-variable values + /// and method parameter defaults). + /// + /// A walrus target in such an expression binds in the class body, so in + /// CPython it becomes a class member (`class C: x = (y := 5)` gives `C.y`). + /// Monty's namespace assembly only records directly-assigned names, so the + /// binding would be silently dropped — reject the syntax until class-scope + /// walrus is implemented. A walrus inside a lambda *body* binds in the + /// lambda's own scope and is allowed (see [`contains_class_scope_walrus`]). + /// The depth check comes first: the search recurses over the raw ruff AST, + /// which `parse_expression` has not yet bounded. + fn reject_class_body_walrus(&self, expr: &AstExpr) -> Result<(), ParseError> { + self.check_expression_depth(expr)?; + if contains_class_scope_walrus(expr) { + Err(ParseError::not_implemented( + "assignment expressions (`:=`) in class bodies", + self.convert_range(expr.range()), + )) + } else { + Ok(()) + } + } + + /// `lhs = rhs` — parses a single-target assignment into the appropriate `Node` variant. + /// + /// Dispatches on the shape of `lhs` by delegating to `parse_assign_target`, then wraps + /// the resulting `AssignTarget` together with the parsed RHS into one of the flat + /// per-shape node variants (`Assign`/`SubscriptAssign`/`AttrAssign`/`UnpackAssign`). + /// Handles simple assignments (`x = value`), subscript assignments (`dict[key] = value`), + /// attribute assignments (`obj.attr = value`), and tuple/list unpacking (`a, b = value`). + fn parse_assignment(&mut self, lhs: AstExpr, rhs: AstExpr) -> Result { + // Parse the target first so sub-expression evaluation order (container, index, ...) + // stays consistent with per-shape parsing done before the refactor. + let target = self.parse_assign_target(lhs)?; + let rhs = self.parse_expression(rhs)?; + let node = match target { + AssignTarget::Name(target) => Node::Assign { target, object: rhs }, + AssignTarget::Subscript { + target, + index, + target_position, + } => Node::SubscriptAssign { + target, + index, + value: rhs, + target_position, + }, + AssignTarget::Attr { + object, + attr, + target_position, + } => Node::AttrAssign { + object, + attr, + target_position, + value: rhs, + }, + AssignTarget::Unpack { + targets, + targets_position, + } => Node::UnpackAssign { + targets, + targets_position, + object: rhs, + }, + }; + Ok(node) + } + + /// Parses a chained assignment like `a = b = c = value` into a `Node::ChainAssign`. + /// + /// The right-hand side `rhs` is evaluated once, and each entry in `targets` receives + /// the resulting value in left-to-right order. Each target may be any valid assignment + /// LHS — a name, subscript, attribute, or unpack pattern — mirroring the shapes handled + /// by `parse_assignment`. + fn parse_chained_assignment(&mut self, targets: Vec, rhs: AstExpr) -> Result { + let parsed_targets = targets + .into_iter() + .map(|t| self.parse_assign_target(t)) + .collect::, _>>()?; + let object = self.parse_expression(rhs)?; + Ok(Node::ChainAssign { + targets: parsed_targets, + object, + }) + } + + /// Parses a single assignment target expression into an `AssignTarget`. + /// + /// Central dispatch for assignment-target shapes, shared by `parse_assignment` + /// (for single-target and annotation-driven assignments) and + /// `parse_chained_assignment` (for `a = b = value`). Keeping shape dispatch in one + /// place means adding a new target form only requires updating this function and + /// its downstream consumers (prepare and compiler). + fn parse_assign_target(&mut self, lhs: AstExpr) -> Result { + match lhs { + AstExpr::Subscript(ast::ExprSubscript { + value, slice, range, .. + }) => Ok(AssignTarget::Subscript { + target: self.parse_expression(*value)?, + index: self.parse_expression(*slice)?, + target_position: self.convert_range(range), + }), + AstExpr::Attribute(ast::ExprAttribute { value, attr, range, .. }) => Ok(AssignTarget::Attr { + object: self.parse_expression(*value)?, + attr: EitherStr::Interned(self.interner.intern(attr.id())), + target_position: self.convert_range(range), + }), + AstExpr::Tuple(ast::ExprTuple { elts, range, .. }) | AstExpr::List(ast::ExprList { elts, range, .. }) => { + let targets_position = self.convert_range(range); + let targets = elts + .into_iter() + .map(|e| self.parse_unpack_target(e)) + .collect::, _>>()?; + check_single_starred(&targets, targets_position)?; + Ok(AssignTarget::Unpack { + targets, + targets_position, + }) + } + AstExpr::Starred(ast::ExprStarred { range, .. }) => Err(starred_root_target(self.convert_range(range))), + other => Ok(AssignTarget::Name(self.parse_identifier(other)?)), + } + } + + /// Parses an expression from the ruff AST into Monty's ExprLoc representation. + /// + /// Includes depth tracking to prevent stack overflow from deeply nested structures. + /// Matches CPython's limit of 200 for nested parentheses. + fn parse_expression(&mut self, expression: AstExpr) -> Result { + self.decr_depth_remaining(|| expression.range())?; + let result = self.parse_expression_impl(expression); + self.depth_remaining += 1; + result + } + + fn parse_expression_impl(&mut self, expression: AstExpr) -> Result { + match expression { + AstExpr::BoolOp(ast::ExprBoolOp { op, values, range, .. }) => { + // Handle chained boolean operations like `a and b and c` by right-folding + // into nested binary operations: `a and (b and c)`. + // + // Ruff hands the operands over as a flat `Vec`, but the fold + // produces a right-nested `Expr::Op` tree that the prepare and + // compile phases walk recursively. Count each fold step against + // the same depth budget that bounds explicitly nested source so + // a long flat chain cannot overflow the host's native stack + // downstream. The budget is restored once the fold completes. + let rust_op = convert_bool_op(op); + let position = self.convert_range(range); + let mut values_iter = values.into_iter().rev(); + + // Start with the rightmost value + let last_value = values_iter.next().expect("Expected at least one value in boolean op"); + let mut result = self.parse_expression(last_value)?; + + // Fold from right to left + let mut levels: u16 = 0; + for value in values_iter { + self.decr_depth_remaining(|| value.range())?; + levels += 1; + let left = Box::new(self.parse_expression(value)?); + result = ExprLoc::new( + position, + Expr::Op { + left, + op: rust_op.clone(), + right: Box::new(result), + }, + ); + } + self.depth_remaining += levels; + Ok(result) + } + AstExpr::Named(ast::ExprNamed { + target, value, range, .. + }) => { + let target_ident = self.parse_identifier(*target)?; + let value_expr = self.parse_expression(*value)?; + Ok(ExprLoc::new( + self.convert_range(range), + Expr::Named { + target: target_ident, + value: Box::new(value_expr), + }, + )) + } + AstExpr::BinOp(ast::ExprBinOp { + left, op, right, range, .. + }) => { + let left = Box::new(self.parse_expression(*left)?); + let right = Box::new(self.parse_expression(*right)?); + Ok(ExprLoc { + position: self.convert_range(range), + expr: Expr::Op { + left, + op: convert_op(op), + right, + }, + }) + } + AstExpr::UnaryOp(ast::ExprUnaryOp { op, operand, range, .. }) => match op { + UnaryOp::Not => { + let operand = Box::new(self.parse_expression(*operand)?); + Ok(ExprLoc::new(self.convert_range(range), Expr::Not(operand))) + } + UnaryOp::USub => { + let operand = Box::new(self.parse_expression(*operand)?); + Ok(ExprLoc::new(self.convert_range(range), Expr::UnaryMinus(operand))) + } + UnaryOp::UAdd => { + let operand = Box::new(self.parse_expression(*operand)?); + Ok(ExprLoc::new(self.convert_range(range), Expr::UnaryPlus(operand))) + } + UnaryOp::Invert => { + let operand = Box::new(self.parse_expression(*operand)?); + Ok(ExprLoc::new(self.convert_range(range), Expr::UnaryInvert(operand))) + } + }, + AstExpr::Lambda(ast::ExprLambda { + parameters, + body, + range, + .. + }) => { + let position = self.convert_range(range); + + // Intern the lambda name + let name_id = self.interner.intern(""); + + // Parse lambda parameters (similar to function parameters) + let signature = if let Some(params) = parameters { + // Parse positional-only parameters (before /) + let pos_args = self.parse_params_with_defaults(¶ms.posonlyargs)?; + + // Parse positional-or-keyword parameters + let args = self.parse_params_with_defaults(¶ms.args)?; + + // Parse *args + let var_args = params.vararg.as_ref().map(|p| self.interner.intern(&p.name.id)); + + // Parse keyword-only parameters (after * or *args) + let kwargs = self.parse_params_with_defaults(¶ms.kwonlyargs)?; + + // Parse **kwargs + let var_kwargs = params.kwarg.as_ref().map(|p| self.interner.intern(&p.name.id)); + + ParsedSignature { + pos_args, + args, + var_args, + kwargs, + var_kwargs, + } + } else { + // No parameters (e.g., `lambda: 42`) + ParsedSignature::default() + }; + + // Parse the body expression + let body = Box::new(self.parse_expression(*body)?); + + Ok(ExprLoc::new( + position, + Expr::LambdaRaw { + name_id, + signature, + body, + }, + )) + } + AstExpr::If(ast::ExprIf { + test, + body, + orelse, + range, + .. + }) => Ok(ExprLoc::new( + self.convert_range(range), + Expr::IfElse { + test: Box::new(self.parse_expression(*test)?), + body: Box::new(self.parse_expression(*body)?), + orelse: Box::new(self.parse_expression(*orelse)?), + }, + )), + AstExpr::Dict(ast::ExprDict { items, range, .. }) => { + let position = self.convert_range(range); + let mut dict_items = Vec::new(); + for ast::DictItem { key, value } in items { + // key is Option - None represents ** unpacking (PEP 448) + if let Some(key_expr_ast) = key { + let key_expr = self.parse_expression(key_expr_ast)?; + let value_expr = self.parse_expression(value)?; + dict_items.push(DictItem::Pair(key_expr, value_expr)); + } else { + // **expr unpack in a dict literal: later keys silently win + let unpack_expr = self.parse_expression(value)?; + dict_items.push(DictItem::Unpack(unpack_expr)); + } + } + Ok(ExprLoc::new(position, Expr::Dict(dict_items))) + } + AstExpr::Set(ast::ExprSet { elts, range, .. }) => { + let mut items = Vec::new(); + for e in elts { + items.push(self.parse_sequence_item(e)?); + } + Ok(ExprLoc::new(self.convert_range(range), Expr::Set(items))) + } + AstExpr::ListComp(ast::ExprListComp { + elt, generators, range, .. + }) => { + let elt = Box::new(self.parse_expression(*elt)?); + let generators = self.parse_comprehension_generators(generators)?; + Ok(ExprLoc::new( + self.convert_range(range), + Expr::ListComp { + elt, + generators, + captured_slots: Vec::new(), + }, + )) + } + AstExpr::SetComp(ast::ExprSetComp { + elt, generators, range, .. + }) => { + let elt = Box::new(self.parse_expression(*elt)?); + let generators = self.parse_comprehension_generators(generators)?; + Ok(ExprLoc::new( + self.convert_range(range), + Expr::SetComp { + elt, + generators, + captured_slots: Vec::new(), + }, + )) + } + AstExpr::DictComp(ast::ExprDictComp { + key, + value, + generators, + range, + .. + }) => { + // Ruff models the key as `Option>` to represent the + // invalid `{**v for ...}` form during error recovery. Real Python + // forbids dict unpacking in a comprehension, so ruff also emits a + // syntax error for that case; treat `None` here as the same syntax + // error to keep behavior consistent if it ever leaks through. + let key = key.ok_or_else(|| { + ParseError::syntax( + "dict unpacking is not allowed in dict comprehension".to_string(), + self.convert_range(range), + ) + })?; + let key = Box::new(self.parse_expression(*key)?); + let value = Box::new(self.parse_expression(*value)?); + let generators = self.parse_comprehension_generators(generators)?; + Ok(ExprLoc::new( + self.convert_range(range), + Expr::DictComp { + key, + value, + generators, + captured_slots: Vec::new(), + }, + )) + } + AstExpr::Generator(ast::ExprGenerator { + elt, generators, range, .. + }) => { + // TODO: When proper generators are implemented, this should produce + // Expr::Generator instead of Expr::ListComp. Currently we treat generator + // expressions as list comprehensions since we don't have generator support. + let elt = Box::new(self.parse_expression(*elt)?); + let generators = self.parse_comprehension_generators(generators)?; + Ok(ExprLoc::new( + self.convert_range(range), + Expr::ListComp { + elt, + generators, + captured_slots: Vec::new(), + }, + )) + } + AstExpr::Await(a) => { + let value = self.parse_expression(*a.value)?; + Ok(ExprLoc::new(self.convert_range(a.range), Expr::Await(Box::new(value)))) + } + AstExpr::Yield(y) => Err(ParseError::not_implemented( + "yield expressions", + self.convert_range(y.range), + )), + AstExpr::YieldFrom(y) => Err(ParseError::not_implemented( + "yield from expressions", + self.convert_range(y.range), + )), + AstExpr::Compare(ast::ExprCompare { + ops, operands, range, .. + }) => { + let position = self.convert_range(range); + let ops_vec = ops.into_vec(); + // `operands` holds every operand in source order, leftmost first. + let mut operands = operands.into_vec().into_iter(); + let left = operands.next().expect("a comparison has a left operand"); + let comparators_vec: Vec = operands.collect(); + + // Simple case: single comparison (most common) + if ops_vec.len() == 1 { + return Ok(ExprLoc::new( + position, + Expr::CmpOp { + left: Box::new(self.parse_expression(left)?), + op: convert_compare_op(ops_vec.into_iter().next().unwrap()), + right: Box::new(self.parse_expression(comparators_vec.into_iter().next().unwrap())?), + }, + )); + } + + // Chain comparison: transform to nested And expressions + self.parse_chain_comparison(left, ops_vec, comparators_vec, position) + } + AstExpr::Call(call) => { + let position = self.convert_range(call.range()); + let ast::ExprCall { func, arguments, .. } = call; + let ast::Arguments { args, keywords, .. } = arguments; + let keywords_vec: Vec<_> = keywords.into_iter().collect(); + self.check_repeated_keywords(&keywords_vec)?; + + // Detect whether we need the generalized path (PEP 448): + // - multiple *args unpacks, OR + // - positional argument after *args, OR + // - multiple **kwargs unpacks + let needs_generalized = Self::needs_generalized_call(&args, &keywords_vec); + + let args = if needs_generalized { + self.parse_generalized_call_args(args, keywords_vec)? + } else { + self.parse_simple_call_args(args, keywords_vec)? + }; + match *func { + AstExpr::Name(ast::ExprName { id, range, .. }) => { + // Always create Callable::Name — builtin resolution happens in + // the prepare phase with scope awareness, so local assignments + // can shadow builtins. + let ident = self.identifier(&id, range); + let callable = Callable::Name(ident); + Ok(ExprLoc::new( + position, + Expr::Call { + callable, + args: Box::new(args), + }, + )) + } + AstExpr::Attribute(ast::ExprAttribute { value, attr, .. }) => { + let object = Box::new(self.parse_expression(*value)?); + Ok(ExprLoc::new( + position, + Expr::AttrCall { + object, + attr: EitherStr::Interned(self.interner.intern(attr.id())), + args: Box::new(args), + }, + )) + } + other => { + // Handle arbitrary expression as callable (e.g., lambda calls) + let callable = Box::new(self.parse_expression(other)?); + Ok(ExprLoc::new( + position, + Expr::IndirectCall { + callable, + args: Box::new(args), + }, + )) + } + } + } + AstExpr::FString(ast::ExprFString { value, range, .. }) => self.parse_fstring(&value, range), + AstExpr::TString(t) => Err(ParseError::not_implemented( + "template strings (t-strings)", + self.convert_range(t.range), + )), + AstExpr::StringLiteral(ast::ExprStringLiteral { value, range, .. }) => { + let string_id = self.interner.intern(&value.to_string()); + Ok(ExprLoc::new( + self.convert_range(range), + Expr::Literal(Literal::Str(string_id)), + )) + } + AstExpr::BytesLiteral(ast::ExprBytesLiteral { value, range, .. }) => { + let bytes: Cow<'_, [u8]> = Cow::from(&value); + let bytes_id = self.interner.intern_bytes(&bytes); + Ok(ExprLoc::new( + self.convert_range(range), + Expr::Literal(Literal::Bytes(bytes_id)), + )) + } + AstExpr::NumberLiteral(ast::ExprNumberLiteral { value, range, .. }) => { + let position = self.convert_range(range); + let const_value = match value { + Number::Int(i) => { + if let Some(i) = i.as_i64() { + Literal::Int(i) + } else { + // Integer too large for i64, parse string representation as BigInt. + // Handles radix prefixes (0x, 0o, 0b) and underscores. + let bi = parse_int_literal(&i.to_string(), position)?; + let long_int_id = self.interner.intern_long_int(bi); + Literal::LongInt(long_int_id) + } + } + Number::Float(f) => Literal::Float(f), + // An imaginary literal has no real part; `1+2j` is a `BinOp`. + Number::Complex { imag, .. } => Literal::Complex(imag), + }; + Ok(ExprLoc::new(position, Expr::Literal(const_value))) + } + AstExpr::BooleanLiteral(ast::ExprBooleanLiteral { value, range, .. }) => Ok(ExprLoc::new( + self.convert_range(range), + Expr::Literal(Literal::Bool(value)), + )), + AstExpr::NoneLiteral(ast::ExprNoneLiteral { range, .. }) => { + Ok(ExprLoc::new(self.convert_range(range), Expr::Literal(Literal::None))) + } + AstExpr::EllipsisLiteral(ast::ExprEllipsisLiteral { range, .. }) => Ok(ExprLoc::new( + self.convert_range(range), + Expr::Literal(Literal::Ellipsis), + )), + AstExpr::Attribute(ast::ExprAttribute { value, attr, range, .. }) => { + let object = Box::new(self.parse_expression(*value)?); + let position = self.convert_range(range); + Ok(ExprLoc::new( + position, + Expr::AttrGet { + object, + attr: EitherStr::Interned(self.interner.intern(attr.id())), + }, + )) + } + AstExpr::Subscript(ast::ExprSubscript { + value, slice, range, .. + }) => { + let object = Box::new(self.parse_expression(*value)?); + let index = Box::new(self.parse_expression(*slice)?); + Ok(ExprLoc::new( + self.convert_range(range), + Expr::Subscript { object, index }, + )) + } + AstExpr::Starred(s) => Err(ParseError::not_implemented( + "starred expressions (*expr)", + self.convert_range(s.range), + )), + AstExpr::Name(ast::ExprName { id, range, .. }) => { + let position = self.convert_range(range); + // Always create Expr::Name — builtin resolution happens in the prepare + // phase with scope awareness, so local assignments can shadow builtins. + let expr = Expr::Name(self.identifier(&id, range)); + Ok(ExprLoc::new(position, expr)) + } + AstExpr::List(ast::ExprList { elts, range, .. }) => { + let mut items = Vec::new(); + for e in elts { + items.push(self.parse_sequence_item(e)?); + } + Ok(ExprLoc::new(self.convert_range(range), Expr::List(items))) + } + AstExpr::Tuple(ast::ExprTuple { elts, range, .. }) => { + let mut items = Vec::new(); + for e in elts { + items.push(self.parse_sequence_item(e)?); + } + Ok(ExprLoc::new(self.convert_range(range), Expr::Tuple(items))) + } + AstExpr::Slice(ast::ExprSlice { + lower, + upper, + step, + range, + .. + }) => { + let lower = lower.map(|e| self.parse_expression(*e)).transpose()?; + let upper = upper.map(|e| self.parse_expression(*e)).transpose()?; + let step = step.map(|e| self.parse_expression(*e)).transpose()?; + Ok(ExprLoc::new( + self.convert_range(range), + Expr::Slice { + lower: lower.map(Box::new), + upper: upper.map(Box::new), + step: step.map(Box::new), + }, + )) + } + AstExpr::IpyEscapeCommand(i) => Err(ParseError::not_implemented( + "IPython escape commands", + self.convert_range(i.range), + )), + } + } + + /// Converts an AST expression into a `SequenceItem` for list/tuple/set literals. + /// + /// A `Starred` node becomes `SequenceItem::Unpack`; all other expressions + /// become `SequenceItem::Value`. This is the entry point for PEP 448 unpack + /// handling in collection literals. + fn parse_sequence_item(&mut self, expr: AstExpr) -> Result { + if let AstExpr::Starred(ast::ExprStarred { value, .. }) = expr { + Ok(SequenceItem::Unpack(self.parse_expression(*value)?)) + } else { + Ok(SequenceItem::Value(self.parse_expression(expr)?)) + } + } + + /// Detects whether a function call needs the generalized `GeneralizedCall` path. + /// + /// Returns `true` when the call has: + /// - More than one `*unpack` among positional args, OR + /// - A plain positional arg following a `*unpack`, OR + /// - More than one `**unpack` among keyword args. + /// + /// In all these cases the simple `ArgsKargs` representation is insufficient + /// and `parse_generalized_call_args` must be used instead. + fn needs_generalized_call(args: &[AstExpr], keywords: &[Keyword]) -> bool { + let mut seen_star = false; + for arg in args { + match arg { + AstExpr::Starred(_) => { + if seen_star { + return true; // second *unpack + } + seen_star = true; + } + _ => { + if seen_star { + return true; // positional after *unpack + } + } + } + } + // Multiple **kwargs unpacks? + keywords.iter().filter(|k| k.arg.is_none()).count() > 1 + } + + /// Parses function call args for the simple case (at most one * and one **). + /// + /// Returns `ArgExprs::new_with_var_kwargs(...)` as before, preserving the + /// fast path for the vast majority of function calls. + fn parse_simple_call_args( + &mut self, + args: impl IntoIterator, + keywords_vec: Vec, + ) -> Result { + let mut positional_args = Vec::new(); + let mut var_args_expr: Option = None; + + for arg_expr in args { + match arg_expr { + AstExpr::Starred(ast::ExprStarred { value, .. }) => { + var_args_expr = Some(self.parse_expression(*value)?); + } + other => { + positional_args.push(self.parse_expression(other)?); + } + } + } + let (kwargs, var_kwargs) = self.parse_keywords(keywords_vec)?; + Ok(ArgExprs::new_with_var_kwargs( + positional_args, + var_args_expr, + kwargs, + var_kwargs, + )) + } + + /// Parses function call args for the PEP 448 generalized case. + /// + /// Builds `Vec` and `Vec` preserving the full order of + /// positional and keyword arguments so the compiler can emit correct + /// `ListAppend`/`ListExtend`/`DictMerge` sequences. + fn parse_generalized_call_args( + &mut self, + args: impl IntoIterator, + keywords_vec: Vec, + ) -> Result { + let mut call_args = Vec::new(); + for arg_expr in args { + match arg_expr { + AstExpr::Starred(ast::ExprStarred { value, .. }) => { + call_args.push(CallArg::Unpack(self.parse_expression(*value)?)); + } + other => { + call_args.push(CallArg::Value(self.parse_expression(other)?)); + } + } + } + + let mut call_kwargs = Vec::new(); + for kwarg in keywords_vec { + if let Some(key) = kwarg.arg { + let key_ident = self.identifier(&key.id, key.range); + let value = self.parse_expression(kwarg.value)?; + call_kwargs.push(CallKwarg::Named(Kwarg { key: key_ident, value })); + } else { + let unpack_expr = self.parse_expression(kwarg.value)?; + call_kwargs.push(CallKwarg::Unpack(unpack_expr)); + } + } + + Ok(ArgExprs::new_generalized(call_args, call_kwargs)) + } + + /// Rejects `f(x=1, x=2)` as CPython's compiler does, pointing at the repeat. + /// + /// ruff reports this from its semantic checker, which Monty does not run, so + /// the parser alone would accept the call. + fn check_repeated_keywords(&self, keywords: &[Keyword]) -> Result<(), ParseError> { + let mut seen = AHashSet::with_capacity(keywords.len()); + keywords + .iter() + .filter_map(|keyword| keyword.arg.as_ref().map(|arg| (arg.id.as_str(), keyword.range()))) + .find(|(name, _)| !seen.insert(*name)) + .map_or(Ok(()), |(name, range)| { + Err(ParseError::syntax( + format!("keyword argument repeated: {name}"), + self.convert_range(range), + )) + }) + } + + /// Parses keyword arguments, separating regular kwargs from var_kwargs (`**expr`). + /// + /// Returns `(kwargs, var_kwargs)` where kwargs is a vec of named keyword arguments + /// and var_kwargs is an optional expression for `**expr` unpacking. + fn parse_keywords(&mut self, keywords: Vec) -> Result<(Vec, Option), ParseError> { + let mut kwargs = Vec::new(); + let mut var_kwargs = None; + + for kwarg in keywords { + if let Some(key) = kwarg.arg { + // Regular kwarg: key=value + let key = self.identifier(&key.id, key.range); + let value = self.parse_expression(kwarg.value)?; + kwargs.push(Kwarg { key, value }); + } else { + // Var kwargs: **expr + if var_kwargs.is_some() { + return Err(ParseError::not_implemented( + "multiple **kwargs unpacking", + self.convert_range(kwarg.range), + )); + } + var_kwargs = Some(self.parse_expression(kwarg.value)?); + } + } + + Ok((kwargs, var_kwargs)) + } + + fn parse_identifier(&mut self, ast: AstExpr) -> Result { + match ast { + AstExpr::Name(ast::ExprName { id, range, .. }) => Ok(self.identifier(&id, range)), + other => Err(ParseError::syntax( + format!("Expected name, got {}", describe_expr_kind(&other)), + self.convert_range(other.range()), + )), + } + } + + /// Parses a chain comparison expression like `a < b < c < d`. + /// + /// Chain comparisons evaluate each intermediate value only once and short-circuit + /// on the first false result. This creates an `Expr::ChainCmp` node which is + /// compiled to bytecode using stack manipulation (Dup, Rot) rather than + /// temporary variables, avoiding namespace pollution. + fn parse_chain_comparison( + &mut self, + left: AstExpr, + ops: Vec, + comparators: Vec, + position: CodeRange, + ) -> Result { + let left_expr = self.parse_expression(left)?; + let comparisons = ops + .into_iter() + .zip(comparators) + .map(|(op, cmp)| Ok((convert_compare_op(op), self.parse_expression(cmp)?))) + .collect::, ParseError>>()?; + + Ok(ExprLoc::new( + position, + Expr::ChainCmp { + left: Box::new(left_expr), + comparisons, + }, + )) + } + + /// Parses the outermost target of a `for`, `with ... as` or comprehension. + /// + /// A bare `*a` is only valid inside a tuple/list target, so it is rejected + /// here before [`Self::parse_unpack_target`] recurses into the elements. + fn parse_unpack_target_root(&mut self, ast: AstExpr) -> Result { + match ast { + AstExpr::Starred(ast::ExprStarred { range, .. }) => Err(starred_root_target(self.convert_range(range))), + other => self.parse_unpack_target(other), + } + } + + /// Parses an unpack target - either a single identifier or a nested tuple. + /// + /// Handles patterns like `a` (single variable), `a, b` (flat tuple), or `(a, b), c` (nested). + /// Includes depth tracking to prevent stack overflow from deeply nested structures. + fn parse_unpack_target(&mut self, ast: AstExpr) -> Result { + self.decr_depth_remaining(|| ast.range())?; + let result = self.parse_unpack_target_impl(ast); + self.depth_remaining += 1; + result + } + + fn parse_unpack_target_impl(&mut self, ast: AstExpr) -> Result { + match ast { + AstExpr::Name(ast::ExprName { id, range, .. }) => Ok(UnpackTarget::Name(self.identifier(&id, range))), + AstExpr::Tuple(ast::ExprTuple { elts, range, .. }) => { + let position = self.convert_range(range); + let targets = elts + .into_iter() + .map(|e| self.parse_unpack_target(e)) // Recursive call for nested tuples + .collect::, _>>()?; + if targets.is_empty() { + return Err(ParseError::syntax("empty tuple in unpack target", position)); + } + check_single_starred(&targets, position)?; + Ok(UnpackTarget::Tuple { targets, position }) + } + AstExpr::Starred(ast::ExprStarred { value, .. }) => { + // `*rest` captures into a list, which is then stored like any + // other target: `*a`, `*obj.x`, `*d[k]` and `*(a, b)` all work. + Ok(UnpackTarget::Starred(Box::new(self.parse_unpack_target(*value)?))) + } + AstExpr::List(ast::ExprList { elts, range, .. }) => { + // List unpacking target [a, b, *rest] - same as tuple + let position = self.convert_range(range); + let targets = elts + .into_iter() + .map(|e| self.parse_unpack_target(e)) + .collect::, _>>()?; + if targets.is_empty() { + return Err(ParseError::syntax("empty list in unpack target", position)); + } + check_single_starred(&targets, position)?; + Ok(UnpackTarget::Tuple { targets, position }) + } + AstExpr::Attribute(ast::ExprAttribute { value, attr, range, .. }) => Ok(UnpackTarget::Attr { + object: Box::new(self.parse_expression(*value)?), + attr: EitherStr::Interned(self.interner.intern(attr.id())), + position: self.convert_range(range), + }), + AstExpr::Subscript(ast::ExprSubscript { + value, slice, range, .. + }) => Ok(UnpackTarget::Subscript { + container: Box::new(self.parse_expression(*value)?), + index: Box::new(self.parse_expression(*slice)?), + position: self.convert_range(range), + }), + other => Err(ParseError::syntax( + format!("invalid unpacking target: {}", describe_expr_kind(&other)), + self.convert_range(other.range()), + )), + } + } + + fn identifier(&mut self, id: &Name, range: TextRange) -> Identifier { + let string_id = self.interner.intern(id); + Identifier::new(string_id, self.convert_range(range)) + } + + /// Parses function parameters with optional default values. + /// + /// Handles parameters like `a`, `b=10`, `c=None` by extracting the parameter + /// name and parsing any default expression. Default expressions are stored + /// as unevaluated AST and will be evaluated during the prepare phase. + fn parse_params_with_defaults(&mut self, params: &[ParameterWithDefault]) -> Result, ParseError> { + params + .iter() + .map(|p| { + let name = self.interner.intern(&p.parameter.name.id); + let default = match &p.default { + Some(expr) => Some(self.parse_expression((**expr).clone())?), + None => None, + }; + Ok(ParsedParam { name, default }) + }) + .collect() + } + + /// Parses comprehension generators (the `for ... in ... if ...` clauses). + /// + /// Each generator represents one `for` clause with zero or more `if` filters. + /// Multiple generators create nested iteration. Supports both single identifiers + /// (`for x in ...`) and tuple unpacking (`for x, y in ...`). + fn parse_comprehension_generators( + &mut self, + generators: impl IntoIterator, + ) -> Result, ParseError> { + generators + .into_iter() + .map(|comp| { + if comp.is_async { + return Err(ParseError::not_implemented( + "async comprehensions", + self.convert_range(comp.range), + )); + } + let target = self.parse_unpack_target_root(comp.target)?; + let iter = self.parse_expression(comp.iter)?; + let ifs = comp + .ifs + .into_iter() + .map(|cond| self.parse_expression(cond)) + .collect::, _>>()?; + Ok(Comprehension { target, iter, ifs }) + }) + .collect() + } + + /// Parses an f-string value into expression parts. + /// + /// F-strings in ruff AST are represented as `FStringValue`, whose parts are + /// either literal strings or `FString` interpolated sections. Each `FString` + /// contains `InterpolatedStringElements`. + fn parse_fstring(&mut self, value: &ast::FStringValue, range: TextRange) -> Result { + let mut parts = Vec::new(); + + for fstring_part in value { + match fstring_part { + ast::FStringPartRef::Literal(lit) => { + // Literal string segment - intern for use at runtime + let processed = lit.value.to_string(); + if !processed.is_empty() { + let string_id = self.interner.intern(&processed); + parts.push(FStringPart::Literal(string_id)); + } + } + ast::FStringPartRef::FString(fstring) => { + // Interpolated f-string section + for element in &fstring.elements { + let part = self.parse_fstring_element(element)?; + parts.push(part); + } + } + } + } + + // Optimization: if only one literal part, return as simple string literal + if parts.len() == 1 + && let FStringPart::Literal(string_id) = parts[0] + { + return Ok(ExprLoc::new( + self.convert_range(range), + Expr::Literal(Literal::Str(string_id)), + )); + } + + Ok(ExprLoc::new(self.convert_range(range), Expr::FString(parts))) + } + + /// Parses a single f-string element (literal or interpolation). + fn parse_fstring_element(&mut self, element: &InterpolatedStringElement) -> Result { + match element { + InterpolatedStringElement::Literal(lit) => { + // Intern the literal string for use at runtime + let processed = lit.value.to_string(); + let string_id = self.interner.intern(&processed); + Ok(FStringPart::Literal(string_id)) + } + InterpolatedStringElement::Interpolation(interp) => { + let expr = Box::new(self.parse_expression((*interp.expression).clone())?); + let format_spec = match &interp.format_spec { + Some(spec) => self.parse_format_spec(spec)?, + None => None, + }; + let mut conversion = convert_conversion_flag(interp.conversion); + // An explicit empty spec (`f"{x=:}"`) collapses to `None` in + // `parse_format_spec`, but — unlike the bare debug form + // (`f"{x=}"`), which defaults to `repr` — it must format with + // `str`. Mark the conversion `Str` so the compiler's repr + // default for debug forms is suppressed; this is exact because + // `format(x, "")` equals `str(x)` for builtins (the same + // equivalence the empty-spec collapse already relies on). + if interp.debug_text.is_some() + && matches!(conversion, ConversionFlag::None) + && interp.format_spec.is_some() + && format_spec.is_none() + { + conversion = ConversionFlag::Str; + } + // Extract debug prefix for `=` specifier (e.g., f'{a=}' -> "a=") + let debug_prefix = interp.debug_text.as_ref().map(|dt| { + let expr_text = &self.code[interp.expression.range()]; + self.interner + .intern(&format!("{}{}{}", dt.leading(), expr_text, dt.trailing())) + }); + Ok(FStringPart::Interpolation { + expr, + conversion, + format_spec, + debug_prefix, + }) + } + } + } + + /// Parses a format specification, which may contain nested interpolations. + /// + /// Specs with no interpolations take the fast path: their literal text is + /// concatenated, parsed, and bit-packed into a single `u64` carried inside + /// `FormatSpec::Static`. The compiler then drops this straight into the + /// constant pool with no further work, and no per-segment interning is + /// performed (the parsed spec is the only thing the bytecode needs). + /// + /// Two cases force a `FormatSpec::Dynamic`: + /// 1. Any nested interpolation (e.g. `f"{x:{width}}"`) — the spec must be + /// materialized at runtime. + /// 2. Valid but extreme specs whose width or precision exceed the compact + /// encoding (e.g. `f"{x:>1048576}"`). The concatenated literal text is + /// interned and emitted as a single-literal dynamic spec so the VM + /// re-parses it at runtime. + fn parse_format_spec( + &mut self, + spec: &ast::InterpolatedStringFormatSpec, + ) -> Result, ParseError> { + let has_interpolation = spec + .elements + .iter() + .any(|e| matches!(e, InterpolatedStringElement::Interpolation(_))); + + if has_interpolation { + let mut parts = Vec::with_capacity(spec.elements.len()); + for element in &spec.elements { + match element { + InterpolatedStringElement::Literal(lit) => { + let string_id = self.interner.intern(&lit.value); + parts.push(FStringPart::Literal(string_id)); + } + InterpolatedStringElement::Interpolation(interp) => { + let expr = Box::new(self.parse_expression((*interp.expression).clone())?); + let conversion = convert_conversion_flag(interp.conversion); + // Format specs within format specs are not allowed in Python, + // and debug_prefix doesn't apply to nested interpolations + parts.push(FStringPart::Interpolation { + expr, + conversion, + format_spec: None, + debug_prefix: None, + }); + } + } + } + Ok(Some(FormatSpec::Dynamic(parts))) + } else { + let static_spec: String = spec + .elements + .iter() + .filter_map(|e| match e { + InterpolatedStringElement::Literal(lit) => Some(&*lit.value), + InterpolatedStringElement::Interpolation(_) => None, + }) + .collect(); + // An empty spec (`f"{x:}"`) is identical to no spec (`f"{x}"`) for + // every builtin type — `format(x, "")` is `str(x)`. Emit no spec so + // the value takes the plain `str()` path rather than the default + // formatter, which diverges for some types (e.g. a bare float would + // otherwise go through `g`: `f"{1234567.0:}"` must be `"1234567.0"`, + // not `"1.23457e+06"`; a bool must be `"True"`, not `"1"`). + if static_spec.is_empty() { + return Ok(None); + } + match static_spec.parse::() { + Ok(parsed) => { + // A spec that does not round-trip stays text: `Decimal` parses its + // own grammar from `to_spec_string`, which would see `0<5` for `<05`. + if let Some(encoded) = encode_format_spec(&parsed) + && parsed.to_spec_string() == static_spec + { + Ok(Some(FormatSpec::Static(encoded))) + } else { + // Valid but too large for the compact encoding, or not in + // canonical form — re-parse the literal at runtime. + let string_id = self.interner.intern(&static_spec); + Ok(Some(FormatSpec::Dynamic(vec![FStringPart::Literal(string_id)]))) + } + } + // Two kinds of failing spec are deferred to the dynamic + // (runtime) path rather than rejected here: + // - one containing `%`, which may be a `strftime` string for a + // date/datetime value (only resolvable once the type is known); + // - one whose error CPython raises as a *runtime* `ValueError` + // with type-dependent or format-time wording (`Unknown format + // code`, grouping conflicts, missing precision) — see + // [`ParseFormatSpecError::defer_to_runtime`]. The VM re-parses + // the literal and raises the matching error. + // Genuinely-malformed specs and `usize` overflow still fail at + // compile time. + Err(err) if static_spec.contains('%') || err.defer_to_runtime() => { + let string_id = self.interner.intern(&static_spec); + Ok(Some(FormatSpec::Dynamic(vec![FStringPart::Literal(string_id)]))) + } + Err(err) => Err(ParseError::syntax(err.to_string(), self.convert_range(spec.range))), + } + } + } + + /// Interns dotted-import components and prefixes; rejects more than [`MAX_IMPORT_COMPONENTS`]. + fn import_path(&mut self, dotted: &str, position: CodeRange) -> Result<(StringId, Vec), ParseError> { + if dotted.split('.').nth(MAX_IMPORT_COMPONENTS).is_some() { + return Err(ParseError::syntax( + format!("dotted import has more than {MAX_IMPORT_COMPONENTS} components"), + position, + )); + } + let mut parts = dotted.split('.'); + let module_name = self.interner.intern(parts.next().unwrap_or_default()); + let mut end = dotted.find('.').unwrap_or(dotted.len()); + let submodules = parts + .map(|part| { + end += 1 + part.len(); + Submodule { + name: self.interner.intern(part), + path: self.interner.intern(&dotted[..end]), + } + }) + .collect(); + Ok((module_name, submodules)) + } + + fn convert_range(&self, range: TextRange) -> CodeRange { + code_range(self.filename_id, range) + } + + /// Decrements the depth remaining for nested parentheses. + /// Returns an error if the depth remaining goes to zero. + fn decr_depth_remaining(&mut self, get_range: impl FnOnce() -> TextRange) -> Result<(), ParseError> { + if let Some(depth_remaining) = self.depth_remaining.checked_sub(1) { + self.depth_remaining = depth_remaining; + Ok(()) + } else { + let position = self.convert_range(get_range()); + Err(ParseError::syntax("Source is too deeply nested", position)) + } + } + + /// Rejects an expression nested deeper than the remaining budget, without + /// consuming any of it — for callers that walk a raw ruff expression + /// recursively *before* [`Parser::parse_expression`] can bound it. + /// + /// Ruff builds deeply nested ASTs from flat source (long attribute chains) + /// without recursing itself, so such a walk can overflow the host stack at + /// compile time. The check stops descending once the budget is exhausted, so + /// its own depth is bounded by [`MAX_NESTING_DEPTH`]. + fn check_expression_depth(&self, expr: &AstExpr) -> Result<(), ParseError> { + /// Expression visitor that reports whether the walk ever ran out of budget. + struct DepthCheck { + remaining: u16, + too_deep: bool, + } + impl<'a> Visitor<'a> for DepthCheck { + fn visit_expr(&mut self, expr: &'a AstExpr) { + // Nothing is pruned (not even lambda bodies): the guarded walks + // reach everywhere, so the bound must too. + match self.remaining.checked_sub(1) { + _ if self.too_deep => {} + None => self.too_deep = true, + Some(remaining) => { + self.remaining = remaining; + walk_expr(self, expr); + self.remaining += 1; + } + } + } + } + + let mut check = DepthCheck { + remaining: self.depth_remaining, + too_deep: false, + }; + check.visit_expr(expr); + if check.too_deep { + Err(ParseError::syntax( + "Source is too deeply nested", + self.convert_range(expr.range()), + )) + } else { + Ok(()) + } + } +} + +fn convert_op(op: AstOperator) -> Operator { + match op { + AstOperator::Add => Operator::Add, + AstOperator::Sub => Operator::Sub, + AstOperator::Mult => Operator::Mult, + AstOperator::MatMult => Operator::MatMult, + AstOperator::Div => Operator::Div, + AstOperator::Mod => Operator::Mod, + AstOperator::Pow => Operator::Pow, + AstOperator::LShift => Operator::LShift, + AstOperator::RShift => Operator::RShift, + AstOperator::BitOr => Operator::BitOr, + AstOperator::BitXor => Operator::BitXor, + AstOperator::BitAnd => Operator::BitAnd, + AstOperator::FloorDiv => Operator::FloorDiv, + } +} + +fn convert_bool_op(op: BoolOp) -> Operator { + match op { + BoolOp::And => Operator::And, + BoolOp::Or => Operator::Or, + } +} + +fn convert_compare_op(op: CmpOp) -> CmpOperator { + match op { + CmpOp::Eq => CmpOperator::Eq, + CmpOp::NotEq => CmpOperator::NotEq, + CmpOp::Lt => CmpOperator::Lt, + CmpOp::LtE => CmpOperator::LtE, + CmpOp::Gt => CmpOperator::Gt, + CmpOp::GtE => CmpOperator::GtE, + CmpOp::Is => CmpOperator::Is, + CmpOp::IsNot => CmpOperator::IsNot, + CmpOp::In => CmpOperator::In, + CmpOp::NotIn => CmpOperator::NotIn, + } +} + +/// Converts ruff's ConversionFlag to our ConversionFlag. +fn convert_conversion_flag(flag: RuffConversionFlag) -> ConversionFlag { + match flag { + RuffConversionFlag::None => ConversionFlag::None, + RuffConversionFlag::Str => ConversionFlag::Str, + RuffConversionFlag::Repr => ConversionFlag::Repr, + RuffConversionFlag::Ascii => ConversionFlag::Ascii, + } +} + +/// Does `expr` contain a `:=` that binds in the enclosing (class-body) scope? +/// +/// Like ruff's `any_over_expr`, but scope-aware for lambdas: a walrus inside a +/// lambda *body* binds in the lambda's own scope (legal CPython, e.g. +/// `class C: f = lambda: (z := 1)`) and is skipped, while lambda parameter +/// *defaults* evaluate in the enclosing scope and are still searched. +/// Comprehensions ARE descended into: CPython also rejects an assignment +/// expression within a comprehension in a class body (as a `SyntaxError`). +fn contains_class_scope_walrus(expr: &AstExpr) -> bool { + /// Expression visitor that records whether a class-scope-binding walrus + /// was seen, pruning lambda bodies from the walk. + struct Finder { + found: bool, + } + impl<'a> Visitor<'a> for Finder { + fn visit_expr(&mut self, expr: &'a AstExpr) { + match expr { + _ if self.found => {} + AstExpr::Named(_) => self.found = true, + AstExpr::Lambda(lambda) => { + // Only the parameter defaults evaluate in the enclosing scope. + for param in lambda.parameters.iter().flat_map(|p| p.iter_non_variadic_params()) { + if let Some(default) = param.default.as_deref() { + self.visit_expr(default); + } + } + } + _ => walk_expr(self, expr), + } + } + } + + let mut finder = Finder { found: false }; + finder.visit_expr(expr); + finder.found +} + +/// The CPython error for a `*target` that is not an element of a tuple or list. +fn starred_root_target(position: CodeRange) -> ParseError { + ParseError::syntax("starred assignment target must be in a list or tuple", position) +} + +/// Rejects a second `*target` at one unpacking level, as CPython does. +/// +/// `UnpackEx` encodes one starred slot as "n before, m after", so a second star +/// has nowhere to go: without this check `a, *b, *c = xs` would bind silently +/// wrong values instead of raising. +fn check_single_starred(targets: &[UnpackTarget], position: CodeRange) -> Result<(), ParseError> { + if targets.iter().filter(|t| matches!(t, UnpackTarget::Starred(_))).count() > 1 { + Err(ParseError::syntax( + "multiple starred expressions in assignment", + position, + )) + } else { + Ok(()) + } +} + +/// Short human-readable name for an `AstExpr` variant, for use in +/// user-facing parse errors. Avoids the Rust `Debug` formatting of the +/// node, which would leak internal field names, ranges, and struct +/// layout of `ruff_python_ast` into the error message. +fn describe_expr_kind(expr: &AstExpr) -> &'static str { + match expr { + AstExpr::Name(_) => "name", + AstExpr::Starred(_) => "starred expression", + AstExpr::Attribute(_) => "attribute", + AstExpr::Subscript(_) => "subscript", + AstExpr::Call(_) => "function call", + AstExpr::Tuple(_) => "tuple", + AstExpr::List(_) => "list", + AstExpr::Set(_) => "set", + AstExpr::Dict(_) => "dict", + AstExpr::NumberLiteral(_) => "number literal", + AstExpr::StringLiteral(_) => "string literal", + AstExpr::BytesLiteral(_) => "bytes literal", + AstExpr::BooleanLiteral(_) => "boolean literal", + AstExpr::NoneLiteral(_) => "None", + AstExpr::EllipsisLiteral(_) => "...", + AstExpr::FString(_) => "f-string", + AstExpr::TString(_) => "t-string", + AstExpr::Lambda(_) => "lambda", + AstExpr::If(_) => "conditional expression", + AstExpr::BoolOp(_) => "boolean expression", + AstExpr::BinOp(_) => "binary expression", + AstExpr::UnaryOp(_) => "unary expression", + AstExpr::Compare(_) => "comparison", + AstExpr::Named(_) => "named expression", + AstExpr::Yield(_) => "yield expression", + AstExpr::YieldFrom(_) => "yield from expression", + AstExpr::Await(_) => "await expression", + AstExpr::ListComp(_) => "list comprehension", + AstExpr::SetComp(_) => "set comprehension", + AstExpr::DictComp(_) => "dict comprehension", + AstExpr::Generator(_) => "generator expression", + AstExpr::Slice(_) => "slice", + AstExpr::IpyEscapeCommand(_) => "IPython escape command", + } +} + +/// Source code location for a parsed node, stored as raw byte offsets. +/// +/// `CodeRange` is written by the parser for every AST node and must therefore +/// be cheap to construct. Storing just byte offsets (matching ruff's native +/// `TextRange` representation) means producing a `CodeRange` is a single +/// struct assignment — no line/column resolution, no UTF-8 char iteration, +/// no line-index lookup. +/// +/// When a diagnostic (traceback, syntax error) actually needs human-readable +/// line/column positions or a source preview line, a [`SourceMap`] is built +/// over the source text once at the diagnostic boundary and used to resolve +/// byte offsets lazily. This keeps the parse hot path O(1) per node while +/// preserving exact CPython-compatible column semantics (`chars().count()` +/// on the relevant line only) at diagnostic time. +#[derive(Clone, Copy, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)] +pub struct CodeRange { + /// Filename identity, resolved by `Interns::get_filename`. + #[serde(rename = "F")] + pub filename: StringId, + /// Byte offset of the range start within the source text. + #[serde(rename = "S")] + pub start_byte: u32, + /// Byte offset of the range end (exclusive) within the source text. + #[serde(rename = "E")] + pub end_byte: u32, +} + +/// Custom Debug implementation to keep AST-printing output compact. +impl fmt::Debug for CodeRange { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "CodeRange{{filename: {:?}, start_byte: {}, end_byte: {}}}", + self.filename, self.start_byte, self.end_byte + ) + } +} + +/// Errors that can occur during parsing or preparation of Python code. +#[derive(Debug, Clone)] +pub enum ParseError { + /// Error in syntax + Syntax { + msg: Cow<'static, str>, + position: CodeRange, + }, + /// Missing feature from Monty, we hope to implement in the future. + /// Message gets prefixed with "The monty syntax parser does not yet support ". + NotImplemented { + msg: Cow<'static, str>, + position: CodeRange, + }, + /// Missing feature with a custom full message (no prefix added). + NotSupported { + msg: Cow<'static, str>, + position: CodeRange, + }, + /// Import error (e.g., relative imports without a package). + Import { + msg: Cow<'static, str>, + position: CodeRange, + }, +} + +impl ParseError { + /// Moves the error `bytes` later in the source, for a parse of a suffix + /// of the caller's text (`eval()` trims leading whitespace) so the line + /// number is counted from the start of what the caller passed. + pub(crate) fn shifted(mut self, bytes: u32) -> Self { + let (Self::Syntax { position, .. } + | Self::NotImplemented { position, .. } + | Self::NotSupported { position, .. } + | Self::Import { position, .. }) = &mut self; + position.start_byte = position.start_byte.saturating_add(bytes); + position.end_byte = position.end_byte.saturating_add(bytes); + self + } + + pub(crate) fn not_implemented(msg: impl Into>, position: CodeRange) -> Self { + Self::NotImplemented { + msg: msg.into(), + position, + } + } + + fn not_supported(msg: impl Into>, position: CodeRange) -> Self { + Self::NotSupported { + msg: msg.into(), + position, + } + } + + fn import_error(msg: impl Into>, position: CodeRange) -> Self { + Self::Import { + msg: msg.into(), + position, + } + } + + pub(crate) fn syntax(msg: impl Into>, position: CodeRange) -> Self { + Self::Syntax { + msg: msg.into(), + position, + } + } +} + +impl ParseError { + /// Converts to the exception an `eval()` / `exec()` call raises for its + /// snippet: the same type and message as [`into_python_exc`](Self::into_python_exc), + /// with a `SyntaxError` carrying CPython's `(, line N)` suffix. + /// Non-syntax errors keep a resolved snippet location, independent of the + /// rejected compilation's intern IDs; propagation adds the caller's frames. + pub(crate) fn into_run_error(self, source: &str) -> RunError { + match self { + Self::Syntax { msg, position } => syntax_error_in_snippet(&msg, position, source), + Self::NotImplemented { msg, position } => { + ExcType::not_implemented(format!("The monty syntax parser does not yet support {msg}")) + .with_snippet_position(position, source) + .into() + } + Self::NotSupported { msg, position } => ExcType::not_implemented(msg) + .with_snippet_position(position, source) + .into(), + Self::Import { msg, position } => SimpleException::new_msg(ExcType::ImportError, msg) + .with_snippet_position(position, source) + .into(), + } + } + + pub fn into_python_exc(self, filename: &str, source: &str) -> MontyException { + let mut source_map = SourceMap::new(source); + match self { + Self::Syntax { msg, position } => MontyException::with_traceback( + ExcType::SyntaxError, + Some(msg.into_owned()), + vec![StackFrame::from_position_syntax_error( + position, + filename, + &mut source_map, + )], + ), + Self::NotImplemented { msg, position } => MontyException::with_traceback( + ExcType::NotImplementedError, + Some(format!("The monty syntax parser does not yet support {msg}")), + vec![StackFrame::from_position(position, filename, &mut source_map)], + ), + Self::NotSupported { msg, position } => MontyException::with_traceback( + ExcType::NotImplementedError, + Some(msg.into_owned()), + vec![StackFrame::from_position(position, filename, &mut source_map)], + ), + Self::Import { msg, position } => MontyException::with_traceback( + ExcType::ImportError, + Some(msg.into_owned()), + vec![StackFrame::from_position_no_caret(position, filename, &mut source_map)], + ), + } + } +} + +/// Parses an integer literal string into a `BigInt`, handling radix prefixes and underscores. +/// +/// Supports Python integer literal formats: +/// - Decimal: `123`, `1_000_000` +/// - Hexadecimal: `0x1a2b`, `0X1A2B` +/// - Octal: `0o777`, `0O777` +/// - Binary: `0b1010`, `0B1010` +/// +/// Check digit limit before the expensive O(n^2) decimal BigInt parse. +/// Only decimal is limited — hex/octal/binary use O(n) algorithms and are handled above. +/// +/// Returns `ParseError` if the string cannot be parsed. +fn parse_int_literal(s: &str, position: CodeRange) -> Result { + // Remove underscores (Python allows them as digit separators) + let cleaned: String = s.chars().filter(|c| *c != '_').collect(); + let cleaned = cleaned.as_str(); + + // Detect radix from prefix + if cleaned.len() >= 2 { + let prefix = &cleaned[..2]; + let digits = &cleaned[2..]; + + let from_radix = |radix: u32| -> Result { + BigInt::from_str_radix(digits, radix) + .map_err(|e| ParseError::syntax(format!("invalid integer literal: {s:?}, error: {e}"), position)) + }; + + match prefix.to_ascii_lowercase().as_str() { + "0x" => return from_radix(16), + "0o" => return from_radix(8), + "0b" => return from_radix(2), + _ => {} + } + } + + // Default to decimal + let digit_count = cleaned.bytes().filter(u8::is_ascii_digit).count(); + if digit_count > INT_MAX_STR_DIGITS { + Err(ParseError::syntax( + format!( + "Exceeds the limit ({INT_MAX_STR_DIGITS} digits) for integer string conversion: \ + value has {digit_count} digits; consider hexadecimal for large integer literals" + ), + position, + )) + } else { + cleaned + .parse::() + .map_err(|e| ParseError::syntax(format!("invalid integer literal {s:?}, error: {e}"), position)) + } +} + +/// The widest pattern the bytecode can encode: sub-pattern counts and attribute +/// indexes are `u8` operands. Checked before any pairwise scan over a pattern's +/// parts so untrusted source cannot buy quadratic parse time with a wide pattern. +const MAX_SUBPATTERNS: usize = u8::MAX as usize; + +/// `SyntaxError: too many sub-patterns in pattern` past [`MAX_SUBPATTERNS`]. +fn check_subpattern_count(count: usize, kind: &str, position: CodeRange) -> Result<(), ParseError> { + if count > MAX_SUBPATTERNS { + Err(ParseError::syntax( + format!("too many sub-patterns in {kind} pattern"), + position, + )) + } else { + Ok(()) + } +} + +/// A mapping-pattern key the parser can evaluate: a literal, optionally negated, +/// or a `real ± imag j` complex number. +/// +/// Mirrors the constant folding CPython applies before its duplicate-key check, +/// so `-1` and `1+2j` are constant keys while `Color.RED` is not. +#[derive(Clone, Copy)] +enum ConstantKey<'a> { + Literal { + literal: &'a Literal, + negated: bool, + }, + /// `1+2j`, folded as CPython does: `complex(real) ± complex(0, imag)`. + Complex { + real: f64, + imag: f64, + }, +} + +impl<'a> ConstantKey<'a> { + fn of(key: &'a ExprLoc, interner: &CompileInterns<'_>) -> Option { + match &key.expr { + Expr::Literal(literal) => Some(Self::Literal { + literal, + negated: false, + }), + Expr::UnaryMinus(inner) => match &inner.expr { + Expr::Literal( + literal @ (Literal::Int(_) | Literal::Float(_) | Literal::LongInt(_) | Literal::Complex(_)), + ) => Some(Self::Literal { literal, negated: true }), + _ => None, + }, + // The grammar only allows a signed real on the left and an + // imaginary literal on the right. + Expr::Op { left, op, right } => { + let Expr::Literal(Literal::Complex(imag)) = right.expr else { + return None; + }; + let real = match Self::of(left, interner)?.number(interner)? { + ConstantNumber::Int(i) => i.to_f64().filter(|f| f.is_finite())?, + ConstantNumber::Float(f) => f, + ConstantNumber::Complex { .. } => return None, + }; + match op { + Operator::Add => Some(Self::Complex { + real: real + 0.0, + imag: 0.0 + imag, + }), + Operator::Sub => Some(Self::Complex { + real: real - 0.0, + imag: 0.0 - imag, + }), + _ => None, + } + } + _ => None, + } + } + + /// The key as an exact number (`bool` included), with its sign applied. + fn number(self, interner: &CompileInterns<'_>) -> Option { + let (literal, negated) = match self { + Self::Literal { literal, negated } => (literal, negated), + Self::Complex { real, imag } => return Some(ConstantNumber::Complex { real, imag }), + }; + let number = match literal { + Literal::Bool(b) => ConstantNumber::Int(BigInt::from(u8::from(*b))), + Literal::Int(i) => ConstantNumber::Int(BigInt::from(*i)), + Literal::LongInt(id) => ConstantNumber::Int(interner.get_long_int(*id).clone()), + Literal::Float(f) => ConstantNumber::Float(*f), + Literal::Complex(imag) => ConstantNumber::Complex { real: 0.0, imag: *imag }, + _ => return None, + }; + Some(if negated { number.neg() } else { number }) + } + + /// The key's `repr`, for the duplicate-key diagnostic, or `None` for an + /// integer (e.g. a long hex literal) past the decimal digit limit. + fn repr(self, interner: &CompileInterns<'_>) -> Option { + let (literal, negated) = match self { + Self::Literal { literal, negated } => (literal, negated), + Self::Complex { real, imag } => return Some(FormatComplex { real, imag }.to_string()), + }; + let sign = if negated { "-" } else { "" }; + let repr = match literal { + Literal::None => "None".to_owned(), + Literal::Bool(true) => "True".to_owned(), + Literal::Bool(false) => "False".to_owned(), + Literal::Int(i) => format!("{sign}{i}"), + Literal::Float(f) => format!("{sign}{}", FormatFloat(*f)), + Literal::Str(id) => StringRepr(interner.get_str(*id)).to_string(), + Literal::Bytes(id) => bytes_repr(interner.get_bytes(*id)), + Literal::LongInt(id) => { + let value = interner.get_long_int(*id); + check_bigint_str_digits_limit(value).ok()?; + format!("{sign}{value}") + } + // `-2j` negates `0+2j`, so its real part is `-0.0` and CPython shows `(-0-2j)`. + Literal::Complex(imag) => FormatComplex { + real: if negated { -0.0 } else { 0.0 }, + imag: if negated { -imag } else { *imag }, + } + .to_string(), + Literal::Ellipsis => "Ellipsis".to_owned(), + Literal::Marker(_) => "".to_owned(), + }; + Some(repr) + } +} + +/// A [`ConstantKey`] with its numeric value computed once, for the pairwise duplicate scan. +struct FoldedKey<'a> { + key: ConstantKey<'a>, + number: Option, +} + +impl FoldedKey<'_> { + /// Python equality between two constant keys, as a `set` of them would see it. + fn py_eq(&self, other: &Self) -> bool { + match (&self.number, &other.number) { + (Some(a), Some(b)) => a.py_eq(b), + (None, None) => match (self.key, other.key) { + (ConstantKey::Literal { literal: a, .. }, ConstantKey::Literal { literal: b, .. }) => match (a, b) { + (Literal::None, Literal::None) => true, + (Literal::Str(a), Literal::Str(b)) => a == b, + (Literal::Bytes(a), Literal::Bytes(b)) => a == b, + _ => false, + }, + _ => false, + }, + _ => false, + } + } +} + +/// A constant mapping-pattern key's numeric value, compared without rounding +/// so distinct integers above 2**53 never collide and `2**63 == 2.0**63` does. +enum ConstantNumber { + Int(BigInt), + Float(f64), + Complex { real: f64, imag: f64 }, +} + +impl ConstantNumber { + fn neg(self) -> Self { + match self { + Self::Int(i) => Self::Int(-i), + Self::Float(f) => Self::Float(-f), + Self::Complex { real, imag } => Self::Complex { + real: -real, + imag: -imag, + }, + } + } + + /// Python `==` across `int`, `float` and `complex`. + fn py_eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::Int(a), Self::Int(b)) => a == b, + (Self::Float(a), Self::Float(b)) => a == b, + (Self::Int(i), Self::Float(f)) | (Self::Float(f), Self::Int(i)) => { + bigint_cmp_f64(i, *f) == Some(Ordering::Equal) + } + (Self::Complex { real: ar, imag: ai }, Self::Complex { real: br, imag: bi }) => ar == br && ai == bi, + // A complex equals a real only when its imaginary part is zero. + (Self::Complex { real, imag }, other) | (other, Self::Complex { real, imag }) => { + *imag == 0.0 && other.py_eq(&Self::Float(*real)) + } + } + } +} diff --git a/crates/bashkit-monty/src/percent_format.rs b/crates/bashkit-monty/src/percent_format.rs new file mode 100644 index 000000000..bce7ca698 --- /dev/null +++ b/crates/bashkit-monty/src/percent_format.rs @@ -0,0 +1,1063 @@ +//! Printf-style `%` formatting for `str` and `bytes` (`'%5.2f' % x`, `b'%s' % data`). +//! +//! Directive parsing, argument consumption and error precedence follow +//! CPython's `PyUnicode_Format` and `_PyBytes_FormatEx`, which share a +//! grammar. Directives are ASCII, so scanning works on the template's bytes +//! for both types; the output stays typed as `String` or `Vec` through the +//! [`Target`] trait. Float digit text comes from the f-string formatters in +//! [`crate::fstring`]; padding happens here because printf pads differently +//! from the format mini-language (zero fill also covers `nan` and `inf`, text +//! right-aligns, integer precision zero-extends). + +use std::ops::Range; + +use memchr::memchr; +use monty_types::ResourceTracker; +use num_bigint::BigInt; +use num_traits::Signed; +use smallvec::{SmallVec, smallvec}; + +use crate::{ + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + fstring::{MAX_FLOAT_PRECISION, ParsedFormatSpec, Sign, TypeChar, format_float_e, format_float_f, format_float_g}, + heap::{ContainsHeap, DropWithContext, Heap, HeapData}, + py_value::PyValue, + resource_checks::check_repeat_size, + str_format::value_error, + string_builder::{BytesBuilder, StringBuilder}, + types::{ + LongInt, PyTrait, Type, bytes::allocate_bytes, long_int::check_bits_str_digits_limit, str::allocate_string, + }, + value::{VALUE_SIZE, Value}, +}; + +/// Renders `template % args` for a `str` template. +pub(crate) fn percent_format(template: &str, args: &Value, vm: &mut VM<'_>) -> RunResult { + format_template::(template, args, vm) +} + +/// Renders `template % args` for a `bytes` template. +pub(crate) fn percent_format_bytes(template: &[u8], args: &Value, vm: &mut VM<'_>) -> RunResult { + format_template::(template, args, vm) +} + +/// Copies a `bytes` template through the tracker, so a template near the +/// memory limit reports `MemoryError` rather than tripping the hard ceiling. +pub(crate) fn copy_bytes_template(template: &[u8], tracker: &ResourceTracker) -> RunResult> { + let mut copy = BytesBuilder::with_capacity(template.len(), tracker)?; + copy.push_slice(template)?; + Ok(copy.finish()) +} + +/// Bytes scanned between tracker clock polls while looking for the next `%`. +const SCAN_CHUNK: usize = 4096; + +/// The largest precision CPython's integer formatter accepts (`INT_MAX - 3`); +/// above it `%d` and friends raise `OverflowError` rather than zero-extending. +const MAX_INTEGER_PRECISION: usize = i32::MAX as usize - 3; + +/// A `%` formatting target: the template type, its output buffer, and the +/// behaviour that differs between `str` and `bytes` templates. Keeping the +/// output typed per target means the `str` path never re-validates UTF-8. +trait Target: Sized { + /// `str` or `[u8]`. + type Template: ?Sized; + /// `String` or `Vec`. + type Output: Default; + /// The tracked builder for [`Self::Output`]. + type Builder<'t>: OutputBuilder<'t, Output = Self::Output>; + + /// Selects the `bytes` rules: `%b`, `ascii()` for `%r`, the error wording. + const IS_BYTES: bool; + /// The error for a literal precision above C `int`. + const PRECISION_TOO_BIG: &'static str; + + /// The template's bytes; every offset the formatter slices at is an ASCII byte. + fn as_bytes(template: &Self::Template) -> &[u8]; + /// Appends `template[range]` to the output. + fn push_literal(builder: &mut Self::Builder<'_>, template: &Self::Template, range: Range) -> RunResult<()>; + /// A `%(key)` as a value of the template's type. + fn key_value(template: &Self::Template, range: Range, heap: &Heap) -> Value; + /// An ASCII fragment (digits, signs, exponents) as an output value. + fn from_ascii(text: String) -> Self::Output; + /// The size of an output fragment in bytes. + fn byte_len(output: &Self::Output) -> usize; + /// A `str` fragment cut to the directive's precision: `%r`, `%a`, and the `str` `%s` / `%c`. + fn text_from_string(text: String, spec: &Directive) -> Text; + /// The `%s` operand (also `%b` for `bytes`). + fn text_operand(value: &Value, spec: &Directive, vm: &mut VM<'_>) -> RunResult>; + /// The `%c` operand, always one character or byte; the precision is ignored. + fn char_operand(value: &Value, vm: &mut VM<'_>) -> RunResult>; + /// The error for a float directive on a non-numeric operand. + fn float_type_error(type_name: &str) -> RunError; + /// The error for an int too large to convert to a float. + fn float_overflow_error() -> RunError; + /// The error for an unknown conversion at byte `index`. + fn unsupported(template: &Self::Template, index: usize) -> RunError; + /// The finished output as a heap value. + fn allocate(output: Self::Output, heap: &Heap) -> Value; +} + +/// The tracked builder a [`Target`] assembles its output with. +trait OutputBuilder<'t>: Sized { + type Output; + + /// Wraps an existing output whose capacity is already tracker-accounted. + fn from_existing(output: Self::Output, tracker: &'t ResourceTracker) -> Self; + /// Reserves `capacity` bytes up front after one tracker check. + fn with_capacity(capacity: usize, tracker: &'t ResourceTracker) -> RunResult; + /// Appends text: template literals, signs, prefixes and digits. + fn push_text(&mut self, text: &str) -> RunResult<()>; + /// Appends `count` copies of an ASCII fill byte. + fn push_fill(&mut self, fill: u8, count: usize) -> RunResult<()>; + /// Appends a rendered fragment. + fn push_output(&mut self, fragment: &Self::Output) -> RunResult<()>; + /// Consumes the builder. + fn finish(self) -> RunResult; +} + +/// A rendered text fragment with its length in the target's units: +/// characters for `str`, bytes for `bytes`. +struct Text { + body: T::Output, + /// Only padding reads this, so a `str` directive with neither width nor + /// precision skips the count and reports `0` rather than walking the text. + len: usize, +} + +/// `str % args`. +struct StrTarget; + +impl Target for StrTarget { + type Template = str; + type Output = String; + type Builder<'t> = StringBuilder<'t>; + + const IS_BYTES: bool = false; + const PRECISION_TOO_BIG: &'static str = "precision too big"; + + fn as_bytes(template: &str) -> &[u8] { + template.as_bytes() + } + + fn push_literal(builder: &mut StringBuilder<'_>, template: &str, range: Range) -> RunResult<()> { + builder.push_text(&template[range]) + } + + fn key_value(template: &str, range: Range, heap: &Heap) -> Value { + allocate_string(&template[range], heap) + } + + fn from_ascii(text: String) -> String { + text + } + + fn byte_len(output: &String) -> usize { + output.len() + } + + fn text_from_string(mut text: String, spec: &Directive) -> Text { + if spec.precision.is_none() && spec.width == 0 { + Text { body: text, len: 0 } + } else { + let mut len = 0; + let mut end = text.len(); + for (offset, _) in text.char_indices() { + if spec.precision == Some(len) { + end = offset; + break; + } + len += 1; + } + text.truncate(end); + Text { body: text, len } + } + } + + /// `str()` of any value. + fn text_operand(value: &Value, spec: &Directive, vm: &mut VM<'_>) -> RunResult> { + Ok(Self::text_from_string(vm.convert_value(value, 1)?, spec)) + } + + fn char_operand(value: &Value, vm: &mut VM<'_>) -> RunResult> { + Ok(Text { + body: char_text(value, vm)?, + len: 1, + }) + } + + fn float_type_error(type_name: &str) -> RunError { + ExcType::type_error(format!("must be real number, not {type_name}")) + } + + fn float_overflow_error() -> RunError { + ExcType::overflow_int_to_float() + } + + /// CPython reports the character (not byte) index in a `str` template, + /// and quotes the character only within its `31..=126` window. + fn unsupported(template: &str, index: usize) -> RunError { + let conversion = template[index..].chars().next().unwrap_or('?'); + let shown = if ('\x1f'..='~').contains(&conversion) { + conversion + } else { + '?' + }; + unsupported_character(shown, conversion, template[..index].chars().count()) + } + + fn allocate(output: String, heap: &Heap) -> Value { + allocate_string(output, heap) + } +} + +/// `bytes % args`. +struct BytesTarget; + +impl Target for BytesTarget { + type Template = [u8]; + type Output = Vec; + type Builder<'t> = BytesBuilder<'t>; + + const IS_BYTES: bool = true; + const PRECISION_TOO_BIG: &'static str = "prec too big"; + + fn as_bytes(template: &[u8]) -> &[u8] { + template + } + + fn push_literal(builder: &mut BytesBuilder<'_>, template: &[u8], range: Range) -> RunResult<()> { + Ok(builder.push_slice(&template[range])?) + } + + fn key_value(template: &[u8], range: Range, heap: &Heap) -> Value { + allocate_bytes(template[range].to_vec(), heap) + } + + fn from_ascii(text: String) -> Vec { + text.into_bytes() + } + + fn byte_len(output: &Vec) -> usize { + output.len() + } + + /// Only ASCII text reaches a `bytes` template (`ascii()` output), so + /// bytes and characters coincide. + fn text_from_string(text: String, spec: &Directive) -> Text { + Self::from_bytes(text.as_bytes(), spec.precision) + } + + /// Only `bytes` values; Monty has no `bytearray`, `memoryview` or `__bytes__`. + fn text_operand(value: &Value, spec: &Directive, vm: &mut VM<'_>) -> RunResult> { + match value { + Value::InternBytes(id) => Ok(Self::from_bytes(vm.interns.get_bytes(*id), spec.precision)), + Value::Ref(id) if let HeapData::Bytes(bytes) = vm.heap.get(*id) => { + Ok(Self::from_bytes(bytes.as_slice(), spec.precision)) + } + _ => Err(ExcType::type_error(format!( + "%b requires a bytes-like object, or an object that implements __bytes__, not '{}'", + value.py_type_name(vm) + ))), + } + } + + fn char_operand(value: &Value, vm: &mut VM<'_>) -> RunResult> { + Ok(Self::from_bytes(&[byte_char(value, vm)?], None)) + } + + fn float_type_error(type_name: &str) -> RunError { + ExcType::type_error(format!("float argument required, not {type_name}")) + } + + /// CPython's bytes formatter folds the overflow into its generic type error. + fn float_overflow_error() -> RunError { + ExcType::type_error("float argument required, not int") + } + + /// CPython quotes any ASCII byte as it is; a non-ASCII byte gets an odd + /// `OverflowError` rather than the unsupported-character error. + fn unsupported(template: &[u8], index: usize) -> RunError { + let conversion = template[index]; + if conversion.is_ascii() { + unsupported_character(char::from(conversion), char::from(conversion), index) + } else { + SimpleException::new_msg(ExcType::OverflowError, "character argument not in range(0x110000)").into() + } + } + + fn allocate(output: Vec, heap: &Heap) -> Value { + allocate_bytes(output, heap) + } +} + +impl BytesTarget { + /// A `bytes` fragment, copying only the first `precision` bytes. + fn from_bytes(bytes: &[u8], precision: Option) -> Text { + let len = precision.map_or(bytes.len(), |precision| precision.min(bytes.len())); + Text { + body: bytes[..len].to_vec(), + len, + } + } +} + +impl<'t> OutputBuilder<'t> for StringBuilder<'t> { + type Output = String; + + fn from_existing(output: String, tracker: &'t ResourceTracker) -> Self { + StringBuilder::from_existing(output, tracker) + } + + fn with_capacity(capacity: usize, tracker: &'t ResourceTracker) -> RunResult { + Ok(StringBuilder::with_capacity(capacity, tracker)?) + } + + fn push_text(&mut self, text: &str) -> RunResult<()> { + Ok(self.push_str(text)?) + } + + fn push_fill(&mut self, fill: u8, count: usize) -> RunResult<()> { + Ok(self.push_repeated(char::from(fill), count)?) + } + + fn push_output(&mut self, fragment: &String) -> RunResult<()> { + Ok(self.push_str(fragment)?) + } + + fn finish(self) -> RunResult { + self.finish_raw() + } +} + +impl<'t> OutputBuilder<'t> for BytesBuilder<'t> { + type Output = Vec; + + fn from_existing(output: Vec, tracker: &'t ResourceTracker) -> Self { + BytesBuilder::from_existing(output, tracker) + } + + fn with_capacity(capacity: usize, tracker: &'t ResourceTracker) -> RunResult { + Ok(BytesBuilder::with_capacity(capacity, tracker)?) + } + + fn push_text(&mut self, text: &str) -> RunResult<()> { + Ok(self.push_slice(text.as_bytes())?) + } + + fn push_fill(&mut self, fill: u8, count: usize) -> RunResult<()> { + Ok(self.push_repeated(fill, count)?) + } + + fn push_output(&mut self, fragment: &Vec) -> RunResult<()> { + Ok(self.push_slice(fragment)?) + } + + fn finish(self) -> RunResult> { + Ok(BytesBuilder::finish(self)) + } +} + +/// Walks the template, copying literal runs and rendering each `%` directive. +fn format_template(template: &T::Template, args: &Value, vm: &mut VM<'_>) -> RunResult { + let bytes = T::as_bytes(template); + let arguments = Arguments::new(args, T::IS_BYTES, vm)?; + defer_drop!(arguments, vm); + let cursor = Cursor::default(); + defer_drop_mut!(cursor, vm); + + let mut output = T::Output::default(); + let mut index = 0; + let mut steps = 0; + while index < bytes.len() { + vm.heap.tracker.check_time_every(steps)?; + steps += 1; + let literal_end = find_percent(bytes, index, &vm.heap.tracker)?; + if literal_end > index { + output = extend::(output, &vm.heap.tracker, |builder| { + T::push_literal(builder, template, index..literal_end) + })?; + } + if literal_end == bytes.len() { + break; + } + index = literal_end + 1; + // Only an immediate `%%` is an escape: `%5%` is a directive whose conversion is `%`. + if bytes.get(index) == Some(&b'%') { + output = extend::(output, &vm.heap.tracker, |builder| builder.push_text("%"))?; + index += 1; + } else { + let (rendered, next) = render_directive::(template, index, arguments, cursor, vm)?; + // A directive that opens the template (the whole of `'%s' % s`) is the output so far. + output = if T::byte_len(&output) == 0 { + rendered + } else { + extend::(output, &vm.heap.tracker, |builder| builder.push_output(&rendered))? + }; + index = next; + } + } + + // A mapping operand never reports leftovers, so `'abc' % {}` is fine. + if arguments.mapping.is_none() && cursor.next < arguments.positional.len() { + let noun = if T::IS_BYTES { "bytes" } else { "string" }; + Err(ExcType::type_error(format!( + "not all arguments converted during {noun} formatting" + ))) + } else { + Ok(T::allocate(output, vm.heap)) + } +} + +/// Finds the next `%` at or after `start` (or the template's end), polling +/// the tracker's clock per chunk so a long literal run stays interruptible. +fn find_percent(bytes: &[u8], start: usize, tracker: &ResourceTracker) -> RunResult { + for (chunk_index, chunk) in bytes[start..].chunks(SCAN_CHUNK).enumerate() { + tracker.check_time_every(chunk_index)?; + if let Some(offset) = memchr(b'%', chunk) { + return Ok(start + chunk_index * SCAN_CHUNK + offset); + } + } + Ok(bytes.len()) +} + +/// Appends to `output` through a short-lived tracked builder, so the tracker +/// borrow ends before the VM is needed again. +fn extend( + output: T::Output, + tracker: &ResourceTracker, + push: impl FnOnce(&mut T::Builder<'_>) -> RunResult<()>, +) -> RunResult { + let mut builder = >::from_existing(output, tracker); + push(&mut builder)?; + builder.finish() +} + +/// The right-hand operand, split the way CPython's `PyUnicode_Format` sees it. +struct Arguments { + /// The tuple's items, or the lone operand itself; inline for the usual few. + positional: SmallVec<[Value; 4]>, + /// The operand again when `%(key)` may index it: the types CPython's + /// mapping check accepts (see `limitations/format.md`), minus `bytes` + /// for a `bytes` template. + mapping: Option, +} + +impl Arguments { + fn new(args: &Value, bytes_template: bool, vm: &VM<'_>) -> RunResult { + let positional = match args { + Value::Ref(id) if let HeapData::Tuple(tuple) = vm.heap.get(*id) => clone_items(tuple.as_slice(), vm)?, + Value::Ref(id) if let HeapData::NamedTuple(tuple) = vm.heap.get(*id) => clone_items(tuple.as_vec(), vm)?, + _ => smallvec![args.clone_with_heap(vm.heap)], + }; + let mapping = match args.py_type(vm) { + Type::Dict | Type::DefaultDict | Type::Counter | Type::List | Type::Range => true, + Type::Bytes => !bytes_template, + _ => false, + } + .then(|| args.clone_with_heap(vm.heap)); + Ok(Self { positional, mapping }) + } +} + +impl DropWithContext for Arguments { + fn drop_with(self, ctx: &mut C) { + self.positional.drop_with(ctx); + self.mapping.drop_with(ctx); + } +} + +impl DropWithContext for Cursor { + fn drop_with(self, ctx: &mut C) { + self.pending.drop_with(ctx); + } +} + +/// Clones tuple items so the operand can be released before rendering ends, +/// preflighting the copy like other bulk container clones. +fn clone_items(items: &[Value], vm: &VM<'_>) -> RunResult> { + vm.heap + .tracker + .check_allocation(items.len().saturating_mul(VALUE_SIZE))?; + Ok(items.iter().map(|item| item.clone_with_heap(vm.heap)).collect()) +} + +/// Argument consumption state; lives inside a `DropGuard` in the render loop +/// so a pending keyed value is released on every error path. +#[derive(Default)] +struct Cursor { + /// Index of the next unconsumed positional argument. + next: usize, + /// Set once a `%(key)` directive has run: from then on the only argument + /// left is the looked-up value itself, which `pending` carries until a `*` + /// or the conversion takes it. + keyed: bool, + /// The value a `%(key)` lookup produced, not yet consumed. + pending: Option, +} + +/// The flags, width and precision of one `%` directive. +#[derive(Default)] +struct Directive { + /// `-`: left-justify within the width. + left: bool, + /// `+` always signs numbers; ` ` puts a space where their sign would go. + /// `+` wins when both are given. + sign: Option, + /// `#`: `0x`/`0o` prefixes and a forced decimal point. + alternate: bool, + /// `0`: pad numbers with zeros after the sign; ignored for text and under `-`. + zero: bool, + /// Minimum field width in characters. + width: usize, + /// Digits after the point for floats, minimum digits for integers, + /// maximum characters for text. + precision: Option, +} + +/// A directive read up to its conversion byte. +struct ParsedDirective { + spec: Directive, + conversion: u8, + /// Index just past the conversion byte. + end: usize, +} + +/// Parses and renders the directive starting just after its `%`. +fn render_directive( + template: &T::Template, + start: usize, + arguments: &Arguments, + cursor: &mut Cursor, + vm: &mut VM<'_>, +) -> RunResult<(T::Output, usize)> { + let bytes = T::as_bytes(template); + let mut index = start; + // `%(key)` is looked up as soon as it is read, so a missing key reports + // before a malformed spec does. + if bytes.get(index) == Some(&b'(') { + let key_end = find_key_end(bytes, index + 1)?; + let key = T::key_value(template, index + 1..key_end, vm.heap); + lookup_key(key, arguments, cursor, vm)?; + index = key_end + 1; + } + let parsed = parse_directive::(bytes, index, arguments, cursor, vm)?; + + // The argument is taken before the conversion is checked, so `'%5%' % ()` + // reports the missing argument rather than the bad conversion. + let value = next_argument(arguments, cursor, vm)?; + defer_drop!(value, vm); + let spec = &parsed.spec; + let rendered = match parsed.conversion { + b's' => T::text_operand(value, spec, vm).and_then(|text| pad_text(text, spec, &vm.heap.tracker)), + b'b' if T::IS_BYTES => T::text_operand(value, spec, vm).and_then(|text| pad_text(text, spec, &vm.heap.tracker)), + b'r' | b'a' => repr_operand::(value, parsed.conversion, spec, vm) + .and_then(|text| pad_text(text, spec, &vm.heap.tracker)), + b'c' => T::char_operand(value, vm).and_then(|text| pad_text(text, spec, &vm.heap.tracker)), + b'd' | b'i' | b'u' => format_integer::(value, 10, parsed.conversion, spec, vm), + b'o' => format_integer::(value, 8, b'o', spec, vm), + b'x' => format_integer::(value, 16, b'x', spec, vm), + b'X' => format_integer::(value, 16, b'X', spec, vm), + b'e' => format_float::(value, TypeChar::E, spec, vm), + b'E' => format_float::(value, TypeChar::EUpper, spec, vm), + b'f' => format_float::(value, TypeChar::F, spec, vm), + b'F' => format_float::(value, TypeChar::FUpper, spec, vm), + b'g' => format_float::(value, TypeChar::G, spec, vm), + b'G' => format_float::(value, TypeChar::GUpper, spec, vm), + _ => Err(T::unsupported(template, parsed.end - 1)), + }?; + Ok((rendered, parsed.end)) +} + +/// Reads the flags, width, precision, optional C length modifier and +/// conversion byte, consuming the arguments a `*` width or precision names. +fn parse_directive( + template: &[u8], + start: usize, + arguments: &Arguments, + cursor: &mut Cursor, + vm: &mut VM<'_>, +) -> RunResult { + let mut spec = Directive::default(); + let mut index = start; + while let Some(flag) = template.get(index) { + match flag { + b'-' => spec.left = true, + b'+' => spec.sign = Some(Sign::Plus), + b' ' => spec.sign = spec.sign.or(Some(Sign::Space)), + b'#' => spec.alternate = true, + b'0' => spec.zero = true, + _ => break, + } + index += 1; + } + + if template.get(index) == Some(&b'*') { + let width = star_operand(arguments, cursor, vm, ExcType::overflow_c_ssize_t)?; + // A negative `*` width left-justifies, like the `-` flag. + spec.left |= width < 0; + spec.width = usize::try_from(width.unsigned_abs()).map_err(|_| ExcType::overflow_c_ssize_t())?; + index += 1; + } else { + (spec.width, index) = parse_number(template, index, isize::MAX, "width too big")?; + } + + if template.get(index) == Some(&b'.') { + index += 1; + if template.get(index) == Some(&b'*') { + let precision = star_operand(arguments, cursor, vm, ExcType::overflow_c_int)?; + // The precision must fit a C `int`; a negative one clamps to zero. + let precision = i32::try_from(precision).map_err(|_| ExcType::overflow_c_int())?; + spec.precision = Some(usize::try_from(precision).unwrap_or(0)); + index += 1; + } else { + let (precision, next) = parse_number(template, index, i32::MAX as isize, T::PRECISION_TOO_BIG)?; + spec.precision = Some(precision); + index = next; + } + } + + // C length modifiers are accepted and ignored. + if matches!(template.get(index), Some(b'h' | b'l' | b'L')) { + index += 1; + } + + match template.get(index) { + Some(conversion) => Ok(ParsedDirective { + spec, + conversion: *conversion, + end: index + 1, + }), + None => Err(value_error("incomplete format")), + } +} + +/// Finds the `)` closing a `%(key)`, allowing nested parentheses in the key. +fn find_key_end(template: &[u8], start: usize) -> RunResult { + let mut depth = 0usize; + for (offset, byte) in template[start..].iter().enumerate() { + match byte { + b'(' => depth += 1, + b')' if depth == 0 => return Ok(start + offset), + b')' => depth -= 1, + _ => {} + } + } + Err(value_error("incomplete format key")) +} + +/// Parses a run of decimal digits, raising `message` above `max`: CPython +/// bounds a width by `ssize_t` but a precision by C `int`. +fn parse_number(template: &[u8], start: usize, max: isize, message: &str) -> RunResult<(usize, usize)> { + let mut index = start; + let mut number = 0usize; + while let Some(digit) = template.get(index).filter(|byte| byte.is_ascii_digit()) { + number = number + .checked_mul(10) + .and_then(|number| number.checked_add(usize::from(digit - b'0'))) + .filter(|number| isize::try_from(*number).is_ok_and(|number| number <= max)) + .ok_or_else(|| value_error(message))?; + index += 1; + } + Ok((number, index)) +} + +/// Looks `key` up in the mapping operand and makes the result the one +/// remaining argument, as CPython does. Takes ownership of `key`. +fn lookup_key(key: Value, arguments: &Arguments, cursor: &mut Cursor, vm: &mut VM<'_>) -> RunResult<()> { + defer_drop!(key, vm); + let Some(mapping) = &arguments.mapping else { + return Err(ExcType::type_error("format requires a mapping")); + }; + let value = mapping.py_getitem(key, vm)?; + cursor.keyed = true; + cursor.pending.replace(value).drop_with(vm); + Ok(()) +} + +/// Takes the next argument: the pending keyed value if there is one, +/// otherwise the next positional value. +fn next_argument(arguments: &Arguments, cursor: &mut Cursor, vm: &VM<'_>) -> RunResult { + let positional = if cursor.keyed { + None + } else { + arguments.positional.get(cursor.next) + }; + match (cursor.pending.take(), positional) { + (Some(value), _) => Ok(value), + (None, Some(value)) => { + cursor.next += 1; + Ok(value.clone_with_heap(vm.heap)) + } + (None, None) => Err(ExcType::type_error("not enough arguments for format string")), + } +} + +/// Consumes the positional argument a `*` width or precision reads. +fn star_operand( + arguments: &Arguments, + cursor: &mut Cursor, + vm: &mut VM<'_>, + on_overflow: fn() -> RunError, +) -> RunResult { + let value = next_argument(arguments, cursor, vm)?; + defer_drop!(value, vm); + match value.py_value(vm) { + PyValue::Int(integer) => integer.to_i64(vm).ok_or_else(on_overflow), + PyValue::Bool(value) => Ok(i64::from(value)), + _ => Err(ExcType::type_error("* wants int")), + } +} + +/// The `%r` / `%a` operand: `repr()` or `ascii()` for a `str` template, and +/// always `ascii()` for a `bytes` template. +fn repr_operand(value: &Value, conversion: u8, spec: &Directive, vm: &mut VM<'_>) -> RunResult> { + let ascii = T::IS_BYTES || conversion == b'a'; + let text = vm.convert_value(value, if ascii { 3 } else { 2 })?; + Ok(T::text_from_string(text, spec)) +} + +/// Pads a text fragment to the width: text right-aligns unless `-` was +/// given, and the `0` flag is ignored. +fn pad_text(text: Text, spec: &Directive, tracker: &ResourceTracker) -> RunResult { + pad::("", "", text.body, text.len, false, spec, tracker) +} + +/// Renders `%d`/`%i`/`%u` (base 10), `%o`, `%x` and `%X`: the magnitude in +/// `base`, zero-extended to the precision, then signed, prefixed and padded. +fn format_integer( + value: &Value, + base: u32, + conversion: u8, + spec: &Directive, + vm: &mut VM<'_>, +) -> RunResult { + let operand = integer_operand(value, conversion, vm)?; + defer_drop!(operand, vm); + // CPython checks this once the operand is an int, before rendering digits. + if spec + .precision + .is_some_and(|precision| precision > MAX_INTEGER_PRECISION) + { + return Err(SimpleException::new_msg(ExcType::OverflowError, "precision too large").into()); + } + let uppercase = conversion == b'X'; + let (negative, digits) = magnitude_digits(operand, base, uppercase, vm)?; + let digits = zero_extend(digits, spec.precision, &vm.heap.tracker)?; + let prefix = match (spec.alternate, base) { + (true, 8) => "0o", + (true, 16) if uppercase => "0X", + (true, 16) => "0x", + _ => "", + }; + let digits_len = digits.len(); + pad::( + number_sign(negative, spec), + prefix, + T::from_ascii(digits), + digits_len, + spec.zero, + spec, + &vm.heap.tracker, + ) +} + +/// Coerces an integer directive's operand: ints and bools as they are, floats +/// truncated for the decimal directives only, other real numbers through `__int__` +/// for those, anything else through `__index__`. +fn integer_operand(value: &Value, conversion: u8, vm: &mut VM<'_>) -> RunResult { + let decimal = matches!(conversion, b'd' | b'i' | b'u'); + match value.py_value(vm) { + PyValue::Int(_) | PyValue::Bool(_) => Ok(value.clone_with_heap(vm.heap)), + PyValue::Float(value) if decimal => LongInt::value_from_f64(value, vm.heap), + // The decimal directives convert any real number through `__int__` (`Decimal`). + _ if decimal && let Some(int) = value.py_int_impl(vm)? => Ok(int), + _ => { + let requirement = if decimal { "a real number" } else { "an integer" }; + value.py_index_impl(vm)?.ok_or_else(|| { + ExcType::type_error(format!( + "%{} format: {requirement} is required, not {}", + char::from(conversion), + value.py_type_name(vm) + )) + }) + } + } +} + +/// Renders an integer operand's magnitude in `base`, reporting whether it was negative. +fn magnitude_digits(operand: &Value, base: u32, uppercase: bool, vm: &VM<'_>) -> RunResult<(bool, String)> { + match operand.py_value(vm) { + PyValue::Int(integer) => integer.with_value( + vm, + |value| Ok((value < 0, small_digits(value.unsigned_abs(), base, uppercase))), + |value| long_digits(value, base, uppercase, &vm.heap.tracker), + ), + PyValue::Bool(value) => Ok((false, u64::from(value).to_string())), + _ => Err(ExcType::type_error(format!( + "__index__ returned non-int (type {})", + operand.py_type_name(vm) + ))), + } +} + +/// Digits of a machine-word magnitude in base 8, 10 or 16. +fn small_digits(magnitude: u64, base: u32, uppercase: bool) -> String { + match (base, uppercase) { + (8, _) => format!("{magnitude:o}"), + (16, true) => format!("{magnitude:X}"), + (16, false) => format!("{magnitude:x}"), + _ => magnitude.to_string(), + } +} + +/// Digits of a big integer's magnitude, budgeted before the render like +/// `format_long_int`; only decimal is bounded by CPython's digit limit. +fn long_digits(li: &BigInt, base: u32, uppercase: bool, tracker: &ResourceTracker) -> RunResult<(bool, String)> { + if base == 10 { + check_bits_str_digits_limit(li.bits())?; + } + let max_digits = li.bits().div_ceil(u64::from(base.trailing_zeros().max(1))); + check_repeat_size( + 1, + usize::try_from(max_digits).unwrap_or(usize::MAX).saturating_add(2), + tracker, + )?; + let mut digits = li.magnitude().to_str_radix(base); + if uppercase { + digits.make_ascii_uppercase(); + } + Ok((li.is_negative(), digits)) +} + +/// Left-pads digits with zeros up to the precision (`'%.3d' % 5` → `005`). +fn zero_extend(digits: String, precision: Option, tracker: &ResourceTracker) -> RunResult { + let target = precision.unwrap_or(0); + if digits.len() >= target { + Ok(digits) + } else { + let mut output = StringBuilder::with_capacity(target, tracker)?; + output.push_repeated('0', target - digits.len())?; + output.push_str(&digits)?; + output.finish_raw() + } +} + +/// Renders the `%e`/`%f`/`%g` family through the shared f-string formatters, +/// then re-signs and pads the digit text the printf way. +fn format_float( + value: &Value, + type_char: TypeChar, + spec: &Directive, + vm: &mut VM<'_>, +) -> RunResult { + let number = float_operand::(value, vm)?; + let precision = spec.precision.unwrap_or(6); + // CPython bounds the precision by `INT_MAX - 1024` before looking at the + // value, so `inf`/`nan` are rejected too. + if precision > MAX_FLOAT_PRECISION { + return Err(ExcType::value_error_precision_too_big()); + } + // The precision may come from an argument (`%.*f`), and the fixed and + // exponent formatters synthesise that many digits; `inf`/`nan` print as is. + let tracker = &vm.heap.tracker; + if number.is_finite() { + check_repeat_size(1, precision, tracker)?; + } + let parsed = ParsedFormatSpec { + alternate: spec.alternate, + precision: Some(precision), + type_char: Some(type_char), + ..ParsedFormatSpec::default() + }; + let mut text = match type_char { + TypeChar::E => format_float_e(number, &parsed, false, tracker), + TypeChar::EUpper => format_float_e(number, &parsed, true, tracker), + TypeChar::G | TypeChar::GUpper => format_float_g(number, &parsed, tracker), + _ => format_float_f(number, &parsed, tracker), + }?; + // The formatter signs negatives itself; printf's flags decide the sign here. + let negative = text.starts_with('-'); + if negative { + text.remove(0); + } + let body_len = text.len(); + pad::( + number_sign(negative, spec), + "", + T::from_ascii(text), + body_len, + spec.zero, + spec, + tracker, + ) +} + +/// Coerces a float directive's operand: floats and ints directly, big ints +/// when they fit a float, anything else through `__float__` or `__index__`. +fn float_operand(value: &Value, vm: &mut VM<'_>) -> RunResult { + match value.py_value(vm) { + PyValue::Float(value) => Ok(value), + PyValue::Bool(value) => Ok(f64::from(value)), + PyValue::Int(integer) => match integer.to_f64(vm) { + Some(f) if f.is_finite() => Ok(f), + _ => Err(T::float_overflow_error()), + }, + _ => { + // `__float__` first (`Decimal`), then `__index__`, as `PyFloat_AsDouble` does. + if let Some(f) = value.py_float_impl(vm)? { + Ok(f) + } else if let Some(index) = value.py_index_impl(vm)? { + defer_drop!(index, vm); + float_operand::(index, vm) + } else { + Err(T::float_type_error(&value.py_type_name(vm))) + } + } + } +} + +/// Renders a `str` `%c`: a one-character string as itself, otherwise an +/// integer code point. +fn char_text(value: &Value, vm: &mut VM<'_>) -> RunResult { + match value.py_value(vm) { + PyValue::Int(integer) => char_from_code(integer.to_i64(vm).ok_or_else(char_range_error)?), + PyValue::Bool(value) => char_from_code(i64::from(value)), + PyValue::Str(value) => { + let text = value.as_str(vm); + let mut chars = text.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) => Ok(c.to_string()), + _ => Err(ExcType::type_error(format!( + "%c requires an int or a unicode character, not a string of length {}", + text.chars().count() + ))), + } + } + _ => match value.py_index_impl(vm)? { + Some(index) => { + defer_drop!(index, vm); + char_text(index, vm) + } + None => Err(ExcType::type_error(format!( + "%c requires an int or a unicode character, not {}", + value.py_type_name(vm) + ))), + }, + } +} + +/// The character for a `str` `%c` code point; surrogates are rejected with +/// the range error, as `chr()` does. +fn char_from_code(code: i64) -> RunResult { + u32::try_from(code) + .ok() + .filter(|code| *code <= 0x0010_FFFF) + .and_then(char::from_u32) + .map(|c| c.to_string()) + .ok_or_else(char_range_error) +} + +/// CPython's out-of-range error for a `str` `%c`. +fn char_range_error() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "%c arg not in range(0x110000)").into() +} + +/// Renders a `bytes` `%c`: a one-byte `bytes` as itself, otherwise an +/// integer in `range(256)`. +fn byte_char(value: &Value, vm: &mut VM<'_>) -> RunResult { + match value.py_value(vm) { + PyValue::Int(integer) => { + u8::try_from(integer.to_i64(vm).ok_or_else(byte_range_error)?).map_err(|_| byte_range_error()) + } + PyValue::Bool(value) => Ok(u8::from(value)), + PyValue::Bytes(value) => single_byte(value.as_slice(vm)), + _ => match value.py_index_impl(vm)? { + Some(index) => { + defer_drop!(index, vm); + byte_char(index, vm) + } + None => Err(ExcType::type_error(format!( + "%c requires an integer in range(256) or a single byte, not {}", + value.py_type_name(vm) + ))), + }, + } +} + +/// The one byte of a `bytes` `%c` operand. +fn single_byte(bytes: &[u8]) -> RunResult { + match bytes { + [byte] => Ok(*byte), + _ => Err(ExcType::type_error(format!( + "%c requires an integer in range(256) or a single byte, not a bytes object of length {}", + bytes.len() + ))), + } +} + +/// CPython's out-of-range error for a `bytes` `%c`. +fn byte_range_error() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, "%c arg not in range(256)").into() +} + +/// The sign printf emits: `-` for negatives, else `+` or a space on request. +fn number_sign(negative: bool, spec: &Directive) -> &'static str { + match spec.sign { + _ if negative => "-", + Some(Sign::Plus) => "+", + Some(Sign::Space) => " ", + _ => "", + } +} + +/// Pads `sign + prefix + body` to the width: `-` left-justifies, otherwise +/// spaces lead, or zeros sit between the prefix and the body under `zero_fill`. +/// A body with nothing to add is returned as it is, so `'%s' % s` copies once. +fn pad( + sign: &str, + prefix: &str, + body: T::Output, + body_len: usize, + zero_fill: bool, + spec: &Directive, + tracker: &ResourceTracker, +) -> RunResult { + let padding = spec.width.saturating_sub(sign.len() + prefix.len() + body_len); + if padding == 0 && sign.is_empty() && prefix.is_empty() { + Ok(body) + } else { + // The width may come from an argument (`%*s`), so the reservation budgets the padding. + let capacity = sign.len() + prefix.len() + T::byte_len(&body) + padding; + let mut output = >::with_capacity(capacity, tracker)?; + if spec.left { + output.push_text(sign)?; + output.push_text(prefix)?; + output.push_output(&body)?; + output.push_fill(b' ', padding)?; + } else if zero_fill { + output.push_text(sign)?; + output.push_text(prefix)?; + output.push_fill(b'0', padding)?; + output.push_output(&body)?; + } else { + output.push_fill(b' ', padding)?; + output.push_text(sign)?; + output.push_text(prefix)?; + output.push_output(&body)?; + } + output.finish() + } +} + +/// CPython's `unsupported format character` error: `shown` is the quoted +/// character (the target decides when that is `?`), `conversion` the one +/// reported in hex. +fn unsupported_character(shown: char, conversion: char, index: usize) -> RunError { + value_error(format!( + "unsupported format character '{shown}' (0x{:x}) at index {index}", + u32::from(conversion) + )) +} diff --git a/crates/bashkit-monty/src/predicate.rs b/crates/bashkit-monty/src/predicate.rs new file mode 100644 index 000000000..0a7f8a6ec --- /dev/null +++ b/crates/bashkit-monty/src/predicate.rs @@ -0,0 +1,20 @@ +//! Calling a user-supplied predicate and taking its truthiness. +//! +//! Shared by `filter` and the `itertools` adaptors `takewhile`, `dropwhile` +//! and `filterfalse`, which differ only in what they do with the answer. + +use crate::{args::ArgValues, bytecode::VM, defer_drop, exception_private::RunResult, types::PyTrait, value::Value}; + +/// Applies `predicate` to `item` and returns its truthiness. +/// +/// `item` is only borrowed — the call gets its own reference, so the caller can +/// still yield the item afterwards. Goes through `evaluate_function`, which +/// runs a defined function's frame to completion, so a predicate that suspends +/// (an external function, an `os` call) is rejected rather than paused. +pub(crate) fn call_predicate(predicate: &Value, item: &Value, vm: &mut VM<'_>) -> RunResult { + let arg = item.clone_with_heap(vm.heap); + let result = vm.evaluate_function(predicate, ArgValues::One(arg))?; + // Guarded because `py_bool` can raise through a user `__bool__`. + defer_drop!(result, vm); + result.py_bool(vm) +} diff --git a/crates/bashkit-monty/src/prepare.rs b/crates/bashkit-monty/src/prepare.rs new file mode 100644 index 000000000..a8c6fcc3b --- /dev/null +++ b/crates/bashkit-monty/src/prepare.rs @@ -0,0 +1,4174 @@ +use std::mem; + +use ahash::{AHashMap, AHashSet, RandomState}; +use indexmap::IndexMap; + +use crate::{ + args::{ArgExprs, CallArg, CallKwarg, Signature}, + builtins::Builtins, + expressions::{ + AssignTarget, Callable, CaptureSource, Comprehension, DictItem, Expr, ExprLoc, Identifier, ImportName, + MatchCase, NameScope, Node, Pattern, PreparedFunctionDef, PreparedNode, SequenceItem, UnpackTarget, + }, + fstring::{FStringPart, FormatSpec}, + intern::{CompileInterns, StringId}, + name_map::{NameMap, namespace_overflow}, + namespace::NamespaceId, + parse::{CodeRange, ExceptHandler, ParseError, ParseNode, ParsedSignature, RawFunctionDef, Try}, +}; + +/// Mutable handle to the module's global [`NameMap`], threaded through +/// nested function preparers so an inner `global X` (or a function-scope +/// implicit global read) can allocate a module slot at the point of +/// discovery. +/// +/// Replaces the previous "snapshot the module's name_map per function, +/// collect discovered globals into a `discovered_globals` set, materialize +/// post-hoc" bubble-up. With the live borrow we allocate eagerly: a function +/// scope's `get_id` calls `ensure_slot` directly on the module's `NameMap` +/// via this handle, and `prepare_function_def` has nothing to bubble up. +struct GlobalsRef<'g> { + globals: &'g mut NameMap, +} + +impl GlobalsRef<'_> { + /// Returns the slot for `name`, allocating a new module-level slot if absent. + fn ensure_slot(&mut self, name: StringId, position: CodeRange) -> Result { + self.globals.ensure_slot(name, position) + } + + /// Re-borrows for shorter-lived use (e.g. passing to a nested inner preparer). + fn reborrow(&mut self) -> GlobalsRef<'_> { + GlobalsRef { globals: self.globals } + } +} + +/// Prepares parsed nodes for REPL-style incremental compilation using an existing global namespace. +/// +/// Existing bindings keep their original namespace slots; any new names are appended with new slots. +/// This ensures snippets can be compiled independently while sharing one persistent global namespace. +/// `globals` is borrowed so a snippet that fails here leaves the session's map intact +/// (plus any slots already appended, which are stable and harmless). +pub(crate) fn prepare_with_existing_names( + nodes: Vec, + interner: &CompileInterns<'_>, + globals: &mut NameMap, +) -> Result, ParseError> { + let mut prepared_nodes = Prepare::new_module(globals, interner).prepare_nodes(nodes)?; + + // In the root frame, the last expression is implicitly returned if it + // is not `None`. This matches Python REPL behavior where the last + // expression value is displayed / returned. + if let Some(Node::Expr(expr_loc)) = prepared_nodes.last() + && !expr_loc.expr.is_none() + { + let new_expr_loc = expr_loc.clone(); + prepared_nodes.pop(); + prepared_nodes.push(Node::Return(Some(new_expr_loc))); + } + + Ok(prepared_nodes) +} + +/// How the top-level names of an `eval()` / `exec()` snippet bind. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SnippetNames { + /// An ordinary module compile against the session `NameMap` (`LoadGlobal`): + /// the implicit form at module scope. + Slots, + /// Top level by name, nested scopes by slot: the implicit form inside a + /// function or class body (slot globals plus a locals snapshot), or + /// `eval(src, None, locals)`. + NameOverSlots, + /// Everything by name against an explicit globals dict. + NameOverDict, +} + +/// Prepares an `eval()` / `exec()` snippet for [`Compiler::compile_snippet`](crate::bytecode::Compiler::compile_snippet). +/// +/// Unlike [`prepare_with_existing_names`] there is no implicit return of a +/// trailing expression: `exec` returns `None` and `eval` parses one expression +/// it returns itself. `globals` is the session map for the slot modes and a +/// scratch map under [`SnippetNames::NameOverDict`], so names that only exist +/// inside a dict-namespaced snippet never consume session slots. +pub(crate) fn prepare_snippet( + nodes: Vec, + interner: &CompileInterns<'_>, + globals: &mut NameMap, + names: SnippetNames, +) -> Result, ParseError> { + let mut prepare = Prepare::new_module(globals, interner); + if names != SnippetNames::Slots { + prepare.top_level_by_name = true; + // `global x` at the top level binds in the globals (CPython emits + // `STORE_GLOBAL` there), so those names keep slot resolution. + let (mut nonlocals, mut assigned) = (AHashSet::new(), AHashSet::new()); + for node in &nodes { + collect_scope_info_from_node( + node, + &mut prepare.module_global_names, + &mut nonlocals, + &mut assigned, + interner, + ); + } + } + prepare.prepare_nodes(nodes) +} + +/// State machine for the preparation phase that transforms parsed AST nodes into a prepared form. +/// +/// Resolves names to namespace slots and rewrites the AST so the bytecode +/// compiler can consume it directly. Scope-dependent fields live in +/// [`PrepareState`] so module and function paths don't share a single +/// `Option<...>` for "is this function scope?" sentinel. +/// +/// The interner is borrowed immutably — every `StringId` we need already +/// arrived through the AST (parse-time interning), so no new strings are +/// allocated during prepare. +struct Prepare<'i, 'g> { + /// String interner for resolving names in error messages. + interner: &'i CompileInterns<'i>, + /// Live mutable handle to the module's global [`NameMap`]. + /// + /// At module scope this points to the same `NameMap` that PrepareState + /// returns through `is_module_scope` checks (module locals ARE + /// globals), so name resolution at module scope routes every binding + /// through this handle. At function scope it points to the same + /// handle re-borrowed from the parent preparer, used both to resolve + /// `global X` and as the fallback when a free name doesn't match any + /// local / enclosing binding. + globals: GlobalsRef<'g>, + /// Distinguishes module vs function scope and holds scope-specific state. + state: PrepareState, + /// Names assigned so far during the second pass (in source order). + /// + /// Drives the "name 'x' is assigned to before global/nonlocal + /// declaration" diagnostic. Tracked at module scope too — the + /// validation only runs at function scope, but unconditionally + /// populating the set keeps the code paths uniform. + names_assigned_in_order: AHashSet, + /// Names read or written so far during the second pass. + /// + /// Drives the "name 'x' is used prior to global/nonlocal declaration" + /// diagnostic. Populated by [`Prepare::get_id`] at every name + /// occurrence in this scope (reads and assignment targets alike). + /// Distinct from `names_assigned_in_order` because the corresponding + /// error messages differ — assignments report "assigned to before", + /// non-assignment uses report "used prior to". + names_used: AHashSet, + /// Number of comprehension-variable slots currently in use. + /// + /// Allocated bottom-up as comprehension target names are encountered and + /// released when the surrounding comprehension finishes. IDs are unique + /// among simultaneously active comprehensions; siblings reuse them. + comp_var_depth: u16, + /// Highest `comp_var_depth` reached since it was last reset. + /// + /// Lets a comprehension reserve every slot its first iterable used, however deeply nested. + comp_var_peak: u16, + /// Stack of comprehension-name → binding maps for currently active comprehensions. + /// + /// Pushed on entry to a comprehension, popped on exit. Read by `get_id` + /// (the **expression-position** read path) before falling through to the + /// regular name-resolution cascade so a comprehension target shadows any + /// same-named enclosing binding. Walrus and other assignment-position + /// stores must bypass this stack (see [`Prepare::get_id_for_store_target`]) + /// so PEP 572 binding semantics are preserved. + comp_name_scopes: Vec, + /// True when this preparer is for a **class body** (see `prepare_class_def`). + /// + /// Class scope is skipped for method free-var resolution in CPython: a + /// method (or lambda) defined in the class body may capture variables from + /// scopes *enclosing the class*, but must NOT see sibling methods or class + /// variables by bare name. [`Self::child_enclosing_locals`] honours this by + /// excluding our own (class-member) locals when this flag is set. + is_class_scope: bool, + /// True when preparing the top level of an `eval()` / `exec()` snippet + /// whose names resolve at runtime (see [`SnippetNames`]): module-level + /// names become [`NameScope::Name`] and builtins are never substituted at + /// compile time, since a namespace dict may shadow them. + top_level_by_name: bool, + /// Names declared `global` at a by-name snippet's top level; they keep + /// slot resolution. Empty otherwise. + module_global_names: AHashSet, + /// Class members whose binding statement has already been prepared, in + /// source order (only populated when `is_class_scope`). + /// + /// CPython class bodies resolve name reads with `LOAD_NAME` semantics: + /// class locals → globals → builtins, decided at *runtime*. Because Monty + /// restricts class bodies to linear statements (no control flow, walrus, + /// `del`, or `exec`-style namespace mutation), source order IS execution + /// order, so the runtime question "is this member bound yet?" is decidable + /// at prepare time: a read of a member listed here uses its local slot; a + /// read of a not-yet-bound member falls back to a late-bound global load + /// (see [`Self::get_id_read`]). If class bodies ever allow conditional + /// bindings this must become a runtime-fallback opcode instead. + bound_class_members: AHashSet, +} + +/// Insertion-ordered bindings for one active comprehension's lexical scope. +type CompNameScope = IndexMap; + +/// Preparation metadata for a target in an active comprehension scope. +#[derive(Clone, Copy)] +struct CompBinding { + /// Scratch-slot identifier shared by the target and its expression reads. + slot: u16, + /// Whether a nested callable captured this target. + captured: bool, +} + +/// Prepared parts shared by list, set, and dict comprehensions. +struct PreparedComprehension { + /// Prepared generator clauses in source order. + generators: Vec, + /// Prepared list/set element, absent for dict comprehensions. + elt: Option, + /// Prepared dict key and value, absent for list/set comprehensions. + key_value: Option<(ExprLoc, ExprLoc)>, + /// Captured lexical target slots in allocation order. + captured_slots: Vec, +} + +/// Scope-specific state for [`Prepare`]. +/// +/// Splitting Module / Function into distinct variants instead of a tangle +/// of `Option<...>` fields makes the two-scope distinction explicit at +/// every callsite and lets the function variant own a coherent block of +/// fields that simply don't apply at module scope (free vars, cell vars, +/// enclosing-locals, …). +enum PrepareState { + /// Module-level code. Every name binds in the module's globals + /// [`NameMap`] (reached through `Prepare::globals`). + Module, + /// A function (or lambda) body. + /// + /// Boxed to keep the discriminant cheap — `FunctionState` is much + /// larger than the unit `Module` variant. + Function(Box), +} + +/// State that only makes sense for function-scope preparation. +/// +/// At module scope the equivalent "locals" ARE the globals, the function +/// declarations (`global X`, `nonlocal X`) cannot exist, and there is no +/// enclosing scope to capture from — so encoding all of this as +/// `PrepareState::Function` keeps module-scope code paths free of +/// `if !is_module_scope()` ceremony. +struct FunctionState { + /// Local namespace for this function. + /// + /// Layout: `[params][cell_vars][free_vars][assigned-during-body locals]`. + /// `locals.len()` is the function's runtime `namespace_size`. + locals: NameMap, + /// Names declared `global` in this function — resolve to module globals. + global_names: AHashSet, + /// Names bound in THIS scope (params + body-assigned, minus globals). + /// A read of any of these resolves to `NameScope::Local`. + assigned_names: AHashSet, + /// Names bound in ANY enclosing function scope (transitive closure). + /// + /// Includes each ancestor's params, locals, cells, and pass-through + /// free vars. Used to validate `nonlocal` declarations (the name must + /// exist somewhere up the chain) and to identify implicit closure + /// captures (a free read that resolves through this set becomes a free + /// var here and a cell var on the binding ancestor). + /// + /// Empty for a top-level function (defined directly in a module body) — + /// at that point there's no enclosing function to capture from. + enclosing_locals: AHashSet, + /// Free variables: name → namespace slot of the cell reference. + /// + /// Pre-populated with nonlocal declarations and implicit captures at + /// initialization, then extended as new captures are discovered while + /// nested functions are prepared. + free_var_map: AHashMap, + /// Cell variables (locals captured by nested functions): name → slot. + /// + /// Pre-populated with names that scope analysis identified as + /// captured (excluding pass-throughs that are also free vars here). + cell_var_map: AHashMap, +} + +impl<'i, 'g> Prepare<'i, 'g> { + /// Returns `true` if this preparer is for module-level code. + fn is_module_scope(&self) -> bool { + matches!(self.state, PrepareState::Module) + } + + /// Allocates (or returns the existing) slot for `name_id` in the + /// current scope's namespace. At module scope this reaches into the + /// module globals; at function scope, the function's `locals`. + /// + /// Used by the walrus pre-allocation pass in `prepare_comprehension` + /// where the slot must exist before the comprehension's body is walked, + /// independent of whether the enclosing scope is module-level or a + /// function body. + fn ensure_scope_slot(&mut self, name_id: StringId, position: CodeRange) -> Result { + match &mut self.state { + PrepareState::Module => self.globals.ensure_slot(name_id, position), + PrepareState::Function(state) => state.locals.ensure_slot(name_id, position), + } + } + + /// Builds the `enclosing_locals` set for a child scope (function, lambda, + /// or class body) about to be prepared under `self`. + /// + /// This is the **transitive** set: our own locals (params, body-assigned, + /// cells, free vars) **plus** everything we ourselves can capture + /// (`enclosing_locals`). Threading `enclosing_locals` through is what lets a + /// deeply nested function capture a variable several levels up: without it, + /// an intermediate scope that doesn't itself mention the variable would hide + /// it from its own children (issue #477). Empty at module scope (module + /// globals are reached via `global`, not closure capture). + /// + /// Names this scope declares `global` are excluded: such a name is not a + /// local binding here, so a nested function referencing it must resolve to + /// the module global rather than capture a (non-existent) cell — e.g. + /// `def mid(): global x; x = 1; def inner(): return x` reads the global `x`. + fn child_enclosing_locals(&self) -> AHashSet { + let mut locals = match &self.state { + PrepareState::Module => AHashSet::new(), + PrepareState::Function(state) if self.is_class_scope => { + // Class scope is skipped for method free-var resolution (CPython): + // a method/lambda defined in the class body may capture variables + // from scopes *enclosing the class* — what we ourselves capture + // (`free_var_map`) plus what we can reach further up + // (`enclosing_locals`) — but must NOT see sibling methods or class + // variables by bare name. + let mut locals: AHashSet = state.free_var_map.keys().copied().collect(); + locals.extend(state.enclosing_locals.iter().copied()); + locals.retain(|name| !state.global_names.contains(name)); + locals + } + PrepareState::Function(state) => { + let mut locals = state.assigned_names.clone(); + for (_, name_id) in state.locals.iter() { + locals.insert(name_id); + } + locals.extend(state.enclosing_locals.iter().copied()); + locals.retain(|name| !state.global_names.contains(name)); + locals + } + }; + // Active comprehension targets are lexical locals even at module scope. + // The innermost binding is selected later when the child's captures are + // finalized; the set only needs to tell scope analysis that capture is possible. + for scope in &self.comp_name_scopes { + locals.extend(scope.keys().copied()); + } + locals + } + + /// Returns the source in THIS scope holding the cell for a child capture. + /// + /// Used to populate `PreparedFunctionDef::free_var_enclosing_slots`, which + /// compilation resolves to either a namespace or comprehension stack slot. + /// + /// Lookup order mirrors lexical shadowing and bubble-up classification: + /// - The innermost active comprehension binding. + /// - Our `cell_var_map` (we own the cell — the local belongs to us). + /// - Our `free_var_map` (we captured the cell from further up; + /// it's a pass-through). + /// - At module scope, the module globals (a top-level function's free + /// var must resolve to a module slot — practically unreachable + /// because top-level functions can't have implicit captures). + fn lookup_captured_slot(&mut self, name_id: StringId) -> CaptureSource { + for scope in self.comp_name_scopes.iter_mut().rev() { + if let Some(binding) = scope.get_mut(&name_id) { + binding.captured = true; + return CaptureSource::CompVar(binding.slot); + } + } + if let PrepareState::Function(state) = &self.state { + if let Some(&slot) = state.cell_var_map.get(&name_id) { + return CaptureSource::Namespace(slot); + } + if let Some(&slot) = state.free_var_map.get(&name_id) { + return CaptureSource::Namespace(slot); + } + } + if let Some(slot) = self.globals.globals.get(name_id) { + return CaptureSource::Namespace(slot); + } + let name_str = self.interner.get_str(name_id); + panic!("free_var '{name_str}' not found in enclosing scope's cells, comprehension targets, or globals"); + } + + /// Inner-to-outer scope hand-off when a just-prepared child scope reports a + /// capture that wasn't predicted by scope analysis. + /// + /// The recursive [`collect_referenced_names_from_node`] pass below + /// pre-populates most transitively captured names before the body is + /// walked, but its `ClassDef` arm collects only decorators, nothing from the + /// class body — so for a capture chain that flows through a class body (a + /// method capturing an enclosing function's local), this bubble-up is + /// **load-bearing**, not a safety net: it is the only mechanism that + /// registers the intermediate scopes' cells. It classifies each late + /// discovery: + /// + /// - Already a cell or free var here → nothing to do. + /// - Bound locally (params or body-assigned) → register as a cell var here. + /// - Bound in an ancestor scope (`enclosing_locals`) → register as a + /// pass-through free var here so the cell propagates upward. + /// - Otherwise the child shouldn't have added it to `free_var_map` in + /// the first place; we surface a panic naming the offending variable. + fn bubble_up_captured_name(&mut self, captured_name: StringId, position: CodeRange) -> Result<(), ParseError> { + for scope in self.comp_name_scopes.iter_mut().rev() { + if let Some(binding) = scope.get_mut(&captured_name) { + binding.captured = true; + return Ok(()); + } + } + + let PrepareState::Function(state) = &mut self.state else { + return Ok(()); + }; + + if state.cell_var_map.contains_key(&captured_name) || state.free_var_map.contains_key(&captured_name) { + return Ok(()); + } + + if state.assigned_names.contains(&captured_name) || state.locals.contains(captured_name) { + let slot = state.locals.ensure_slot(captured_name, position)?; + state.cell_var_map.insert(captured_name, slot); + } else if state.enclosing_locals.contains(&captured_name) { + let slot = state.locals.ensure_slot(captured_name, position)?; + state.free_var_map.insert(captured_name, slot); + } else { + let name_str = self.interner.get_str(captured_name); + panic!("bubble-up captured '{name_str}' that is bound nowhere — scope analysis bug"); + } + Ok(()) + } + + /// Builds the parallel free-var slot vectors for a just-prepared child + /// scope from its `free_var_map` (`name -> the child's own slot`). + /// + /// Returns `(free_var_slots, free_var_enclosing_slots)`: the first holds the + /// child's own slots (where it installs each captured cell at call time); + /// the second holds OUR slot it reads that cell from when the closure is + /// built (via [`Self::lookup_captured_slot`]). Both are ordered by the + /// child slot so they stay index-aligned. + fn build_free_var_slots( + &mut self, + inner_free_var_map: AHashMap, + ) -> (Vec, Vec) { + let mut entries: Vec<_> = inner_free_var_map.into_iter().collect(); + entries.sort_by_key(|(_, inner_slot)| *inner_slot); + let inner_slots = entries.iter().map(|(_, slot)| *slot).collect(); + let enclosing_slots = entries + .into_iter() + .map(|(var_name, _)| self.lookup_captured_slot(var_name)) + .collect(); + (inner_slots, enclosing_slots) + } + + /// Records a freshly-prepared child scope's captures against `self` and + /// builds the child's closure-slot vectors. + /// + /// Shared tail of [`Self::prepare_function_def`], [`Self::prepare_lambda`] + /// and [`Self::prepare_class_def`]. `inner_free_var_map` / + /// `inner_cell_var_map` are the child's maps, already moved out of the child + /// preparer — which **must** have been dropped first so its `GlobalsRef` + /// borrow is released before this mutates `self`. Each name the child + /// captured is filed against us as an owned cell or a pass-through free var + /// (see [`Self::bubble_up_captured_name`]). + fn finalize_child_scope( + &mut self, + inner_free_var_map: AHashMap, + inner_cell_var_map: AHashMap, + param_names: &[StringId], + position: CodeRange, + ) -> Result { + // Bubble-up: each captured name in the child's `free_var_map` must be + // backed by a slot in OUR namespace. Recursive scope analysis predicts + // most of these via `cell_var_names`, but captures that flow through a + // class body are only discovered here (see `bubble_up_captured_name`), + // so this loop is required for correctness — do not remove it on the + // assumption that scope analysis already covered everything. + for &captured_name in inner_free_var_map.keys() { + self.bubble_up_captured_name(captured_name, position)?; + } + // Build the explicit closure-slot vectors the runtime installs at frame + // setup (see `install_closure_cells`): the child's own free-var slots + // paired with OUR slot each captured cell is read from, and the child's + // owned-cell slots paired with the param index each is seeded from. + let (free_var_slots, free_var_enclosing_slots) = self.build_free_var_slots(inner_free_var_map); + let (cell_var_slots, cell_param_indices) = build_cell_slots(inner_cell_var_map, param_names); + Ok(FinalizedScope { + free_var_enclosing_slots, + free_var_slots, + cell_var_slots, + cell_param_indices, + }) + } + + /// Borrows the caller's global slots so nested functions can assign new ones. + /// The caller restores those provisional slots if compilation fails. + fn new_module(globals: &'g mut NameMap, interner: &'i CompileInterns<'i>) -> Self { + Self { + interner, + globals: GlobalsRef { globals }, + state: PrepareState::Module, + names_assigned_in_order: AHashSet::new(), + names_used: AHashSet::new(), + comp_var_depth: 0, + comp_var_peak: 0, + comp_name_scopes: Vec::new(), + top_level_by_name: false, + module_global_names: AHashSet::new(), + is_class_scope: false, + bound_class_members: AHashSet::new(), + } + } + + /// Creates a new Prepare instance for function-level code. + /// + /// Pre-populates `free_var_map` with nonlocal declarations and implicit captures, + /// and `cell_var_map` with cell variables (excluding pass-through variables). + /// + /// # Arguments + /// * `params` - Function parameter `StringId`s (pre-registered in the local namespace). + /// * `position` - Source position of the function header, used to anchor namespace-overflow errors. + /// * `assigned_names` - Names bound in this function (params ∪ body-assigned, minus globals). + /// * `global_names` - Names declared as `global` in this function. + /// * `nonlocal_names` - Names declared as `nonlocal` in this function. + /// * `implicit_captures` - Names captured from an enclosing scope without an explicit nonlocal. + /// * `globals` - Live handle to the module-level `NameMap`. + /// * `enclosing_locals` - Names bound in ANY enclosing function (transitive closure). + /// * `cell_var_names` - Names that nested functions capture from this scope. + /// * `interner` - String interner for looking up names in diagnostics. + #[expect(clippy::too_many_arguments)] + fn new_function( + params: &[StringId], + position: CodeRange, + assigned_names: AHashSet, + global_names: AHashSet, + nonlocal_names: &AHashSet, + implicit_captures: &AHashSet, + globals: GlobalsRef<'g>, + enclosing_locals: AHashSet, + cell_var_names: &AHashSet, + interner: &'i CompileInterns<'i>, + ) -> Result { + // Reject duplicate parameter names while building `locals`. + // Ruff's parser accepts `def f(x, x)` that CPython rejects at + // compile time; without this check, `locals` is deduplicated by + // `NameMap` semantics but each positional `NamespaceId` came from + // the parameter index, so the duplicate would land past the + // allocated stack region and panic `load_local` at runtime. + let mut locals = NameMap::with_capacity(params.len() + cell_var_names.len()); + for &name_id in params { + if locals.contains(name_id) { + let name_str = interner.get_str(name_id); + return Err(ParseError::syntax( + format!("duplicate argument '{name_str}' in function definition"), + position, + )); + } + locals.ensure_slot(name_id, position)?; + } + + // Namespace layout: params occupy slots `0..params.len()`, then cell + // vars, captured free vars, and ordinary body-assigned locals follow, + // assigned in that order below. The regions are NOT guaranteed + // contiguous — a late-discovered pass-through free var (see + // `bubble_up_captured_name`) can land in the locals region — so the + // runtime does not assume contiguity: cell/free slots are carried + // explicitly (`cell_var_slots`/`free_var_slots`) and installed + // individually at frame setup (see `install_closure_cells`). Every name + // is still bound into `locals` up front so the reverse map slot → name + // is complete from the start — that's what the VM needs to label + // `UnboundLocalError` / free-var `NameError` messages without consulting + // a separate side table. + + // Pre-populate cell_var_map with cell variables FIRST (right after params). + // Excludes pass-through variables (names that are both nonlocal / + // implicit captures AND captured by nested functions — these stay + // in `free_var_map` since we receive the cell from the enclosing + // frame instead of allocating one). + // + // We use `push_aliased_slot` here, not `ensure_slot`, so that a + // cell variable whose name matches a parameter (e.g. + // `def f(n): return lambda x: x + n`) gets a fresh slot for the + // cell — distinct from the parameter slot. The runtime copies the + // parameter value into the cell at call time + // (see [`PreparedFunctionDef::cell_param_indices`]). + let mut cell_var_map = AHashMap::with_capacity(cell_var_names.len()); + for &name in cell_var_names { + if !nonlocal_names.contains(&name) && !implicit_captures.contains(&name) { + let slot = locals.push_aliased_slot(name, position)?; + cell_var_map.insert(name, slot); + } + } + + // Pre-populate free_var_map with nonlocal declarations AND + // implicit captures, after cell_vars. Same aliased-slot rationale: + // a free var sharing a name with a parameter must still get its + // own slot to carry the captured cell reference. + let free_var_capacity = nonlocal_names.len() + implicit_captures.len(); + let mut free_var_map = AHashMap::with_capacity(free_var_capacity); + for name in nonlocal_names.iter().copied().chain(implicit_captures.iter().copied()) { + let slot = locals.push_aliased_slot(name, position)?; + free_var_map.insert(name, slot); + } + + Ok(Self { + interner, + globals, + state: PrepareState::Function(Box::new(FunctionState { + locals, + global_names, + assigned_names, + enclosing_locals, + free_var_map, + cell_var_map, + })), + names_assigned_in_order: AHashSet::new(), + names_used: AHashSet::new(), + comp_var_depth: 0, + comp_var_peak: 0, + comp_name_scopes: Vec::new(), + top_level_by_name: false, + module_global_names: AHashSet::new(), + is_class_scope: false, + bound_class_members: AHashSet::new(), + }) + } + + /// Recursively prepares a sequence of AST nodes by resolving names and transforming expressions. + /// + /// This method processes each node type differently: + /// - Resolves variable names to namespace indices + /// - Transforms function calls from identifier-based to builtin type-based + /// - Handles special cases like implicit returns in root frames + /// - Validates that names used in attribute calls are already defined + /// + /// # Returns + /// A vector of prepared nodes ready for compilation + fn prepare_nodes(&mut self, nodes: Vec) -> Result, ParseError> { + let nodes_len = nodes.len(); + let mut new_nodes = Vec::with_capacity(nodes_len); + for node in nodes { + match node { + Node::Pass => (), + Node::Expr(expr) => new_nodes.push(Node::Expr(self.prepare_expression(expr)?)), + Node::Return(expr) => new_nodes.push(Node::Return(match expr { + Some(expr) => Some(self.prepare_expression(expr)?), + None => None, + })), + Node::Raise(exc) => { + let expr = match exc { + Some(expr) => { + let prepared = self.prepare_expression(expr)?; + match prepared.expr { + // Handle raising a builtin exception type without instantiation, + // e.g. `raise TypeError`. Transform into `raise TypeError()` + // so the exception is properly instantiated before being raised. + Expr::Builtin(b) => { + let call_expr = Expr::Call { + callable: Callable::Builtin(b), + args: Box::new(ArgExprs::Empty), + }; + Some(ExprLoc::new(prepared.position, call_expr)) + } + _ => Some(prepared), + } + } + None => None, + }; + new_nodes.push(Node::Raise(expr)); + } + Node::Assert { test, msg } => { + let test = self.prepare_expression(test)?; + let msg = match msg { + Some(m) => Some(self.prepare_expression(m)?), + None => None, + }; + new_nodes.push(Node::Assert { test, msg }); + } + Node::Assign { target, object } => { + let object = self.prepare_expression(object)?; + // Track that this name was assigned before we call get_id + self.names_assigned_in_order.insert(target.name_id); + let target = self.get_id(target)?; + // In a class body, the member becomes bound only now — the + // value expression above must see the pre-binding state + // (`x = x + 1` reads the global `x`, like CPython). + if self.is_class_scope { + self.bound_class_members.insert(target.name_id); + } + new_nodes.push(Node::Assign { target, object }); + } + Node::UnpackAssign { + targets, + targets_position, + object, + } => { + let object = self.prepare_expression(object)?; + // Recursively resolve all targets (supports nested tuples) + let targets = targets + .into_iter() + .map(|target| self.prepare_unpack_target(target)) + .collect::>()?; + new_nodes.push(Node::UnpackAssign { + targets, + targets_position, + object, + }); + } + Node::OpAssign { target, op, value } => { + // Track that this name was assigned + self.names_assigned_in_order.insert(target.name_id); + let target = self.get_id(target)?; + let value = self.prepare_expression(value)?; + new_nodes.push(Node::OpAssign { target, op, value }); + } + Node::SubscriptOpAssign { + target, + index, + op, + value, + target_position, + } => { + let target = self.prepare_expression(target)?; + let index = self.prepare_expression(index)?; + let value = self.prepare_expression(value)?; + new_nodes.push(Node::SubscriptOpAssign { + target, + index, + op, + value, + target_position, + }); + } + Node::SubscriptAssign { + target, + index, + value, + target_position, + } => { + // SubscriptAssign doesn't assign to the target itself, just modifies it + let target = self.prepare_expression(target)?; + let index = self.prepare_expression(index)?; + let value = self.prepare_expression(value)?; + new_nodes.push(Node::SubscriptAssign { + target, + index, + value, + target_position, + }); + } + Node::AttrOpAssign { + object, + attr, + op, + value, + target_position, + } => { + let object = self.prepare_expression(object)?; + let value = self.prepare_expression(value)?; + new_nodes.push(Node::AttrOpAssign { + object, + attr, + op, + value, + target_position, + }); + } + Node::AttrAssign { + object, + attr, + target_position, + value, + } => { + // AttrAssign doesn't assign to the object itself, just modifies its attribute + let object = self.prepare_expression(object)?; + let value = self.prepare_expression(value)?; + new_nodes.push(Node::AttrAssign { + object, + attr, + target_position, + value, + }); + } + Node::ChainAssign { targets, object } => { + // Prepare the single shared right-hand side, then prepare each + // target in left-to-right order so name-assignment tracking matches + // the source order (`a = b = 1` assigns `a` then `b`). + let object = self.prepare_expression(object)?; + let targets = targets + .into_iter() + .map(|t| self.prepare_assign_target(t)) + .collect::, _>>()?; + new_nodes.push(Node::ChainAssign { targets, object }); + } + Node::For { + target, + iter, + body, + or_else, + } => { + // Prepare target with normal scoping (not comprehension isolation) + let target = self.prepare_unpack_target(target)?; + new_nodes.push(Node::For { + target, + iter: self.prepare_expression(iter)?, + body: self.prepare_nodes(body)?, + or_else: self.prepare_nodes(or_else)?, + }); + } + Node::Break { position } => { + new_nodes.push(Node::Break { position }); + } + Node::Continue { position } => { + new_nodes.push(Node::Continue { position }); + } + Node::While { test, body, or_else } => { + new_nodes.push(Node::While { + test: self.prepare_expression(test)?, + body: self.prepare_nodes(body)?, + or_else: self.prepare_nodes(or_else)?, + }); + } + Node::If { test, body, or_else } => { + let test = self.prepare_expression(test)?; + let body = self.prepare_nodes(body)?; + let or_else = self.prepare_nodes(or_else)?; + new_nodes.push(Node::If { test, body, or_else }); + } + Node::FunctionDef { + def: + RawFunctionDef { + name, + signature, + body, + is_async, + }, + decorators, + } => { + // Decorators evaluate in the enclosing scope, not the function + // body, and before the name binds — so `@f def f()` sees the + // previous `f`, as in CPython. + let decorators = decorators + .into_iter() + .map(|d| self.prepare_expression(d)) + .collect::, ParseError>>()?; + let func = self.prepare_function_def(name, &signature, body, is_async)?; + // In a class body, the method name becomes a bound member + // only now — its own parameter defaults (evaluated in class + // scope, above) must see the pre-binding state. + if self.is_class_scope { + self.bound_class_members.insert(func.name.name_id); + } + new_nodes.push(Node::FunctionDef { def: func, decorators }); + } + Node::ClassDef { + name, + body, + members, + decorators, + position, + } => { + new_nodes.push(self.prepare_class_def(name, body, members, decorators, position)?); + } + Node::Global { names, position } => { + // At module level, `global` is a no-op since all variables are already global. + // In functions, the global declarations are already collected in the first pass + // (see prepare_function_def), so this is also a no-op at this point. + // The actual effect happens in get_id where we check global_names. + if !self.is_module_scope() { + // Validate that names weren't already used/assigned before `global` declaration + for string_id in names { + if self.names_assigned_in_order.contains(&string_id) { + let name_str = self.interner.get_str(string_id); + return Err(ParseError::syntax( + format!("name '{name_str}' is assigned to before global declaration"), + position, + )); + } else if self.names_used.contains(&string_id) { + let name_str = self.interner.get_str(string_id); + return Err(ParseError::syntax( + format!("name '{name_str}' is used prior to global declaration"), + position, + )); + } + } + } + // Global statements don't produce any runtime nodes + } + Node::Nonlocal { names, position } => { + // Nonlocal can only be used inside a function, not at module level + let PrepareState::Function(fn_state) = &self.state else { + return Err(ParseError::syntax( + "nonlocal declaration not allowed at module level", + position, + )); + }; + // Validate that names weren't already used/assigned before `nonlocal` declaration + // and that the binding exists in an enclosing scope. + for string_id in names { + if self.names_assigned_in_order.contains(&string_id) { + let name_str = self.interner.get_str(string_id); + return Err(ParseError::syntax( + format!("name '{name_str}' is assigned to before nonlocal declaration"), + position, + )); + } else if self.names_used.contains(&string_id) { + let name_str = self.interner.get_str(string_id); + return Err(ParseError::syntax( + format!("name '{name_str}' is used prior to nonlocal declaration"), + position, + )); + } + // The binding must exist somewhere in the enclosing function chain. + if !fn_state.enclosing_locals.contains(&string_id) { + let name_str = self.interner.get_str(string_id); + return Err(ParseError::syntax( + format!("no binding for nonlocal '{name_str}' found"), + position, + )); + } + } + // Nonlocal statements don't produce any runtime nodes + } + Node::Try(Try { + body, + handlers, + or_else, + finally, + }) => { + let body = self.prepare_nodes(body)?; + let handlers = handlers + .into_iter() + .map(|h| self.prepare_except_handler(h)) + .collect::, _>>()?; + let or_else = self.prepare_nodes(or_else)?; + let finally = self.prepare_nodes(finally)?; + new_nodes.push(Node::Try(Try { + body, + handlers, + or_else, + finally, + })); + } + Node::Match { + subject, + cases, + position, + } => { + let subject = self.prepare_expression(subject)?; + let cases = cases + .into_iter() + .map(|case| self.prepare_match_case(case)) + .collect::, _>>()?; + new_nodes.push(Node::Match { + subject, + cases, + position, + }); + } + Node::With { + context, + target, + body, + position, + } => { + let context = self.prepare_expression(context)?; + let target = match target { + Some(t) => Some(self.prepare_unpack_target(t)?), + None => None, + }; + let body = self.prepare_nodes(body)?; + new_nodes.push(Node::With { + context, + target, + body, + position, + }); + } + Node::Import { names } => { + let resolved_names = names + .into_iter() + .map(|import_name| -> Result<_, ParseError> { + // Note: import bindings are intentionally NOT recorded in + // `names_assigned_in_order`. CPython treats `import X [as Y]` + // as a soft binding: a later `global X` in the same scope is + // accepted without a "name 'X' is assigned to before global + // declaration" SyntaxError, even though every other binding + // form (plain assign, `def`, `class`, `for`, `with`, `except as`, + // walrus) triggers that diagnostic. See issue #423. + let resolved_binding = self.get_id(import_name.binding)?; + Ok(ImportName { + module_name: import_name.module_name, + submodules: import_name.submodules, + binds_top_level: import_name.binds_top_level, + binding: resolved_binding, + }) + }) + .collect::>()?; + new_nodes.push(Node::Import { names: resolved_names }); + } + Node::ImportFrom { + module_name, + submodules, + names, + position, + } => { + let resolved_names = names + .into_iter() + .map(|(import_name, binding)| -> Result<_, ParseError> { + // See `Node::Import` for why import bindings skip + // `names_assigned_in_order` — same CPython compatibility quirk. + let resolved_binding = self.get_id(binding)?; + Ok((import_name, resolved_binding)) + }) + .collect::>()?; + new_nodes.push(Node::ImportFrom { + module_name, + submodules, + names: resolved_names, + position, + }); + } + } + } + Ok(new_nodes) + } + + /// Prepares an exception handler by resolving names in the exception type and body. + /// + /// The exception variable (if present) is treated as an assigned name in the current scope. + fn prepare_except_handler( + &mut self, + handler: ExceptHandler, + ) -> Result, ParseError> { + let exc_type = match handler.exc_type { + Some(expr) => Some(self.prepare_expression(expr)?), + None => None, + }; + // The exception variable binding (e.g., `as e:`) is an assignment + let name = match handler.name { + Some(ident) => { + // Track that this name was assigned + self.names_assigned_in_order.insert(ident.name_id); + Some(self.get_id(ident)?) + } + None => None, + }; + let body = self.prepare_nodes(handler.body)?; + Ok(ExceptHandler { exc_type, name, body }) + } + + /// Prepares an expression by resolving names, transforming calls, and applying optimizations. + /// + /// Key transformations performed: + /// - Name lookups are resolved to namespace indices via `get_id` + /// - Function calls are resolved from identifiers to builtin types + /// - Attribute calls validate that the object is already defined (not a new name) + /// - Lists and tuples are recursively prepared + /// + /// # Errors + /// Returns a NameError if an attribute call references an undefined variable + fn prepare_expression(&mut self, loc_expr: ExprLoc) -> Result { + let ExprLoc { position, expr } = loc_expr; + let expr = match expr { + Expr::Literal(object) => Expr::Literal(object), + Expr::Builtin(callable) => Expr::Builtin(callable), + Expr::Name(name) => self.resolve_name_or_builtin(name)?, + Expr::Op { left, op, right } => Expr::Op { + left: Box::new(self.prepare_expression(*left)?), + op, + right: Box::new(self.prepare_expression(*right)?), + }, + Expr::CmpOp { left, op, right } => Expr::CmpOp { + left: Box::new(self.prepare_expression(*left)?), + op, + right: Box::new(self.prepare_expression(*right)?), + }, + Expr::ChainCmp { left, comparisons } => Expr::ChainCmp { + left: Box::new(self.prepare_expression(*left)?), + comparisons: comparisons + .into_iter() + .map(|(op, expr)| Ok((op, self.prepare_expression(expr)?))) + .collect::, _>>()?, + }, + Expr::Call { callable, mut args } => { + // Prepare the arguments + args.prepare_args(|expr| self.prepare_expression(expr))?; + // For Name callables, resolve the identifier in the namespace + // Don't error here if undefined - let runtime raise NameError with proper traceback + let callable = match callable { + Callable::Name(ident) => match self.resolve_name_or_builtin(ident)? { + Expr::Builtin(b) => Callable::Builtin(b), + Expr::Name(resolved) => Callable::Name(resolved), + _ => unreachable!("resolve_name_or_builtin returns Name or Builtin"), + }, + other @ Callable::Builtin(_) => other, + }; + Expr::Call { callable, args } + } + Expr::AttrCall { object, attr, mut args } => { + // Prepare the object expression (supports chained access like a.b.c.method()) + let object = Box::new(self.prepare_expression(*object)?); + args.prepare_args(|expr| self.prepare_expression(expr))?; + Expr::AttrCall { object, attr, args } + } + Expr::IndirectCall { callable, mut args } => { + // Prepare the callable expression (e.g., lambda or any expression returning a callable) + let callable = Box::new(self.prepare_expression(*callable)?); + args.prepare_args(|expr| self.prepare_expression(expr))?; + Expr::IndirectCall { callable, args } + } + Expr::AttrGet { object, attr } => { + // Prepare the object expression (supports chained access like a.b.c) + let object = Box::new(self.prepare_expression(*object)?); + Expr::AttrGet { object, attr } + } + Expr::List(elements) => { + let items = elements + .into_iter() + .map(|item| self.prepare_sequence_item(item)) + .collect::>()?; + Expr::List(items) + } + Expr::Tuple(elements) => { + let items = elements + .into_iter() + .map(|item| self.prepare_sequence_item(item)) + .collect::>()?; + Expr::Tuple(items) + } + Expr::Subscript { object, index } => Expr::Subscript { + object: Box::new(self.prepare_expression(*object)?), + index: Box::new(self.prepare_expression(*index)?), + }, + Expr::Dict(dict_items) => { + let prepared = dict_items + .into_iter() + .map(|item| match item { + DictItem::Pair(k, v) => { + Ok(DictItem::Pair(self.prepare_expression(k)?, self.prepare_expression(v)?)) + } + DictItem::Unpack(e) => Ok(DictItem::Unpack(self.prepare_expression(e)?)), + }) + .collect::>()?; + Expr::Dict(prepared) + } + Expr::Set(elements) => { + let items = elements + .into_iter() + .map(|item| self.prepare_sequence_item(item)) + .collect::>()?; + Expr::Set(items) + } + Expr::Not(operand) => Expr::Not(Box::new(self.prepare_expression(*operand)?)), + Expr::UnaryMinus(operand) => Expr::UnaryMinus(Box::new(self.prepare_expression(*operand)?)), + Expr::UnaryPlus(operand) => Expr::UnaryPlus(Box::new(self.prepare_expression(*operand)?)), + Expr::UnaryInvert(operand) => Expr::UnaryInvert(Box::new(self.prepare_expression(*operand)?)), + Expr::FString(parts) => { + let prepared_parts = parts + .into_iter() + .map(|part| self.prepare_fstring_part(part)) + .collect::, ParseError>>()?; + Expr::FString(prepared_parts) + } + Expr::IfElse { test, body, orelse } => Expr::IfElse { + test: Box::new(self.prepare_expression(*test)?), + body: Box::new(self.prepare_expression(*body)?), + orelse: Box::new(self.prepare_expression(*orelse)?), + }, + Expr::ListComp { elt, generators, .. } => { + let prepared = self.prepare_comprehension(generators, Some(*elt), None)?; + Expr::ListComp { + elt: Box::new(prepared.elt.expect("list comp must have elt")), + generators: prepared.generators, + captured_slots: prepared.captured_slots, + } + } + Expr::SetComp { elt, generators, .. } => { + let prepared = self.prepare_comprehension(generators, Some(*elt), None)?; + Expr::SetComp { + elt: Box::new(prepared.elt.expect("set comp must have elt")), + generators: prepared.generators, + captured_slots: prepared.captured_slots, + } + } + Expr::DictComp { + key, value, generators, .. + } => { + let prepared = self.prepare_comprehension(generators, None, Some((*key, *value)))?; + let (key, value) = prepared.key_value.expect("dict comp must have key/value"); + Expr::DictComp { + key: Box::new(key), + value: Box::new(value), + generators: prepared.generators, + captured_slots: prepared.captured_slots, + } + } + Expr::LambdaRaw { + name_id, + signature, + body, + } => { + // Convert the raw lambda into a prepared lambda expression + return self.prepare_lambda(name_id, &signature, &body, position); + } + Expr::Lambda { .. } => { + // Lambda should only be created during prepare, never during parsing + unreachable!("Expr::Lambda should not exist before prepare phase") + } + Expr::Slice { lower, upper, step } => Expr::Slice { + lower: lower.map(|e| self.prepare_expression(*e)).transpose()?.map(Box::new), + upper: upper.map(|e| self.prepare_expression(*e)).transpose()?.map(Box::new), + step: step.map(|e| self.prepare_expression(*e)).transpose()?.map(Box::new), + }, + Expr::Named { target, value } => { + let value = Box::new(self.prepare_expression(*value)?); + // Register the target as assigned in this scope + self.names_assigned_in_order.insert(target.name_id); + // Walrus binds in the enclosing scope (PEP 572), NOT in the + // comprehension's scratch region. Resolve through the + // assignment-target path which bypasses `comp_name_scopes`. + let resolved_target = self.get_id_for_store_target(target)?; + Expr::Named { + target: resolved_target, + value, + } + } + Expr::Await(value) => Expr::Await(Box::new(self.prepare_expression(*value)?)), + }; + + Ok(ExprLoc { position, expr }) + } + + /// Resolves a name to either `Expr::Builtin` or `Expr::Name` with scope-aware builtin detection. + /// + /// Python's name resolution follows LEGB order (Local, Enclosing, Global, Builtin). + /// Builtins are only used when the name is not found in any other scope. This method + /// ensures that local assignments (e.g., `int = 42`) properly shadow builtin names. + /// + /// We check before calling `get_id` to avoid allocating unnecessary namespace slots. + /// At module level, a slot allocated for an unassigned builtin would leak into + /// `global_name_map` for nested functions, causing incorrect resolution. + fn resolve_name_or_builtin(&mut self, name: Identifier) -> Result { + // This is the canonical name-READ path: every `Expr::Name` (and + // every `Callable::Name`) flows through here. Recording the read in + // `names_used` is what makes the `global X` / `nonlocal X` "used + // prior to declaration" diagnostic fire for source-level reads while + // *not* tripping on import bindings or pure write-target resolutions + // (which take a different path through `get_id`). See issue #423. + self.names_used.insert(name.name_id); + + // Parse-time builtin substitution is a module-scope-only optimization: turning + // `len(x)` into `CallBuiltinFunction(Len)` skips a `LoadGlobal` round-trip, + // but it's only safe when we are CERTAIN nothing will rebind the name later. + // + // At MODULE scope we have that certainty as long as no prior statement (this + // snippet) and no prior REPL snippet (the seeded globals) has bound the name. + // Once either has, we have to defer to runtime so a later read sees the user + // value. + // + // At FUNCTION scope we never have that certainty: the module can rebind a name + // after the function is compiled (e.g. `def call_sum(): return sum(...)` + // followed later by `def sum(...)`), and in REPL the rebinding can happen in a + // future snippet that the current compile can't see. So at function scope we + // always go through `get_id` and defer the builtin check to runtime. + // + // A by-name snippet top level never has it either: its namespace dict + // may shadow the builtin, so the read is deferred to runtime too. + if self.is_module_scope() && !self.top_level_by_name { + let name_str = self.interner.get_str(name.name_id); + let already_bound = + self.names_assigned_in_order.contains(&name.name_id) || self.globals.globals.contains(name.name_id); + if !already_bound && let Ok(builtin) = name_str.parse::() { + return Ok(Expr::Builtin(builtin)); + } + } + + Ok(Expr::Name(self.get_id_read(name)?)) + } + + /// Prepares a `SequenceItem` by recursively preparing its inner expression. + /// + /// Both `Value` and `Unpack` variants need their expressions prepared + /// (name resolution, scope analysis, builtin detection, etc.). + fn prepare_sequence_item(&mut self, item: SequenceItem) -> Result { + match item { + SequenceItem::Value(e) => Ok(SequenceItem::Value(self.prepare_expression(e)?)), + SequenceItem::Unpack(e) => Ok(SequenceItem::Unpack(self.prepare_expression(e)?)), + } + } + + /// Prepares a comprehension with scope isolation for loop variables. + /// + /// Comprehension loop variables are isolated from the enclosing scope - they do not + /// leak after the comprehension completes. CPython scoping rules require: + /// + /// 1. The FIRST generator's iter is evaluated in the enclosing scope + /// 2. ALL loop variables from ALL generators are then shadowed as local + /// 3. Subsequent generators' iters see all loop vars as local (even if unassigned) + /// + /// This means `[y for x in [1] for y in z for z in [[2]]]` raises UnboundLocalError + /// because `z` is treated as local (it's a loop var in generator 3) when evaluating + /// generator 2's iter. + /// + /// For list/set comprehensions, pass `elt` as Some and `key_value` as None. + /// For dict comprehensions, pass `elt` as None and `key_value` as Some((key, value)). + fn prepare_comprehension( + &mut self, + generators: Vec, + elt: Option, + key_value: Option<(ExprLoc, ExprLoc)>, + ) -> Result { + // Per PEP 572, walrus operators inside comprehensions bind in the ENCLOSING scope. + // Pre-register walrus targets so they exist in the enclosing namespace BEFORE the + // comp-name scope is pushed — that way `get_id_for_store_target` resolves them + // straight to enclosing-scope slots without seeing comp-var. + let mut walrus_targets: AHashSet = AHashSet::new(); + if let Some(ref e) = elt { + collect_assigned_names_from_expr(e, &mut walrus_targets, self.interner); + } + if let Some((ref k, ref v)) = key_value { + collect_assigned_names_from_expr(k, &mut walrus_targets, self.interner); + collect_assigned_names_from_expr(v, &mut walrus_targets, self.interner); + } + for generator in &generators { + // Note: we don't scan iter expressions here because walrus in iterable is not allowed + for cond in &generator.ifs { + collect_assigned_names_from_expr(cond, &mut walrus_targets, self.interner); + } + } + // Pre-allocate slots for walrus targets in the enclosing scope. + // Anchor any namespace-overflow error to the first generator's iter, + // since the walrus statements themselves can be scattered through the + // comprehension and don't have a single load-bearing position. + let comp_pos = generators.first().map(|g| g.iter.position).unwrap_or_default(); + for &name in &walrus_targets { + self.ensure_scope_slot(name, comp_pos)?; + self.names_assigned_in_order.insert(name); + } + + // A comprehension is a single lexical scope even though its generators are + // written left-to-right. Push one comp scope for the whole comprehension and + // remember the scratch depth so we can release this comp's slots on exit + // (sibling comps reuse the slots; high-water mark records peak nesting). + let saved_var_depth = self.comp_var_depth; + self.comp_name_scopes.push(CompNameScope::default()); + + // PEP 709 / CPython: the FIRST generator's iter is evaluated in the + // *enclosing* scope, before any comp shadowing — that is why + // `[x for x in x]` inside `def inner(): x = ...; return [x for x in x]` + // pulls the outer `x` into the iter and then rebinds it. Prepare it now, + // with the (empty) comp scope already pushed so any walrus or nested + // lookup follows the same path as the rest of the comprehension; the + // empty scope can't shadow anything yet. + let mut generators_iter = generators.into_iter(); + let first_gen = generators_iter + .next() + .expect("comprehension must have at least one generator"); + let saved_var_peak = mem::replace(&mut self.comp_var_peak, self.comp_var_depth); + let first_iter = self.prepare_expression(first_gen.iter)?; + // The compiler activates this comprehension's captured cells before compiling the + // first iterable, so its targets must not reuse any slot a comprehension nested there used. + self.comp_var_depth = self.comp_var_peak; + self.comp_var_peak = saved_var_peak.max(self.comp_var_peak); + let remaining_gens: Vec = generators_iter.collect(); + + // Predeclare every generator target's names as comp-var slots BEFORE + // preparing any *remaining* iter expression. This makes references to a + // later generator's target name (or the first generator's target, in + // the body) resolve to scratch — raising `UnboundLocalError` at runtime + // if loaded before the corresponding `for` assigns (the reviewer's + // `[x for x in [1] for y in z for z in [[2], [3]]]` example). + let first_target = self.prepare_unpack_target_for_comprehension(first_gen.target)?; + let mut remaining_targets: Vec = Vec::with_capacity(remaining_gens.len()); + for generator in &remaining_gens { + remaining_targets.push(self.prepare_unpack_target_for_comprehension(generator.target.clone())?); + } + + // Now prepare the first generator's filters (with full comp scope visible), + // then the remaining generators' iter + filters, then the body element. + let first_ifs = first_gen + .ifs + .into_iter() + .map(|cond| self.prepare_expression(cond)) + .collect::, _>>()?; + + let mut prepared_generators = Vec::with_capacity(1 + remaining_gens.len()); + prepared_generators.push(Comprehension { + target: first_target, + iter: first_iter, + ifs: first_ifs, + }); + for (generator, prepared_target) in remaining_gens.into_iter().zip(remaining_targets) { + let iter = self.prepare_expression(generator.iter)?; + let ifs = generator + .ifs + .into_iter() + .map(|cond| self.prepare_expression(cond)) + .collect::, _>>()?; + prepared_generators.push(Comprehension { + target: prepared_target, + iter, + ifs, + }); + } + + // Prepare the element / key-value expression(s) in the same comp scope + // so they too see the comp targets. + let prepared_elt = match elt { + Some(e) => Some(self.prepare_expression(e)?), + None => None, + }; + let prepared_key_value = match key_value { + Some((k, v)) => Some((self.prepare_expression(k)?, self.prepare_expression(v)?)), + None => None, + }; + + // The scope preserves lexical allocation order while keeping each name unique. + let comp_scope = self.comp_name_scopes.pop().expect("comprehension scope was pushed"); + let captured_slots = comp_scope + .into_values() + .filter_map(|binding| binding.captured.then_some(binding.slot)) + .collect(); + self.comp_var_depth = saved_var_depth; + + Ok(PreparedComprehension { + generators: prepared_generators, + elt: prepared_elt, + key_value: prepared_key_value, + captured_slots, + }) + } + + /// Prepares an `AssignTarget` used by chained assignments. + /// + /// Resolves identifiers, sub-expressions and nested unpack patterns so that each + /// target is ready for the compiler. Name-targets are also recorded in + /// `names_assigned_in_order` just like single-target `Node::Assign` would, so the + /// observable scope behaviour of `a = b = 1` matches `a = 1; b = 1`. + fn prepare_assign_target(&mut self, target: AssignTarget) -> Result { + match target { + AssignTarget::Name(ident) => { + self.names_assigned_in_order.insert(ident.name_id); + let ident = self.get_id(ident)?; + Ok(AssignTarget::Name(ident)) + } + AssignTarget::Subscript { + target, + index, + target_position, + } => Ok(AssignTarget::Subscript { + target: self.prepare_expression(target)?, + index: self.prepare_expression(index)?, + target_position, + }), + AssignTarget::Attr { + object, + attr, + target_position, + } => Ok(AssignTarget::Attr { + object: self.prepare_expression(object)?, + attr, + target_position, + }), + AssignTarget::Unpack { + targets, + targets_position, + } => { + let targets = targets + .into_iter() + .map(|t| self.prepare_unpack_target(t)) + .collect::>()?; + Ok(AssignTarget::Unpack { + targets, + targets_position, + }) + } + } + } + + /// Prepares an unpack target by resolving identifiers recursively. + /// + /// Handles both single identifiers and nested tuples like `(a, b), c`. + fn prepare_unpack_target(&mut self, target: UnpackTarget) -> Result { + match target { + UnpackTarget::Name(ident) => { + self.names_assigned_in_order.insert(ident.name_id); + Ok(UnpackTarget::Name(self.get_id(ident)?)) + } + UnpackTarget::Starred(inner) => Ok(UnpackTarget::Starred(Box::new(self.prepare_unpack_target(*inner)?))), + UnpackTarget::Attr { object, attr, position } => Ok(UnpackTarget::Attr { + object: Box::new(self.prepare_expression(*object)?), + attr, + position, + }), + UnpackTarget::Subscript { + container, + index, + position, + } => Ok(UnpackTarget::Subscript { + container: Box::new(self.prepare_expression(*container)?), + index: Box::new(self.prepare_expression(*index)?), + position, + }), + UnpackTarget::Tuple { targets, position } => { + let resolved_targets = targets + .into_iter() + .map(|t| self.prepare_unpack_target(t)) // Recursive call + .collect::, _>>()?; + Ok(UnpackTarget::Tuple { + targets: resolved_targets, + position, + }) + } + } + } + + /// Prepares one `case` clause: pattern captures bind like assignment + /// targets, then the guard and body are prepared in the same scope. + fn prepare_match_case(&mut self, case: MatchCase) -> Result, ParseError> { + let pattern = self.prepare_pattern(case.pattern)?; + let guard = match case.guard { + Some(guard) => Some(self.prepare_expression(guard)?), + None => None, + }; + let body = self.prepare_nodes(case.body)?; + Ok(MatchCase { + pattern, + guard, + body, + position: case.position, + }) + } + + /// Resolves a pattern's expressions and capture names. + /// + /// Every capture (`case x`, `*rest`, `**rest`, `as name`) is a store target in + /// the enclosing scope, so it goes through [`Self::get_id`] like an unpack name. + fn prepare_pattern(&mut self, pattern: Pattern) -> Result { + Ok(match pattern { + Pattern::Value(expr) => Pattern::Value(self.prepare_expression(expr)?), + Pattern::Singleton(expr) => Pattern::Singleton(self.prepare_expression(expr)?), + Pattern::Sequence { patterns, position } => Pattern::Sequence { + patterns: self.prepare_patterns(patterns)?, + position, + }, + Pattern::Mapping { + keys, + patterns, + rest, + position, + } => Pattern::Mapping { + keys: keys + .into_iter() + .map(|key| self.prepare_expression(key)) + .collect::, _>>()?, + patterns: self.prepare_patterns(patterns)?, + rest: self.prepare_capture(rest)?, + position, + }, + Pattern::Class { + cls, + patterns, + kwd_attrs, + kwd_patterns, + position, + } => Pattern::Class { + cls: self.prepare_expression(cls)?, + patterns: self.prepare_patterns(patterns)?, + kwd_attrs, + kwd_patterns: self.prepare_patterns(kwd_patterns)?, + position, + }, + Pattern::Star { name, position } => Pattern::Star { + name: self.prepare_capture(name)?, + position, + }, + Pattern::As { + pattern, + name, + position, + } => Pattern::As { + pattern: match pattern { + Some(inner) => Some(Box::new(self.prepare_pattern(*inner)?)), + None => None, + }, + name: self.prepare_capture(name)?, + position, + }, + Pattern::Or { patterns, position } => Pattern::Or { + patterns: self.prepare_patterns(patterns)?, + position, + }, + }) + } + + fn prepare_patterns(&mut self, patterns: Vec) -> Result, ParseError> { + patterns.into_iter().map(|p| self.prepare_pattern(p)).collect() + } + + /// Resolves an optional capture name to its store slot. + fn prepare_capture(&mut self, name: Option) -> Result, ParseError> { + match name { + Some(ident) => { + self.names_assigned_in_order.insert(ident.name_id); + Ok(Some(self.get_id(ident)?)) + } + None => Ok(None), + } + } + + /// Predeclares an unpack target's names as comprehension-variable slots. + /// + /// Called during the first pass of `prepare_comprehension`, before any + /// generator iter expressions are walked, so later target names shadow + /// enclosing scopes. Each new lexical name claims the next comp-var slot; + /// repeated targets reuse it. Reads inside the comprehension resolve + /// through this scope, while outside it the slot is unreachable. + fn prepare_unpack_target_for_comprehension(&mut self, target: UnpackTarget) -> Result { + match target { + UnpackTarget::Name(ident) => { + let slot = self.alloc_comp_var_slot(ident.name_id, ident.position)?; + Ok(UnpackTarget::Name(Identifier::new_with_scope( + ident.name_id, + ident.position, + NamespaceId::new(usize::from(slot)).expect("comp-var slot fits in NamespaceId"), + NameScope::CompVar, + ))) + } + UnpackTarget::Starred(inner) => Ok(UnpackTarget::Starred(Box::new( + self.prepare_unpack_target_for_comprehension(*inner)?, + ))), + UnpackTarget::Tuple { targets, position } => { + let resolved_targets = targets + .into_iter() + .map(|t| self.prepare_unpack_target_for_comprehension(t)) + .collect::, _>>()?; + Ok(UnpackTarget::Tuple { + targets: resolved_targets, + position, + }) + } + // A comprehension's targets are its comp vars, which live in + // operand-stack slots; a store to an object has nowhere to go there. + UnpackTarget::Attr { position, .. } => Err(ParseError::syntax( + "comprehension target must be a name, not an attribute", + position, + )), + UnpackTarget::Subscript { position, .. } => Err(ParseError::syntax( + "comprehension target must be a name, not a subscript", + position, + )), + } + } + + /// Returns the comp-var slot for `name_id`, allocating it on first use. + /// + /// Repeated targets in one comprehension share a slot because the whole + /// comprehension is one lexical scope. New slots use a `u16` operand and + /// report namespace overflow consistently with regular namespace slots. + fn alloc_comp_var_slot(&mut self, name_id: StringId, position: CodeRange) -> Result { + let top = self + .comp_name_scopes + .last_mut() + .expect("alloc_comp_var_slot called outside an active comp scope"); + if let Some(binding) = top.get(&name_id) { + Ok(binding.slot) + } else { + let slot = self.comp_var_depth; + self.comp_var_depth = slot.checked_add(1).ok_or_else(|| namespace_overflow(position))?; + self.comp_var_peak = self.comp_var_peak.max(self.comp_var_depth); + top.insert(name_id, CompBinding { slot, captured: false }); + Ok(slot) + } + } + + /// Prepares a function definition using a two-pass approach for correct scope resolution. + /// + /// Pass 1: Scan the function body to collect: + /// - Names declared as `global` + /// - Names declared as `nonlocal` + /// - Names that are assigned (these are local unless declared global/nonlocal) + /// + /// Pass 2: Prepare the function body with the scope information from pass 1. + /// + /// # Closure Analysis + /// + /// When the nested function uses `nonlocal` declarations, those names must exist + /// in an enclosing scope. The enclosing scope's variable becomes a cell_var + /// (stored in a heap cell), and the nested function captures it as a free_var. + fn prepare_function_def( + &mut self, + name: Identifier, + parsed_sig: &ParsedSignature, + body: Vec, + is_async: bool, + ) -> Result { + // A `def` (top-level, nested, or method — class bodies are function scopes + // too) binds its name in the enclosing scope. + self.names_assigned_in_order.insert(name.name_id); + let name = self.get_id(name)?; + + // Extract param names from the parsed signature for scope analysis + let param_names: Vec = parsed_sig.param_names().collect(); + + // Pass 1: Collect scope information from the function body + let scope_info = collect_function_scope_info(&body, ¶m_names, self.interner); + + // Build `enclosing_locals` for the new function: the union of every + // ancestor function scope's locals (see `child_enclosing_locals` for the + // transitive-closure and class-scope-skipping rationale). + let enclosing_locals = self.child_enclosing_locals(); + + // Filter potential_captures to get actual implicit captures. + // Only names that are ALSO in enclosing_locals are true implicit captures. + // Names NOT in enclosing_locals are either builtins or globals (handled at runtime). + let implicit_captures: AHashSet = scope_info + .potential_captures + .into_iter() + .filter(|name| enclosing_locals.contains(name)) + .collect(); + + // Re-borrow the live globals handle so the new function preparer + // can extend the module-level `NameMap` in place. + let globals = self.globals.reborrow(); + + // Pass 2: create the child preparer for the function body. + let mut inner_prepare = Prepare::new_function( + ¶m_names, + name.position, + scope_info.assigned_names, + scope_info.global_names, + &scope_info.nonlocal_names, + &implicit_captures, + globals, + enclosing_locals, + &scope_info.cell_var_names, + self.interner, + )?; + + // Prepare the function body + let prepared_body = inner_prepare.prepare_nodes(body)?; + + // Take the per-function state out of `inner_prepare` and drop the + // child so its `GlobalsRef` borrow is released. We need exclusive + // mutable access to `self`'s function state for the bubble-up work + // below — the borrow on the module globals can't be live at the + // same time. No "global X" bubble-up is needed: the inner preparer's + // `get_id` already allocated module slots through the shared handle. + let PrepareState::Function(inner_state) = mem::replace(&mut inner_prepare.state, PrepareState::Module) else { + unreachable!("child preparer was constructed with new_function"); + }; + let FunctionState { + locals: inner_locals, + free_var_map: inner_free_var_map, + cell_var_map: inner_cell_var_map, + .. + } = *inner_state; + let namespace_size = inner_locals.len(); + drop(inner_prepare); + + // Record every variable the inner function captured from us (filing each + // as an owned cell or a pass-through free var) and build its slot vectors. + let FinalizedScope { + free_var_enclosing_slots, + free_var_slots, + cell_var_slots, + cell_param_indices, + } = self.finalize_child_scope(inner_free_var_map, inner_cell_var_map, ¶m_names, name.position)?; + + // Build the runtime Signature from the parsed signature + let pos_args: Vec = parsed_sig.pos_args.iter().map(|p| p.name).collect(); + let pos_defaults_count = parsed_sig.pos_args.iter().filter(|p| p.default.is_some()).count(); + let args: Vec = parsed_sig.args.iter().map(|p| p.name).collect(); + let arg_defaults_count = parsed_sig.args.iter().filter(|p| p.default.is_some()).count(); + let mut kwargs: Vec = Vec::with_capacity(parsed_sig.kwargs.len()); + let mut kwarg_default_map: Vec> = Vec::with_capacity(parsed_sig.kwargs.len()); + let mut kwarg_default_index = 0; + for param in &parsed_sig.kwargs { + kwargs.push(param.name); + if param.default.is_some() { + kwarg_default_map.push(Some(kwarg_default_index)); + kwarg_default_index += 1; + } else { + kwarg_default_map.push(None); + } + } + + let signature = Signature::new( + pos_args, + pos_defaults_count, + args, + arg_defaults_count, + parsed_sig.var_args, + kwargs, + kwarg_default_map, + parsed_sig.var_kwargs, + ); + + // Collect and prepare default expressions in order: pos_args -> args -> kwargs + // Only includes parameters that actually have defaults. + let mut default_exprs = Vec::with_capacity(signature.total_defaults_count()); + for param in &parsed_sig.pos_args { + if let Some(ref expr) = param.default { + default_exprs.push(self.prepare_expression(expr.clone())?); + } + } + for param in &parsed_sig.args { + if let Some(ref expr) = param.default { + default_exprs.push(self.prepare_expression(expr.clone())?); + } + } + for param in &parsed_sig.kwargs { + if let Some(ref expr) = param.default { + default_exprs.push(self.prepare_expression(expr.clone())?); + } + } + + // Return the prepared function definition; the caller wraps it in a + // `Node::FunctionDef` or uses it as a `Node::ClassDef`'s body. + Ok(PreparedFunctionDef { + name, + signature, + body: prepared_body, + namespace_size, + free_var_names: free_var_slots + .iter() + .map(|slot| inner_locals.names()[slot.index()]) + .collect(), + free_var_enclosing_slots, + free_var_slots, + cell_var_slots, + cell_param_indices, + default_exprs, + is_async, + }) + } + + /// Prepares a `class Foo: ...` definition. + /// + /// The class body is a synthetic zero-argument function (see + /// [`Node::ClassDef`]); this mirrors [`Self::prepare_function_def`] but: + /// - the inner preparer is flagged `is_class_scope = true`, so methods skip + /// the class scope for free-var resolution (see + /// [`Self::child_enclosing_locals`]); + /// - it carries no params/defaults; + /// - `cell_var_names` is forced empty: skip-class-scope guarantees no nested + /// scope captures a class-body local, so every member stays a plain local + /// (the compiler loads members with `LoadLocal`); + /// - it resolves each member name to its class-body slot (for namespace + /// assembly) from the inner preparer's locals. + /// + /// The class name itself binds in the **enclosing** scope, exactly like a `def`. + fn prepare_class_def( + &mut self, + name: Identifier, + body: RawFunctionDef, + members: Vec, + decorators: Vec, + position: CodeRange, + ) -> Result { + // The class name binds in the enclosing scope, exactly like a `def`. + self.names_assigned_in_order.insert(name.name_id); + let name = self.get_id(name)?; + + // Decorators evaluate in the enclosing scope, not the class body. + let decorators = decorators + .into_iter() + .map(|d| self.prepare_expression(d)) + .collect::, ParseError>>()?; + + // The class body is a synthetic zero-arg function: no params, no defaults. + let RawFunctionDef { + name: body_name, + body: body_nodes, + .. + } = body; + let param_names: Vec = Vec::new(); + + // Pass 1: collect scope info over the class-body statements. The class + // body's own locals are never cells (no nested scope may capture them — + // see the doc above), so drop any cell-var candidates the generic + // pre-pass flagged: keeping every member a plain local. + let mut scope_info = collect_function_scope_info(&body_nodes, ¶m_names, self.interner); + scope_info.cell_var_names.clear(); + + // Names the class body may capture from scopes enclosing the class. + let enclosing_locals = self.child_enclosing_locals(); + let implicit_captures: AHashSet = scope_info + .potential_captures + .into_iter() + .filter(|n| enclosing_locals.contains(n)) + .collect(); + + // Re-borrow the live globals handle (see `prepare_function_def`). + let globals = self.globals.reborrow(); + + // Pass 2: child preparer for the class body, flagged as a class scope. + let mut inner_prepare = Prepare::new_function( + ¶m_names, + body_name.position, + scope_info.assigned_names, + scope_info.global_names, + &scope_info.nonlocal_names, + &implicit_captures, + globals, + enclosing_locals, + &scope_info.cell_var_names, + self.interner, + )?; + inner_prepare.is_class_scope = true; + + let prepared_body = inner_prepare.prepare_nodes(body_nodes)?; + + // Take the per-function state out of the child and drop it so its + // `GlobalsRef` borrow is released before we mutate `self` below. + let PrepareState::Function(inner_state) = mem::replace(&mut inner_prepare.state, PrepareState::Module) else { + unreachable!("class-body preparer was constructed with new_function"); + }; + let FunctionState { + locals: inner_locals, + free_var_map: inner_free_var_map, + cell_var_map: inner_cell_var_map, + .. + } = *inner_state; + let namespace_size = inner_locals.len(); + drop(inner_prepare); + + // Resolve each member to its class-body-local slot. Every member is + // assigned in the class body (a method `def` or a class-var `Assign`), + // so it is always present as a plain local. + let members = members + .into_iter() + .map(|member| { + let slot = inner_locals.get(member.name_id).unwrap_or_else(|| { + let member_name = self.interner.get_str(member.name_id); + panic!("class member '{member_name}' missing from class-body locals") + }); + Identifier::new_with_scope(member.name_id, member.position, slot, NameScope::Local) + }) + .collect::>(); + + // Same-name collision (a known divergence — see `limitations/classes.md`): + // a class-body owned cell means a method captured a class-body local that + // ALSO has the same name as a variable in an enclosing scope. CPython keeps + // these distinct (class-dict entry vs. closure cell); Monty maps one name + // to a single slot, so it cannot represent both. Reject cleanly rather than + // miscompile (the alternative is a runtime "expected cell reference" crash). + if let Some(&name_id) = inner_cell_var_map.keys().next() { + let name_str = self.interner.get_str(name_id); + return Err(ParseError::not_implemented( + format!( + "class member '{name_str}' that shadows a captured variable of the same name from an enclosing scope" + ), + position, + )); + } + + // Record what the class body captured from us and build its slot vectors. + let FinalizedScope { + free_var_enclosing_slots, + free_var_slots, + cell_var_slots, + cell_param_indices, + } = self.finalize_child_scope(inner_free_var_map, inner_cell_var_map, ¶m_names, position)?; + + // The class body is a synthetic, never-registered zero-arg function. Its + // name reuses the class `name_id` (for tracebacks) with a placeholder slot. + let body_name = Identifier::new_with_scope( + body_name.name_id, + body_name.position, + NamespaceId::new(0).expect("slot 0 fits in u16"), + NameScope::Local, + ); + let body_def = PreparedFunctionDef { + name: body_name, + signature: Signature::default(), + body: prepared_body, + namespace_size, + free_var_names: free_var_slots + .iter() + .map(|slot| inner_locals.names()[slot.index()]) + .collect(), + free_var_enclosing_slots, + free_var_slots, + cell_var_slots, + cell_param_indices, + default_exprs: Vec::new(), + is_async: false, + }; + + Ok(Node::ClassDef { + name, + body: body_def, + members, + decorators, + position, + }) + } + + /// Prepares a lambda expression, converting it into a prepared function definition. + /// + /// Lambdas are essentially anonymous functions with an implicit return of their body + /// expression. This method follows the same preparation logic as `prepare_function_def` + /// but: + /// - Uses `` as the function name (not registered in scope) + /// - Wraps the body expression as `Node::Return(body)` + /// - Returns `ExprLoc` with `Expr::Lambda` instead of `PreparedNode` + fn prepare_lambda( + &mut self, + lambda_name_id: StringId, + parsed_sig: &ParsedSignature, + body: &ExprLoc, + position: CodeRange, + ) -> Result { + // Create a synthetic name identifier (not registered in scope) + let lambda_name = Identifier::new_with_scope( + lambda_name_id, + position, + // Slot 0 is the trivial placeholder; the lambda name never lands + // in a namespace because lambdas don't have a binding name. + NamespaceId::new(0).expect("slot 0 fits in u16"), + NameScope::Local, + ); + + // Wrap the body expression as a return statement for scope analysis + let body_as_node: ParseNode = Node::Return(Some(body.clone())); + let body_nodes = vec![body_as_node]; + + // Extract param names from the parsed signature for scope analysis + let param_names: Vec = parsed_sig.param_names().collect(); + + // Pass 1: Collect scope information from the lambda body + // (Lambdas can't have global/nonlocal declarations, but can have nested functions) + let scope_info = collect_function_scope_info(&body_nodes, ¶m_names, self.interner); + + // Build enclosing_locals: names that are local to this scope or + // captured from any enclosing scope (see `child_enclosing_locals`). + let enclosing_locals = self.child_enclosing_locals(); + + // Filter potential_captures to get actual implicit captures + let implicit_captures: AHashSet = scope_info + .potential_captures + .into_iter() + .filter(|name| enclosing_locals.contains(name)) + .collect(); + + // Re-borrow the live globals handle for the lambda preparer. + let globals = self.globals.reborrow(); + + // Pass 2: Create child preparer for lambda body with scope info + let mut inner_prepare = Prepare::new_function( + ¶m_names, + position, + scope_info.assigned_names, + scope_info.global_names, + &scope_info.nonlocal_names, + &implicit_captures, + globals, + enclosing_locals, + &scope_info.cell_var_names, + self.interner, + )?; + + // Prepare the lambda body + let prepared_body = inner_prepare.prepare_nodes(body_nodes)?; + + // Move the lambda's per-function state out so its `GlobalsRef` is + // released before we touch `self`'s function state. + let PrepareState::Function(inner_state) = mem::replace(&mut inner_prepare.state, PrepareState::Module) else { + unreachable!("lambda preparer was constructed with new_function"); + }; + let FunctionState { + locals: inner_locals, + free_var_map: inner_free_var_map, + cell_var_map: inner_cell_var_map, + .. + } = *inner_state; + let namespace_size = inner_locals.len(); + drop(inner_prepare); + + // Record every variable the lambda captured from us (filing each as an + // owned cell or a pass-through free var) and build its slot vectors. + let FinalizedScope { + free_var_enclosing_slots, + free_var_slots, + cell_var_slots, + cell_param_indices, + } = self.finalize_child_scope(inner_free_var_map, inner_cell_var_map, ¶m_names, position)?; + + // Build the runtime Signature from the parsed signature + let pos_args: Vec = parsed_sig.pos_args.iter().map(|p| p.name).collect(); + let pos_defaults_count = parsed_sig.pos_args.iter().filter(|p| p.default.is_some()).count(); + let args: Vec = parsed_sig.args.iter().map(|p| p.name).collect(); + let arg_defaults_count = parsed_sig.args.iter().filter(|p| p.default.is_some()).count(); + let mut kwargs: Vec = Vec::with_capacity(parsed_sig.kwargs.len()); + let mut kwarg_default_map: Vec> = Vec::with_capacity(parsed_sig.kwargs.len()); + let mut kwarg_default_index = 0; + for param in &parsed_sig.kwargs { + kwargs.push(param.name); + if param.default.is_some() { + kwarg_default_map.push(Some(kwarg_default_index)); + kwarg_default_index += 1; + } else { + kwarg_default_map.push(None); + } + } + + let signature = Signature::new( + pos_args, + pos_defaults_count, + args, + arg_defaults_count, + parsed_sig.var_args, + kwargs, + kwarg_default_map, + parsed_sig.var_kwargs, + ); + + // Collect and prepare default expressions (evaluated in enclosing scope) + let mut default_exprs = Vec::with_capacity(signature.total_defaults_count()); + for param in &parsed_sig.pos_args { + if let Some(ref expr) = param.default { + default_exprs.push(self.prepare_expression(expr.clone())?); + } + } + for param in &parsed_sig.args { + if let Some(ref expr) = param.default { + default_exprs.push(self.prepare_expression(expr.clone())?); + } + } + for param in &parsed_sig.kwargs { + if let Some(ref expr) = param.default { + default_exprs.push(self.prepare_expression(expr.clone())?); + } + } + + // Create the prepared function definition (lambdas are never async) + let func_def = PreparedFunctionDef { + name: lambda_name, + signature, + body: prepared_body, + namespace_size, + free_var_names: free_var_slots + .iter() + .map(|slot| inner_locals.names()[slot.index()]) + .collect(), + free_var_enclosing_slots, + free_var_slots, + cell_var_slots, + cell_param_indices, + default_exprs, + is_async: false, + }; + + Ok(ExprLoc::new( + position, + Expr::Lambda { + func_def: Box::new(func_def), + }, + )) + } + + /// Resolves an identifier to its namespace index and scope, creating a new entry if needed. + /// + /// TODO This whole implementation seems ugly at best. + /// + /// This is the core name resolution mechanism with scope-aware resolution: + /// + /// **At module level:** All names go to the local namespace (which IS the global namespace). + /// + /// **In functions:** + /// - If name is declared `global` → resolve to global namespace + /// - If name is declared `nonlocal` → resolve to enclosing scope via Cell + /// - If name is assigned in this function → resolve to local namespace + /// - If name exists in global namespace (read-only access) → resolve to global namespace + /// - Otherwise → resolve to local namespace (will be NameError at runtime) + /// + /// Resolves an identifier for an assignment-position store (e.g. walrus target). + /// + /// Per PEP 572, walrus operators inside comprehensions bind in the **enclosing** + /// scope, not the comprehension. The same applies to any other store target + /// that is not a comprehension's own generator target. Bypassing + /// `comp_name_scopes` ensures the store can never accidentally land in a + /// comp-var slot that happens to share its name. Generator target stores + /// are installed by `prepare_unpack_target_for_comprehension` and never come + /// through here. + fn get_id_for_store_target(&mut self, ident: Identifier) -> Result { + let saved_scopes = mem::take(&mut self.comp_name_scopes); + let result = self.get_id(ident); + self.comp_name_scopes = saved_scopes; + result + } + + fn get_id(&mut self, ident: Identifier) -> Result { + self.get_id_impl(ident, false) + } + + /// Resolves an identifier for an expression-position READ. + /// + /// Identical to [`Self::get_id`] except in class-body scopes, where a read + /// of a class member whose binding statement has not yet been prepared + /// falls back to the module-global namespace (CPython `LOAD_NAME` + /// semantics — see `bound_class_members`) instead of the member's local + /// slot. Store targets must keep using `get_id` so they always bind the + /// member's local slot. + fn get_id_read(&mut self, ident: Identifier) -> Result { + self.get_id_impl(ident, true) + } + + fn get_id_impl(&mut self, ident: Identifier, is_read: bool) -> Result { + let name_id = ident.name_id; + let position = ident.position; + // Note: `names_used` is intentionally NOT updated here. The "name 'X' + // is used prior to global declaration" diagnostic must fire only for + // genuine READS (an `Expr::Name` referenced as a value), not for + // assignment-target resolutions that share this entry point. Write + // sites populate `names_assigned_in_order` themselves; read sites + // populate `names_used` from `resolve_name_or_builtin` (which is the + // canonical name-read path). Import bindings call `get_id` to + // resolve the slot but skip both tracking sets, matching CPython's + // quirk where `import X; global X` is accepted (see issue #423). + + // Read path: check the comp-name scope stack first, top-down. A name + // bound by a generator target shadows any same-named outer binding + // *for ordinary expression-position reads inside the comprehension*. + // Walrus targets and other assignment-position stores take a separate + // path that bypasses the comp scope (see `get_id_for_store_target`), + // so this lookup is read-only-safe. + for scope in self.comp_name_scopes.iter().rev() { + if let Some(binding) = scope.get(&name_id) { + return Ok(Identifier::new_with_scope( + name_id, + position, + NamespaceId::new(usize::from(binding.slot)).expect("comp-var slot fits in NamespaceId"), + NameScope::CompVar, + )); + } + } + + // In a class body, a READ of a member that has not been bound yet + // cannot hit its local slot: CPython's `LOAD_NAME` falls back to + // globals → builtins (never enclosing function locals). The linear + // class-body grammar makes "bound yet" a compile-time fact, so resolve + // straight to a late-bound global slot — at runtime an `Undefined` + // global picks up a builtin or raises `NameError`, exactly the + // `LOAD_NAME` tail. See `bound_class_members` for the full rationale. + if is_read + && self.is_class_scope + && !self.bound_class_members.contains(&name_id) + && matches!(&self.state, PrepareState::Function(state) if state.assigned_names.contains(&name_id)) + { + let slot = self.globals.ensure_slot(name_id, position)?; + return Ok(Identifier::new_with_scope(name_id, position, slot, NameScope::Global)); + } + + // At module scope every name is a global — the module's local namespace + // IS the global namespace, and Python module scope has no + // `UnboundLocalError`, only `NameError`. Every reference allocates a + // module slot on first sight; subsequent references reuse it. Reads + // of never-bound names get a slot too — they need it to store any + // value resolved by the host. + // + // Comprehensions don't reach this branch: their loop variables live + // in `NameScope::CompVar`, handled by the comp-name scope lookup above. + let fn_state = match &mut self.state { + PrepareState::Module => { + let slot = self.globals.ensure_slot(name_id, position)?; + let scope = if self.top_level_by_name && !self.module_global_names.contains(&name_id) { + NameScope::Name + } else { + NameScope::Global + }; + return Ok(Identifier::new_with_scope(name_id, position, slot, scope)); + } + PrepareState::Function(state) => state, + }; + + // In a function: walk the scope cascade. + + // 1. Declared `global` — resolve to a module slot. + if fn_state.global_names.contains(&name_id) { + let slot = self.globals.ensure_slot(name_id, position)?; + return Ok(Identifier::new_with_scope(name_id, position, slot, NameScope::Global)); + } + + // 2. Captured from enclosing scope (nonlocal declaration or implicit capture). + if let Some(&slot) = fn_state.free_var_map.get(&name_id) { + return Ok(Identifier::new_with_scope(name_id, position, slot, NameScope::Cell)); + } + + // 3. A cell variable (a local of ours captured by nested functions). + if let Some(&slot) = fn_state.cell_var_map.get(&name_id) { + return Ok(Identifier::new_with_scope(name_id, position, slot, NameScope::Cell)); + } + + // 4. Assigned in this function (a true local). + if fn_state.assigned_names.contains(&name_id) { + let slot = fn_state.locals.ensure_slot(name_id, position)?; + return Ok(Identifier::new_with_scope(name_id, position, slot, NameScope::Local)); + } + + // 5. Pre-populated in `locals` (a parameter that's not also assigned + // in the body, or a cell/free slot reserved by `new_function`). + // This MUST be checked before `enclosing_locals` so a parameter + // `def inner(x)` shadows a same-named outer binding instead of + // being mis-resolved as a closure capture. + if let Some(slot) = fn_state.locals.get(name_id) { + return Ok(Identifier::new_with_scope(name_id, position, slot, NameScope::Local)); + } + + // 6. Bound in an enclosing scope — implicit closure capture. + if fn_state.enclosing_locals.contains(&name_id) { + let slot = fn_state.locals.ensure_slot(name_id, position)?; + fn_state.free_var_map.insert(name_id, slot); + return Ok(Identifier::new_with_scope(name_id, position, slot, NameScope::Cell)); + } + + // 7. Fall back to the module global namespace. The name is either + // already there (an implicit global read of a module-level binding) + // or we allocate a fresh slot for it (typo, builtin, external + // function — runtime resolution will find `Undefined` and either + // pick up a builtin or yield to the host). + let slot = self.globals.ensure_slot(name_id, position)?; + Ok(Identifier::new_with_scope(name_id, position, slot, NameScope::Global)) + } + + /// Prepares an f-string part by resolving names in interpolated expressions. + fn prepare_fstring_part(&mut self, part: FStringPart) -> Result { + match part { + FStringPart::Literal(s) => Ok(FStringPart::Literal(s)), + FStringPart::Interpolation { + expr, + conversion, + format_spec, + debug_prefix, + } => { + let prepared_expr = Box::new(self.prepare_expression(*expr)?); + let prepared_spec = match format_spec { + Some(FormatSpec::Static(s)) => Some(FormatSpec::Static(s)), + Some(FormatSpec::Dynamic(parts)) => { + let prepared = parts + .into_iter() + .map(|p| self.prepare_fstring_part(p)) + .collect::, _>>()?; + Some(FormatSpec::Dynamic(prepared)) + } + None => None, + }; + Ok(FStringPart::Interpolation { + expr: prepared_expr, + conversion, + format_spec: prepared_spec, + debug_prefix, + }) + } + } + } +} + +/// The closure-slot vectors produced when a freshly-prepared child scope +/// (function, lambda, or class body) is finalized against its parent. +/// +/// Built by [`Prepare::finalize_child_scope`] after the bubble-up that records +/// each captured name against the parent. These are exactly the fields the +/// compiler needs to emit `MakeFunction`/`MakeClosure` and install cells at +/// call time; see [`crate::function::Function`] for their meaning. +struct FinalizedScope { + free_var_enclosing_slots: Vec, + free_var_slots: Vec, + cell_var_slots: Vec, + cell_param_indices: Vec>, +} + +/// Information collected from the first-pass scan of a function body. +/// +/// Holds the scope-related name sets needed for the second pass of function +/// preparation and for closure analysis. +struct FunctionScopeInfo { + /// Names declared as `global` + global_names: AHashSet, + /// Names declared as `nonlocal` + nonlocal_names: AHashSet, + /// Names that are assigned in this scope + assigned_names: AHashSet, + /// Names that are captured by nested functions (must be stored in cells) + cell_var_names: AHashSet, + /// Names that are referenced but not local, global, or nonlocal. + /// These are POTENTIAL implicit captures - they may be captures from an enclosing function + /// OR they may be builtin/global reads. The actual implicit captures are determined + /// by filtering against enclosing_locals in new_function. + potential_captures: AHashSet, +} + +/// Builds the parallel owned-cell vectors for a nested scope from its cell-var +/// map (`name -> slot`). +/// +/// Returns `(cell_var_slots, cell_param_indices)`, ordered by slot: the slot +/// where each fresh cell is installed at call time, and the parameter index it +/// should be seeded from when the cell is for one of `params` (else `None`). +fn build_cell_slots( + cell_var_map: AHashMap, + params: &[StringId], +) -> (Vec, Vec>) { + let param_name_to_index: AHashMap = params + .iter() + .enumerate() + .map(|(idx, &name_id)| (name_id, idx)) + .collect(); + let mut entries: Vec<_> = cell_var_map.into_iter().collect(); + entries.sort_by_key(|(_, slot)| *slot); + let slots = entries.iter().map(|(_, slot)| *slot).collect(); + let param_indices = entries + .iter() + .map(|(name, _)| param_name_to_index.get(name).copied()) + .collect(); + (slots, param_indices) +} + +/// Scans a function body to collect scope information (first phase of preparation). +/// +/// This function performs three passes over the AST: +/// 1. Collect global, nonlocal, and assigned names +/// 2. Identify cell_vars (names captured by nested functions) +/// 3. Collect potential implicit captures (referenced but not local/global/nonlocal) +/// +/// The collected information includes: +/// - Names declared as `global` (from Global statements) +/// - Names declared as `nonlocal` (from Nonlocal statements) +/// - Names that are assigned (from Assign, OpAssign, For targets, etc.) +/// - Names that are captured by nested functions (cell_var_names) +/// - Names that might be captured from enclosing scope (potential_captures) +/// +/// This information is used to determine whether each name reference should resolve +/// to the local namespace, global namespace, or an enclosing scope via cells. +fn collect_function_scope_info( + nodes: &[ParseNode], + params: &[StringId], + interner: &CompileInterns<'_>, +) -> FunctionScopeInfo { + let mut global_names = AHashSet::new(); + let mut nonlocal_names = AHashSet::new(); + let mut assigned_names = AHashSet::new(); + let mut cell_var_names = AHashSet::new(); + let mut referenced_names = AHashSet::new(); + + // First pass: collect global, nonlocal, and assigned names + for node in nodes { + collect_scope_info_from_node( + node, + &mut global_names, + &mut nonlocal_names, + &mut assigned_names, + interner, + ); + } + + // Build the set of our locals: params + assigned_names (excluding globals) + let param_names: AHashSet = params.iter().copied().collect(); + + let our_locals: AHashSet = param_names + .iter() + .copied() + .chain(assigned_names.iter().copied()) + .filter(|name| !global_names.contains(name)) + .collect(); + + // Second pass: find what nested functions capture from us + for node in nodes { + collect_cell_vars_from_node(node, &our_locals, &mut cell_var_names, interner); + } + + // Third pass: collect all referenced names to identify potential implicit captures. + // These are names that might be captured from an enclosing function scope. + // We can't fully determine implicit captures here because we don't know yet what + // the enclosing scope's locals are - that's determined later when we call new_function. + for node in nodes { + collect_referenced_names_from_node(node, &mut referenced_names, interner); + } + + // Potential implicit captures are names that are: + // - Referenced in the function body + // - Not local (not params, not assigned) + // - Not declared global + // - Not declared nonlocal (those are handled separately) + // The actual implicit captures will be filtered against enclosing_locals in new_function. + let potential_captures: AHashSet = referenced_names + .into_iter() + .filter(|name| !our_locals.contains(name) && !global_names.contains(name) && !nonlocal_names.contains(name)) + .collect(); + + FunctionScopeInfo { + global_names, + nonlocal_names, + assigned_names, + cell_var_names, + potential_captures, + } +} + +/// Helper to collect scope info from a single node. +fn collect_scope_info_from_node( + node: &ParseNode, + global_names: &mut AHashSet, + nonlocal_names: &mut AHashSet, + assigned_names: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match node { + Node::Global { names, .. } => { + for string_id in names { + global_names.insert(*string_id); + } + } + Node::Nonlocal { names, .. } => { + for string_id in names { + nonlocal_names.insert(*string_id); + } + } + Node::Assign { target, object } => { + assigned_names.insert(target.name_id); + // Scan value expression for walrus operators + collect_assigned_names_from_expr(object, assigned_names, interner); + } + Node::UnpackAssign { targets, object, .. } => { + // Recursively collect all names from nested unpack targets + for target in targets { + collect_names_from_unpack_target(target, assigned_names, interner); + } + // Scan value expression for walrus operators + collect_assigned_names_from_expr(object, assigned_names, interner); + } + Node::OpAssign { target, value, .. } => { + assigned_names.insert(target.name_id); + // Scan value expression for walrus operators + collect_assigned_names_from_expr(value, assigned_names, interner); + } + Node::SubscriptOpAssign { + target, index, value, .. + } => { + collect_assigned_names_from_expr(target, assigned_names, interner); + collect_assigned_names_from_expr(index, assigned_names, interner); + collect_assigned_names_from_expr(value, assigned_names, interner); + } + Node::SubscriptAssign { + target, index, value, .. + } => { + // Subscript assignment doesn't create a new name, it modifies existing container + // But scan expressions for walrus operators + collect_assigned_names_from_expr(target, assigned_names, interner); + collect_assigned_names_from_expr(index, assigned_names, interner); + collect_assigned_names_from_expr(value, assigned_names, interner); + } + Node::AttrOpAssign { object, value, .. } => { + collect_assigned_names_from_expr(object, assigned_names, interner); + collect_assigned_names_from_expr(value, assigned_names, interner); + } + Node::AttrAssign { object, value, .. } => { + // Attribute assignment doesn't create a new name, it modifies existing object + // But scan expressions for walrus operators + collect_assigned_names_from_expr(object, assigned_names, interner); + collect_assigned_names_from_expr(value, assigned_names, interner); + } + Node::ChainAssign { targets, object } => { + // Each target sees the same shared RHS; treat it like each per-target + // assignment would be treated individually. + for target in targets { + collect_assigned_names_from_assign_target(target, assigned_names, interner); + } + collect_assigned_names_from_expr(object, assigned_names, interner); + } + Node::For { + target, + iter, + body, + or_else, + } => { + // For loop target is assigned - collect all names from the target + collect_names_from_unpack_target(target, assigned_names, interner); + // Scan iter expression for walrus operators + collect_assigned_names_from_expr(iter, assigned_names, interner); + // Recurse into body and else + for n in body { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + for n in or_else { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + } + Node::While { test, body, or_else } => { + // Scan test expression for walrus operators + collect_assigned_names_from_expr(test, assigned_names, interner); + // Recurse into body and else blocks + for n in body { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + for n in or_else { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + } + Node::If { test, body, or_else } => { + // Scan test expression for walrus operators + collect_assigned_names_from_expr(test, assigned_names, interner); + // Recurse into branches + for n in body { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + for n in or_else { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + } + Node::FunctionDef { + def: RawFunctionDef { name, .. }, + decorators, + } => { + // Function definition creates a local binding for the function name + // But we don't recurse into the function body - that's a separate scope + assigned_names.insert(name.name_id); + // Decorators evaluate in *this* scope, so a walrus in one binds here. + for decorator in decorators { + collect_assigned_names_from_expr(decorator, assigned_names, interner); + } + } + Node::ClassDef { name, decorators, .. } => { + // A class definition binds the class name in this scope, just like a `def`. + // The class body is a separate scope (handled by the cell-var pass). + assigned_names.insert(name.name_id); + // Decorators evaluate in *this* scope, so a walrus in one binds here. + for decorator in decorators { + collect_assigned_names_from_expr(decorator, assigned_names, interner); + } + } + Node::Try(Try { + body, + handlers, + or_else, + finally, + }) => { + // Recurse into all blocks + for n in body { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + for handler in handlers { + // Exception variable name is assigned + if let Some(ref name) = handler.name { + assigned_names.insert(name.name_id); + } + for n in &handler.body { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + } + for n in or_else { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + for n in finally { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + } + Node::Match { subject, cases, .. } => { + collect_assigned_names_from_expr(subject, assigned_names, interner); + for case in cases { + collect_pattern_captures(&case.pattern, assigned_names); + for_each_pattern_expr(&case.pattern, &mut |expr| { + collect_assigned_names_from_expr(expr, assigned_names, interner); + }); + if let Some(guard) = &case.guard { + collect_assigned_names_from_expr(guard, assigned_names, interner); + } + for n in &case.body { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + } + } + Node::With { + context, target, body, .. + } => { + // The `as TARGET` binds names like a for-loop target does. + if let Some(t) = target { + collect_names_from_unpack_target(t, assigned_names, interner); + } + // Scan the context expression for walrus operators. + collect_assigned_names_from_expr(context, assigned_names, interner); + for n in body { + collect_scope_info_from_node(n, global_names, nonlocal_names, assigned_names, interner); + } + } + // Import creates bindings for each module name (or alias) + Node::Import { names, .. } => { + for import_name in names { + assigned_names.insert(import_name.binding.name_id); + } + } + // ImportFrom creates bindings for each imported name (or alias) + Node::ImportFrom { names, .. } => { + for (_import_name, binding) in names { + assigned_names.insert(binding.name_id); + } + } + // Statements with expressions that may contain walrus operators + Node::Expr(expr) | Node::Return(Some(expr)) | Node::Raise(Some(expr)) => { + collect_assigned_names_from_expr(expr, assigned_names, interner); + } + Node::Assert { test, msg } => { + collect_assigned_names_from_expr(test, assigned_names, interner); + if let Some(m) = msg { + collect_assigned_names_from_expr(m, assigned_names, interner); + } + } + // These don't create new names + Node::Pass | Node::Return(None) | Node::Raise(None) | Node::Break { .. } | Node::Continue { .. } => {} + } +} + +/// Collects names assigned by walrus operators (`:=`) within an expression. +/// +/// Per PEP 572, walrus operator targets are assignments in the enclosing scope. +/// This function recursively scans expressions to find all `Named` expression targets. +/// It does NOT recurse into lambda bodies as those have their own scope. +fn collect_assigned_names_from_expr( + expr: &ExprLoc, + assigned_names: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match &expr.expr { + Expr::Named { target, value } => { + // The target of a walrus operator is assigned in this scope + assigned_names.insert(target.name_id); + // Also scan the value expression + collect_assigned_names_from_expr(value, assigned_names, interner); + } + // Recurse into sub-expressions + Expr::List(items) | Expr::Tuple(items) | Expr::Set(items) => { + for item in items { + let expr = match item { + SequenceItem::Value(e) | SequenceItem::Unpack(e) => e, + }; + collect_assigned_names_from_expr(expr, assigned_names, interner); + } + } + Expr::Dict(dict_items) => { + for item in dict_items { + match item { + DictItem::Pair(key, value) => { + collect_assigned_names_from_expr(key, assigned_names, interner); + collect_assigned_names_from_expr(value, assigned_names, interner); + } + DictItem::Unpack(e) => collect_assigned_names_from_expr(e, assigned_names, interner), + } + } + } + Expr::Op { left, right, .. } | Expr::CmpOp { left, right, .. } => { + collect_assigned_names_from_expr(left, assigned_names, interner); + collect_assigned_names_from_expr(right, assigned_names, interner); + } + Expr::ChainCmp { left, comparisons } => { + collect_assigned_names_from_expr(left, assigned_names, interner); + for (_, expr) in comparisons { + collect_assigned_names_from_expr(expr, assigned_names, interner); + } + } + Expr::Not(operand) + | Expr::UnaryMinus(operand) + | Expr::UnaryPlus(operand) + | Expr::UnaryInvert(operand) + | Expr::Await(operand) => { + collect_assigned_names_from_expr(operand, assigned_names, interner); + } + Expr::Subscript { object, index } => { + collect_assigned_names_from_expr(object, assigned_names, interner); + collect_assigned_names_from_expr(index, assigned_names, interner); + } + Expr::Call { args, .. } => { + collect_assigned_names_from_args(args, assigned_names, interner); + } + Expr::AttrCall { object, args, .. } => { + collect_assigned_names_from_expr(object, assigned_names, interner); + collect_assigned_names_from_args(args, assigned_names, interner); + } + Expr::IndirectCall { callable, args } => { + collect_assigned_names_from_expr(callable, assigned_names, interner); + collect_assigned_names_from_args(args, assigned_names, interner); + } + Expr::AttrGet { object, .. } => { + collect_assigned_names_from_expr(object, assigned_names, interner); + } + Expr::IfElse { test, body, orelse } => { + collect_assigned_names_from_expr(test, assigned_names, interner); + collect_assigned_names_from_expr(body, assigned_names, interner); + collect_assigned_names_from_expr(orelse, assigned_names, interner); + } + // Per PEP 572, walrus in comprehensions assigns to the ENCLOSING scope + Expr::ListComp { elt, generators, .. } | Expr::SetComp { elt, generators, .. } => { + collect_assigned_names_from_expr(elt, assigned_names, interner); + for generator in generators { + collect_assigned_names_from_expr(&generator.iter, assigned_names, interner); + for cond in &generator.ifs { + collect_assigned_names_from_expr(cond, assigned_names, interner); + } + } + } + Expr::DictComp { + key, value, generators, .. + } => { + collect_assigned_names_from_expr(key, assigned_names, interner); + collect_assigned_names_from_expr(value, assigned_names, interner); + for generator in generators { + collect_assigned_names_from_expr(&generator.iter, assigned_names, interner); + for cond in &generator.ifs { + collect_assigned_names_from_expr(cond, assigned_names, interner); + } + } + } + Expr::FString(parts) => { + for part in parts { + if let FStringPart::Interpolation { expr, .. } = part { + collect_assigned_names_from_expr(expr, assigned_names, interner); + } + } + } + Expr::Slice { lower, upper, step } => { + if let Some(e) = lower { + collect_assigned_names_from_expr(e, assigned_names, interner); + } + if let Some(e) = upper { + collect_assigned_names_from_expr(e, assigned_names, interner); + } + if let Some(e) = step { + collect_assigned_names_from_expr(e, assigned_names, interner); + } + } + // Lambda bodies have their own scope - walrus inside them doesn't affect us + Expr::LambdaRaw { .. } | Expr::Lambda { .. } => {} + // Leaf expressions don't contain walrus operators + Expr::Literal(_) | Expr::Builtin(_) | Expr::Name(_) => {} + } +} + +/// Helper to collect assigned names from argument expressions. +fn collect_assigned_names_from_args( + args: &ArgExprs, + assigned_names: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match args { + ArgExprs::Empty => {} + ArgExprs::One(arg) => collect_assigned_names_from_expr(arg, assigned_names, interner), + ArgExprs::Two(arg1, arg2) => { + collect_assigned_names_from_expr(arg1, assigned_names, interner); + collect_assigned_names_from_expr(arg2, assigned_names, interner); + } + ArgExprs::Args(args) => { + for arg in args { + collect_assigned_names_from_expr(arg, assigned_names, interner); + } + } + ArgExprs::Kwargs(kwargs) => { + for kwarg in kwargs { + collect_assigned_names_from_expr(&kwarg.value, assigned_names, interner); + } + } + ArgExprs::ArgsKargs { + args, + kwargs, + var_args, + var_kwargs, + } => { + if let Some(args) = args { + for arg in args { + collect_assigned_names_from_expr(arg, assigned_names, interner); + } + } + if let Some(kwargs) = kwargs { + for kwarg in kwargs { + collect_assigned_names_from_expr(&kwarg.value, assigned_names, interner); + } + } + if let Some(var_args) = var_args { + collect_assigned_names_from_expr(var_args, assigned_names, interner); + } + if let Some(var_kwargs) = var_kwargs { + collect_assigned_names_from_expr(var_kwargs, assigned_names, interner); + } + } + ArgExprs::GeneralizedCall { args, kwargs } => { + for arg in args { + match arg { + CallArg::Value(e) | CallArg::Unpack(e) => { + collect_assigned_names_from_expr(e, assigned_names, interner); + } + } + } + for kwarg in kwargs { + match kwarg { + CallKwarg::Named(kw) => { + collect_assigned_names_from_expr(&kw.value, assigned_names, interner); + } + CallKwarg::Unpack(e) => { + collect_assigned_names_from_expr(e, assigned_names, interner); + } + } + } + } + } +} + +/// Collects cell_vars by analyzing what nested functions capture from our scope. +/// +/// For each FunctionDef node, we recursively analyze its body to find what names it +/// references. Any name that is in `our_locals` and referenced by the nested function +/// (not as a local of the nested function) becomes a cell_var. +fn collect_cell_vars_from_node( + node: &ParseNode, + our_locals: &AHashSet, + cell_vars: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match node { + Node::FunctionDef { + def: RawFunctionDef { signature, body, .. }, + decorators, + } => { + collect_cell_vars_from_function(signature, body, our_locals, cell_vars, interner); + // A nested scope inside a decorator expression (a lambda in decorator + // position, or one passed to a factory) can capture our locals too. + for decorator in decorators { + collect_cell_vars_from_expr(decorator, our_locals, cell_vars, interner); + } + } + Node::ClassDef { body, decorators, .. } => { + // The class body is a nested scope of *this* scope, like a `def`: any + // of our locals referenced from the class-var values or (transitively) + // the method bodies becomes a cell var. `collect_cell_vars_from_function` + // recurses into the nested method bodies for us. + collect_cell_vars_from_function(&body.signature, &body.body, our_locals, cell_vars, interner); + // A nested scope inside a decorator expression (a lambda in decorator + // position, or one passed to a factory) can capture our locals too. + for decorator in decorators { + collect_cell_vars_from_expr(decorator, our_locals, cell_vars, interner); + } + } + // Recurse into control flow structures + Node::For { + target, + iter, + body, + or_else, + } => { + // Attribute/subscript targets embed expressions that may hold lambdas. + collect_cell_vars_from_unpack_target(target, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(iter, our_locals, cell_vars, interner); + for n in body { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + for n in or_else { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + } + Node::While { test, body, or_else } => { + collect_cell_vars_from_expr(test, our_locals, cell_vars, interner); + for n in body { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + for n in or_else { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + } + Node::If { test, body, or_else } => { + collect_cell_vars_from_expr(test, our_locals, cell_vars, interner); + for n in body { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + for n in or_else { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + } + Node::Try(Try { + body, + handlers, + or_else, + finally, + }) => { + for n in body { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + for handler in handlers { + if let Some(exc_type) = &handler.exc_type { + collect_cell_vars_from_expr(exc_type, our_locals, cell_vars, interner); + } + for n in &handler.body { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + } + for n in or_else { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + for n in finally { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + } + Node::Match { subject, cases, .. } => { + collect_cell_vars_from_expr(subject, our_locals, cell_vars, interner); + for case in cases { + for_each_pattern_expr(&case.pattern, &mut |expr| { + collect_cell_vars_from_expr(expr, our_locals, cell_vars, interner); + }); + if let Some(guard) = &case.guard { + collect_cell_vars_from_expr(guard, our_locals, cell_vars, interner); + } + for n in &case.body { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + } + } + Node::With { + context, target, body, .. + } => { + collect_cell_vars_from_expr(context, our_locals, cell_vars, interner); + if let Some(target) = target { + collect_cell_vars_from_unpack_target(target, our_locals, cell_vars, interner); + } + for n in body { + collect_cell_vars_from_node(n, our_locals, cell_vars, interner); + } + } + // Handle expressions that may contain lambdas + Node::Expr(expr) | Node::Return(Some(expr)) | Node::Raise(Some(expr)) => { + collect_cell_vars_from_expr(expr, our_locals, cell_vars, interner); + } + Node::Assert { test, msg } => { + collect_cell_vars_from_expr(test, our_locals, cell_vars, interner); + if let Some(msg) = msg { + collect_cell_vars_from_expr(msg, our_locals, cell_vars, interner); + } + } + Node::Assign { object, .. } => { + collect_cell_vars_from_expr(object, our_locals, cell_vars, interner); + } + Node::UnpackAssign { targets, object, .. } => { + for target in targets { + collect_cell_vars_from_unpack_target(target, our_locals, cell_vars, interner); + } + collect_cell_vars_from_expr(object, our_locals, cell_vars, interner); + } + Node::OpAssign { value, .. } => { + collect_cell_vars_from_expr(value, our_locals, cell_vars, interner); + } + Node::SubscriptOpAssign { + target, index, value, .. + } => { + collect_cell_vars_from_expr(target, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(index, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(value, our_locals, cell_vars, interner); + } + Node::SubscriptAssign { + target, index, value, .. + } => { + collect_cell_vars_from_expr(target, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(index, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(value, our_locals, cell_vars, interner); + } + Node::AttrOpAssign { object, value, .. } => { + collect_cell_vars_from_expr(object, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(value, our_locals, cell_vars, interner); + } + Node::AttrAssign { object, value, .. } => { + collect_cell_vars_from_expr(object, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(value, our_locals, cell_vars, interner); + } + Node::ChainAssign { targets, object } => { + for target in targets { + collect_cell_vars_from_assign_target(target, our_locals, cell_vars, interner); + } + collect_cell_vars_from_expr(object, our_locals, cell_vars, interner); + } + // Listed rather than matched by `_`: a missed capture compiles a local's + // stores as plain stores and its later loads as cell loads. + Node::Pass + | Node::Return(None) + | Node::Raise(None) + | Node::Break { .. } + | Node::Continue { .. } + | Node::Global { .. } + | Node::Nonlocal { .. } + | Node::Import { .. } + | Node::ImportFrom { .. } => {} + } +} + +/// Detects which of `our_locals` a nested function (a `def` or a class method) +/// captures — directly or transitively — marking each as a cell var of the +/// enclosing scope. +/// +/// Shared by the `FunctionDef` and `ClassDef` arms of +/// [`collect_cell_vars_from_node`]: a name referenced by the nested function that +/// is not one of its own locals/params/globals, but *is* one of `our_locals`, +/// must be promoted to a heap cell so the nested function can capture it. The +/// same applies to names referenced by the nested function's *default* +/// expressions (evaluated in our scope at definition time) and to names captured +/// by functions nested deeper still (the transitive recursion at the end). +fn collect_cell_vars_from_function( + signature: &ParsedSignature, + body: &[ParseNode], + our_locals: &AHashSet, + cell_vars: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + // This nested function's *default* expressions are evaluated in OUR + // scope at definition time, not inside the nested function — so any + // name they reference that is one of our locals is captured by us, + // regardless of the nested function's own params/assignments (cf. + // the `def f(a=a)` gotcha, where the right-hand `a` is enclosing). + // Body references are filtered below; defaults are not. + for default in signature.default_exprs() { + let mut default_referenced = AHashSet::new(); + collect_referenced_names_from_expr(default, &mut default_referenced, interner); + for name in &default_referenced { + if our_locals.contains(name) { + cell_vars.insert(*name); + } + } + } + + // Find what names are referenced inside this nested function + let mut referenced = AHashSet::new(); + for n in body { + collect_referenced_names_from_node(n, &mut referenced, interner); + } + + // Extract param names from signature for scope analysis + let param_names: Vec = signature.param_names().collect(); + + // Collect *only* this nested function's own bindings (params + + // assigned + global/nonlocal declarations). Use + // `collect_scope_info_from_node`, which does NOT descend into + // further-nested functions, rather than `collect_function_scope_info`: + // the latter re-runs this entire cell-var pass for the nested body, + // which — combined with the transitive recursion below — would make + // the analysis exponential in nesting depth (`C(d) = 2·C(d-1)`). + // The deeper captures are found by the explicit recursion instead. + let mut nested_global = AHashSet::new(); + let mut nested_nonlocal = AHashSet::new(); + let mut nested_assigned = AHashSet::new(); + for n in body { + collect_scope_info_from_node( + n, + &mut nested_global, + &mut nested_nonlocal, + &mut nested_assigned, + interner, + ); + } + + // Any name that is: + // - Referenced by the nested function + // - Not a local of the nested function + // - Not declared global in the nested function + // - In our locals + // becomes a cell_var + let nested_param_set: AHashSet = param_names.iter().copied().collect(); + for name in &referenced { + if !nested_assigned.contains(name) + && !nested_param_set.contains(name) + && !nested_global.contains(name) + && our_locals.contains(name) + { + cell_vars.insert(*name); + } + } + + // Also check what the nested function explicitly declares as nonlocal + for name in &nested_nonlocal { + if our_locals.contains(name) { + cell_vars.insert(*name); + } + } + + // Transitive captures: a function nested *inside* this one can also + // capture one of our locals (e.g. `outer` -> `mid` -> `inner` + // reading an `outer` variable), unless an intermediate scope rebinds + // the name. Recurse into this function's body with our locals minus + // this function's own bindings, so deeper closures over our + // variables are recognised as cells *before* their references are + // resolved — otherwise the variable would be compiled as a plain + // local here and then promoted inconsistently. + let mut deeper_locals = our_locals.clone(); + for param_id in ¶m_names { + deeper_locals.remove(param_id); + } + for name in &nested_assigned { + deeper_locals.remove(name); + } + for name in &nested_global { + deeper_locals.remove(name); + } + if !deeper_locals.is_empty() { + for n in body { + collect_cell_vars_from_node(n, &deeper_locals, cell_vars, interner); + } + } +} + +/// Collects cell_vars from lambda expressions within an expression. +/// +/// Recursively searches through an expression tree to find lambda expressions +/// that capture variables from the enclosing scope. +fn collect_cell_vars_from_expr( + expr: &ExprLoc, + our_locals: &AHashSet, + cell_vars: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + use crate::expressions::Expr; + match &expr.expr { + Expr::LambdaRaw { signature, body, .. } => { + // This lambda's *default* expressions are evaluated in OUR scope at + // definition time, not inside the lambda — so any name they + // reference that is one of our locals is captured by us, regardless + // of the lambda's own params. Crucially the default must NOT be + // filtered by the lambda's params: in `lambda x=(lambda: x): x()` + // the inner lambda captures the enclosing `x`, not the param `x`, + // so filtering would drop the required outer cell. Body references + // are filtered below; defaults are not. + for default in signature.default_exprs() { + let mut default_referenced = AHashSet::new(); + collect_referenced_names_from_expr(default, &mut default_referenced, interner); + for name in &default_referenced { + if our_locals.contains(name) { + cell_vars.insert(*name); + } + } + } + + // Find what names are referenced in the lambda body + let mut referenced = AHashSet::new(); + collect_referenced_names_from_expr(body, &mut referenced, interner); + + // Extract param names from signature + let param_names: Vec = signature.param_names().collect(); + + // A body reference becomes a cell_var if it is not one of the + // lambda's own params (which the lambda binds itself) and is one of + // our locals. + let lambda_param_set: AHashSet = param_names.iter().copied().collect(); + for name in &referenced { + if !lambda_param_set.contains(name) && our_locals.contains(name) { + cell_vars.insert(*name); + } + } + + // Recursively check the lambda body for nested lambdas. + // For nested lambdas, extend our_locals to include this lambda's parameters + // so that inner lambdas can find them for closure capture. + let mut extended_locals = our_locals.clone(); + for param_id in ¶m_names { + extended_locals.insert(*param_id); + } + collect_cell_vars_from_expr(body, &extended_locals, cell_vars, interner); + } + // Recurse into sub-expressions + Expr::List(items) | Expr::Tuple(items) | Expr::Set(items) => { + for item in items { + let expr = match item { + SequenceItem::Value(e) | SequenceItem::Unpack(e) => e, + }; + collect_cell_vars_from_expr(expr, our_locals, cell_vars, interner); + } + } + Expr::Dict(dict_items) => { + for item in dict_items { + match item { + DictItem::Pair(key, value) => { + collect_cell_vars_from_expr(key, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(value, our_locals, cell_vars, interner); + } + DictItem::Unpack(e) => collect_cell_vars_from_expr(e, our_locals, cell_vars, interner), + } + } + } + Expr::Op { left, right, .. } | Expr::CmpOp { left, right, .. } => { + collect_cell_vars_from_expr(left, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(right, our_locals, cell_vars, interner); + } + Expr::ChainCmp { left, comparisons } => { + collect_cell_vars_from_expr(left, our_locals, cell_vars, interner); + for (_, expr) in comparisons { + collect_cell_vars_from_expr(expr, our_locals, cell_vars, interner); + } + } + Expr::Not(operand) | Expr::UnaryMinus(operand) | Expr::UnaryPlus(operand) | Expr::UnaryInvert(operand) => { + collect_cell_vars_from_expr(operand, our_locals, cell_vars, interner); + } + Expr::Subscript { object, index } => { + collect_cell_vars_from_expr(object, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(index, our_locals, cell_vars, interner); + } + Expr::Call { args, .. } => { + collect_cell_vars_from_args(args, our_locals, cell_vars, interner); + } + Expr::AttrCall { object, args, .. } => { + collect_cell_vars_from_expr(object, our_locals, cell_vars, interner); + collect_cell_vars_from_args(args, our_locals, cell_vars, interner); + } + Expr::IndirectCall { callable, args } => { + collect_cell_vars_from_expr(callable, our_locals, cell_vars, interner); + collect_cell_vars_from_args(args, our_locals, cell_vars, interner); + } + Expr::AttrGet { object, .. } => { + collect_cell_vars_from_expr(object, our_locals, cell_vars, interner); + } + Expr::IfElse { test, body, orelse } => { + collect_cell_vars_from_expr(test, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(body, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(orelse, our_locals, cell_vars, interner); + } + Expr::ListComp { elt, generators, .. } | Expr::SetComp { elt, generators, .. } => { + collect_cell_vars_from_expr(elt, our_locals, cell_vars, interner); + for generator in generators { + collect_cell_vars_from_expr(&generator.iter, our_locals, cell_vars, interner); + for cond in &generator.ifs { + collect_cell_vars_from_expr(cond, our_locals, cell_vars, interner); + } + } + } + Expr::DictComp { + key, value, generators, .. + } => { + collect_cell_vars_from_expr(key, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(value, our_locals, cell_vars, interner); + for generator in generators { + collect_cell_vars_from_expr(&generator.iter, our_locals, cell_vars, interner); + for cond in &generator.ifs { + collect_cell_vars_from_expr(cond, our_locals, cell_vars, interner); + } + } + } + Expr::FString(parts) => { + for part in parts { + if let FStringPart::Interpolation { expr, .. } = part { + collect_cell_vars_from_expr(expr, our_locals, cell_vars, interner); + } + } + } + Expr::Named { value, .. } => { + // Only scan the value expression for cell vars + collect_cell_vars_from_expr(value, our_locals, cell_vars, interner); + } + Expr::Await(value) => { + collect_cell_vars_from_expr(value, our_locals, cell_vars, interner); + } + // Leaf expressions + Expr::Literal(_) | Expr::Builtin(_) | Expr::Name(_) | Expr::Lambda { .. } | Expr::Slice { .. } => {} + } +} + +/// Helper to collect cell vars from argument expressions. +fn collect_cell_vars_from_args( + args: &ArgExprs, + our_locals: &AHashSet, + cell_vars: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match args { + ArgExprs::Empty => {} + ArgExprs::One(arg) => collect_cell_vars_from_expr(arg, our_locals, cell_vars, interner), + ArgExprs::Two(arg1, arg2) => { + collect_cell_vars_from_expr(arg1, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(arg2, our_locals, cell_vars, interner); + } + ArgExprs::Args(args) => { + for arg in args { + collect_cell_vars_from_expr(arg, our_locals, cell_vars, interner); + } + } + ArgExprs::Kwargs(kwargs) => { + for kwarg in kwargs { + collect_cell_vars_from_expr(&kwarg.value, our_locals, cell_vars, interner); + } + } + ArgExprs::ArgsKargs { + args, + kwargs, + var_args, + var_kwargs, + } => { + if let Some(args) = args { + for arg in args { + collect_cell_vars_from_expr(arg, our_locals, cell_vars, interner); + } + } + if let Some(kwargs) = kwargs { + for kwarg in kwargs { + collect_cell_vars_from_expr(&kwarg.value, our_locals, cell_vars, interner); + } + } + if let Some(var_args) = var_args { + collect_cell_vars_from_expr(var_args, our_locals, cell_vars, interner); + } + if let Some(var_kwargs) = var_kwargs { + collect_cell_vars_from_expr(var_kwargs, our_locals, cell_vars, interner); + } + } + ArgExprs::GeneralizedCall { args, kwargs } => { + for arg in args { + match arg { + CallArg::Value(e) | CallArg::Unpack(e) => { + collect_cell_vars_from_expr(e, our_locals, cell_vars, interner); + } + } + } + for kwarg in kwargs { + match kwarg { + CallKwarg::Named(kw) => { + collect_cell_vars_from_expr(&kw.value, our_locals, cell_vars, interner); + } + CallKwarg::Unpack(e) => { + collect_cell_vars_from_expr(e, our_locals, cell_vars, interner); + } + } + } + } + } +} + +/// Collects all names referenced (read) in a node and its descendants. +/// +/// This is used to find what names a nested function references from enclosing scopes. +fn collect_referenced_names_from_node( + node: &ParseNode, + referenced: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match node { + Node::Expr(expr) | Node::Return(Some(expr)) | Node::Raise(Some(expr)) => { + collect_referenced_names_from_expr(expr, referenced, interner); + } + Node::Return(None) | Node::Raise(None) => {} + Node::Assert { test, msg } => { + collect_referenced_names_from_expr(test, referenced, interner); + if let Some(m) = msg { + collect_referenced_names_from_expr(m, referenced, interner); + } + } + Node::Assign { object, .. } => { + collect_referenced_names_from_expr(object, referenced, interner); + } + Node::UnpackAssign { targets, object, .. } => { + for target in targets { + collect_referenced_names_from_unpack_target(target, referenced, interner); + } + collect_referenced_names_from_expr(object, referenced, interner); + } + Node::OpAssign { target, value, .. } => { + // OpAssign reads the target before writing + referenced.insert(target.name_id); + collect_referenced_names_from_expr(value, referenced, interner); + } + Node::SubscriptOpAssign { + target, index, value, .. + } => { + collect_referenced_names_from_expr(target, referenced, interner); + collect_referenced_names_from_expr(index, referenced, interner); + collect_referenced_names_from_expr(value, referenced, interner); + } + Node::SubscriptAssign { + target, index, value, .. + } => { + collect_referenced_names_from_expr(target, referenced, interner); + collect_referenced_names_from_expr(index, referenced, interner); + collect_referenced_names_from_expr(value, referenced, interner); + } + Node::AttrOpAssign { object, value, .. } => { + collect_referenced_names_from_expr(object, referenced, interner); + collect_referenced_names_from_expr(value, referenced, interner); + } + Node::AttrAssign { object, value, .. } => { + collect_referenced_names_from_expr(object, referenced, interner); + collect_referenced_names_from_expr(value, referenced, interner); + } + Node::ChainAssign { targets, object } => { + for target in targets { + collect_referenced_names_from_assign_target(target, referenced, interner); + } + collect_referenced_names_from_expr(object, referenced, interner); + } + Node::For { + target, + iter, + body, + or_else, + } => { + collect_referenced_names_from_unpack_target(target, referenced, interner); + collect_referenced_names_from_expr(iter, referenced, interner); + for n in body { + collect_referenced_names_from_node(n, referenced, interner); + } + for n in or_else { + collect_referenced_names_from_node(n, referenced, interner); + } + } + Node::While { test, body, or_else } => { + collect_referenced_names_from_expr(test, referenced, interner); + for n in body { + collect_referenced_names_from_node(n, referenced, interner); + } + for n in or_else { + collect_referenced_names_from_node(n, referenced, interner); + } + } + Node::If { test, body, or_else } => { + collect_referenced_names_from_expr(test, referenced, interner); + for n in body { + collect_referenced_names_from_node(n, referenced, interner); + } + for n in or_else { + collect_referenced_names_from_node(n, referenced, interner); + } + } + Node::FunctionDef { + def: RawFunctionDef { signature, body, .. }, + decorators, + } => { + // Recurse into the nested function's body so transitively-captured + // names propagate out of it. Without this, an intermediate scope + // that doesn't itself reference a deep capture would not see it + // — the bug behind issue #477's multi-hop closures. + collect_nested_function_references(signature, body, referenced, interner); + // Decorators evaluate in *our* scope, so their names are ours to collect. + for decorator in decorators { + collect_referenced_names_from_expr(decorator, referenced, interner); + } + } + Node::ClassDef { decorators, .. } => { + // The class body is a separate scope and the name is a binding, so + // neither is a reference here — but decorators evaluate in *our* + // scope, so their names are ours to collect. + for decorator in decorators { + collect_referenced_names_from_expr(decorator, referenced, interner); + } + } + Node::Try(Try { + body, + handlers, + or_else, + finally, + }) => { + for n in body { + collect_referenced_names_from_node(n, referenced, interner); + } + for handler in handlers { + // Exception type expression may reference names + if let Some(ref exc_type) = handler.exc_type { + collect_referenced_names_from_expr(exc_type, referenced, interner); + } + for n in &handler.body { + collect_referenced_names_from_node(n, referenced, interner); + } + } + for n in or_else { + collect_referenced_names_from_node(n, referenced, interner); + } + for n in finally { + collect_referenced_names_from_node(n, referenced, interner); + } + } + Node::Match { subject, cases, .. } => { + collect_referenced_names_from_expr(subject, referenced, interner); + for case in cases { + for_each_pattern_expr(&case.pattern, &mut |expr| { + collect_referenced_names_from_expr(expr, referenced, interner); + }); + if let Some(guard) = &case.guard { + collect_referenced_names_from_expr(guard, referenced, interner); + } + for n in &case.body { + collect_referenced_names_from_node(n, referenced, interner); + } + } + } + Node::With { + context, target, body, .. + } => { + if let Some(target) = target { + collect_referenced_names_from_unpack_target(target, referenced, interner); + } + collect_referenced_names_from_expr(context, referenced, interner); + for n in body { + collect_referenced_names_from_node(n, referenced, interner); + } + } + // Imports create bindings but don't reference names + Node::Import { .. } | Node::ImportFrom { .. } => {} + Node::Pass | Node::Global { .. } | Node::Nonlocal { .. } | Node::Break { .. } | Node::Continue { .. } => {} + } +} + +/// Collects all names referenced in an expression. +/// Adds the transitive free-name references of a nested function definition +/// to `referenced`, after filtering out names that the nested function binds +/// for itself (params, body-assigned, and `global` declarations). +/// +/// Required for the [issue #477](https://github.com/pydantic/monty/issues/477) +/// fix: an outer scope must see the names that DEEPER nested scopes capture +/// from it, even when no statement in the outer body references them +/// directly. Without this, the intermediate "pass-through" scope is invisible +/// to scope analysis and the deepest closure misresolves the capture as a +/// global. +fn collect_nested_function_references( + signature: &ParsedSignature, + body: &[ParseNode], + referenced: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + // First collect everything the nested function references — this recurses + // into still-deeper FunctionDefs via the same path, so the transitive + // closure builds up bottom-up. + let mut nested_referenced: AHashSet = AHashSet::new(); + for n in body { + collect_referenced_names_from_node(n, &mut nested_referenced, interner); + } + + // Anything the nested function binds for itself does NOT propagate out. + // We treat `global X` the same way: the nested function explicitly + // routes X to module scope, so we don't want to capture X in this scope's + // cell variables. + let param_names: Vec = signature.param_names().collect(); + let nested_scope = collect_function_scope_info(body, ¶m_names, interner); + let nested_params: AHashSet = param_names.iter().copied().collect(); + for name in nested_referenced { + if nested_scope.assigned_names.contains(&name) + || nested_params.contains(&name) + || nested_scope.global_names.contains(&name) + { + continue; + } + referenced.insert(name); + } +} + +fn collect_referenced_names_from_expr( + expr: &ExprLoc, + referenced: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match &expr.expr { + Expr::Name(ident) => { + referenced.insert(ident.name_id); + } + Expr::Literal(_) => {} + Expr::Builtin(_) => {} + Expr::List(items) | Expr::Tuple(items) | Expr::Set(items) => { + for item in items { + let expr = match item { + SequenceItem::Value(e) | SequenceItem::Unpack(e) => e, + }; + collect_referenced_names_from_expr(expr, referenced, interner); + } + } + Expr::Dict(dict_items) => { + for item in dict_items { + match item { + DictItem::Pair(key, value) => { + collect_referenced_names_from_expr(key, referenced, interner); + collect_referenced_names_from_expr(value, referenced, interner); + } + DictItem::Unpack(e) => collect_referenced_names_from_expr(e, referenced, interner), + } + } + } + Expr::Op { left, right, .. } | Expr::CmpOp { left, right, .. } => { + collect_referenced_names_from_expr(left, referenced, interner); + collect_referenced_names_from_expr(right, referenced, interner); + } + Expr::ChainCmp { left, comparisons } => { + collect_referenced_names_from_expr(left, referenced, interner); + for (_, expr) in comparisons { + collect_referenced_names_from_expr(expr, referenced, interner); + } + } + Expr::Not(operand) | Expr::UnaryMinus(operand) | Expr::UnaryPlus(operand) | Expr::UnaryInvert(operand) => { + collect_referenced_names_from_expr(operand, referenced, interner); + } + Expr::FString(parts) => { + collect_referenced_names_from_fstring_parts(parts, referenced, interner); + } + Expr::Subscript { object, index } => { + collect_referenced_names_from_expr(object, referenced, interner); + collect_referenced_names_from_expr(index, referenced, interner); + } + Expr::Call { callable, args } => { + // Check if the callable is a Name reference + if let Callable::Name(ident) = callable { + referenced.insert(ident.name_id); + } + collect_referenced_names_from_args(args, referenced, interner); + } + Expr::AttrCall { object, args, .. } => { + collect_referenced_names_from_expr(object, referenced, interner); + collect_referenced_names_from_args(args, referenced, interner); + } + Expr::AttrGet { object, .. } => { + collect_referenced_names_from_expr(object, referenced, interner); + } + Expr::IndirectCall { callable, args } => { + // Collect references from the callable expression and arguments + collect_referenced_names_from_expr(callable, referenced, interner); + collect_referenced_names_from_args(args, referenced, interner); + } + Expr::IfElse { test, body, orelse } => { + collect_referenced_names_from_expr(test, referenced, interner); + collect_referenced_names_from_expr(body, referenced, interner); + collect_referenced_names_from_expr(orelse, referenced, interner); + } + Expr::ListComp { elt, generators, .. } | Expr::SetComp { elt, generators, .. } => { + collect_referenced_names_from_comprehension(generators, Some(elt), None, referenced, interner); + } + Expr::DictComp { + key, value, generators, .. + } => { + collect_referenced_names_from_comprehension(generators, None, Some((key, value)), referenced, interner); + } + Expr::LambdaRaw { signature, body, .. } => { + // Build set of parameter names (these are local to the lambda, not free variables) + let lambda_params: AHashSet = signature.param_names().collect(); + + // Collect references from the body expression into a temporary set + let mut body_refs: AHashSet = AHashSet::new(); + collect_referenced_names_from_expr(body, &mut body_refs, interner); + + // Filter out the lambda's own parameters before adding to referenced set. + // The lambda's parameters are bound by the lambda, not free from outer scope. + for name in body_refs { + if !lambda_params.contains(&name) { + referenced.insert(name); + } + } + + // Default value expressions are evaluated in the enclosing scope, not the lambda's + // scope, so they can reference outer scope without filtering. + for param in &signature.pos_args { + if let Some(ref default) = param.default { + collect_referenced_names_from_expr(default, referenced, interner); + } + } + for param in &signature.args { + if let Some(ref default) = param.default { + collect_referenced_names_from_expr(default, referenced, interner); + } + } + for param in &signature.kwargs { + if let Some(ref default) = param.default { + collect_referenced_names_from_expr(default, referenced, interner); + } + } + } + Expr::Lambda { .. } => { + // Lambda should only exist after preparation; this function operates on raw expressions + unreachable!("Expr::Lambda should not exist during scope analysis") + } + Expr::Named { value, .. } => { + // Only the value is referenced; target is being assigned, not read + collect_referenced_names_from_expr(value, referenced, interner); + } + Expr::Slice { lower, upper, step } => { + if let Some(expr) = lower { + collect_referenced_names_from_expr(expr, referenced, interner); + } + if let Some(expr) = upper { + collect_referenced_names_from_expr(expr, referenced, interner); + } + if let Some(expr) = step { + collect_referenced_names_from_expr(expr, referenced, interner); + } + } + Expr::Await(value) => { + collect_referenced_names_from_expr(value, referenced, interner); + } + } +} + +/// Collects referenced names from comprehension expressions. +/// +/// Handles the special scoping rules: loop variables are local to the comprehension, +/// so we collect references from iterators and conditions but exclude loop variable names. +fn collect_referenced_names_from_comprehension( + generators: &[Comprehension], + elt: Option<&ExprLoc>, + key_value: Option<(&ExprLoc, &ExprLoc)>, + referenced: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + // Track loop variable names (these are local to the comprehension) + let mut comp_locals: AHashSet = AHashSet::new(); + + // Collect references from expressions that can see prior loop variables. + // These need to be filtered against comp_locals before adding to referenced. + let mut inner_refs: AHashSet = AHashSet::new(); + + for (i, comp) in generators.iter().enumerate() { + if i == 0 { + // FIRST generator's iter expression truly references enclosing scope + // (evaluated before any loop variable is defined). + collect_referenced_names_from_expr(&comp.iter, referenced, interner); + } else { + // SUBSEQUENT generators' iter expressions can reference prior loop variables. + // For example, in `[y for x in xs for y in x]`, the `x` in the second + // generator's iter is the first generator's loop variable, not outer scope. + collect_referenced_names_from_expr(&comp.iter, &mut inner_refs, interner); + } + + // Add this generator's target(s) to local set + collect_names_from_unpack_target(&comp.target, &mut comp_locals, interner); + + // Filter conditions can see prior loop variables - collect separately + for cond in &comp.ifs { + collect_referenced_names_from_expr(cond, &mut inner_refs, interner); + } + } + + // Element expression(s) can see all loop variables - collect separately + if let Some(e) = elt { + collect_referenced_names_from_expr(e, &mut inner_refs, interner); + } + if let Some((k, v)) = key_value { + collect_referenced_names_from_expr(k, &mut inner_refs, interner); + collect_referenced_names_from_expr(v, &mut inner_refs, interner); + } + + // Add inner references that are NOT comprehension-locals to the outer referenced set. + // Names that ARE comp_locals refer to the comprehension's loop variable, not enclosing scope. + for name in inner_refs { + if !comp_locals.contains(&name) { + referenced.insert(name); + } + } +} + +/// Collects referenced names from argument expressions. +fn collect_referenced_names_from_args( + args: &ArgExprs, + referenced: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match args { + ArgExprs::Empty => {} + ArgExprs::One(e) => collect_referenced_names_from_expr(e, referenced, interner), + ArgExprs::Two(e1, e2) => { + collect_referenced_names_from_expr(e1, referenced, interner); + collect_referenced_names_from_expr(e2, referenced, interner); + } + ArgExprs::Args(exprs) => { + for e in exprs { + collect_referenced_names_from_expr(e, referenced, interner); + } + } + ArgExprs::Kwargs(kwargs) => { + for kwarg in kwargs { + collect_referenced_names_from_expr(&kwarg.value, referenced, interner); + } + } + ArgExprs::ArgsKargs { + args, + kwargs, + var_args, + var_kwargs, + } => { + if let Some(args) = args { + for e in args { + collect_referenced_names_from_expr(e, referenced, interner); + } + } + if let Some(kwargs) = kwargs { + for kwarg in kwargs { + collect_referenced_names_from_expr(&kwarg.value, referenced, interner); + } + } + if let Some(e) = var_args { + collect_referenced_names_from_expr(e, referenced, interner); + } + if let Some(e) = var_kwargs { + collect_referenced_names_from_expr(e, referenced, interner); + } + } + ArgExprs::GeneralizedCall { args, kwargs } => { + for arg in args { + match arg { + CallArg::Value(e) | CallArg::Unpack(e) => { + collect_referenced_names_from_expr(e, referenced, interner); + } + } + } + for kwarg in kwargs { + match kwarg { + CallKwarg::Named(kw) => { + collect_referenced_names_from_expr(&kw.value, referenced, interner); + } + CallKwarg::Unpack(e) => { + collect_referenced_names_from_expr(e, referenced, interner); + } + } + } + } + } +} + +/// Collects referenced names from f-string parts (both expressions and dynamic format specs). +fn collect_referenced_names_from_fstring_parts( + parts: &[FStringPart], + referenced: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + for part in parts { + if let FStringPart::Interpolation { expr, format_spec, .. } = part { + collect_referenced_names_from_expr(expr, referenced, interner); + // Also check dynamic format specs which can contain interpolated expressions + if let Some(FormatSpec::Dynamic(spec_parts)) = format_spec { + collect_referenced_names_from_fstring_parts(spec_parts, referenced, interner); + } + } + } +} + +/// Adds every name a pattern binds (`case x`, `*rest`, `**rest`, `as name`) to `names`. +fn collect_pattern_captures(pattern: &Pattern, names: &mut AHashSet) { + match pattern { + Pattern::Value(_) | Pattern::Singleton(_) => {} + Pattern::Sequence { patterns, .. } | Pattern::Or { patterns, .. } => { + for p in patterns { + collect_pattern_captures(p, names); + } + } + Pattern::Mapping { patterns, rest, .. } => { + for p in patterns { + collect_pattern_captures(p, names); + } + if let Some(rest) = rest { + names.insert(rest.name_id); + } + } + Pattern::Class { + patterns, kwd_patterns, .. + } => { + for p in patterns.iter().chain(kwd_patterns) { + collect_pattern_captures(p, names); + } + } + Pattern::Star { name, .. } => { + if let Some(name) = name { + names.insert(name.name_id); + } + } + Pattern::As { pattern, name, .. } => { + if let Some(inner) = pattern { + collect_pattern_captures(inner, names); + } + if let Some(name) = name { + names.insert(name.name_id); + } + } + } +} + +/// Calls `f` on every expression a pattern evaluates: value and singleton +/// constants, mapping keys and class names. Captures are not expressions. +fn for_each_pattern_expr(pattern: &Pattern, f: &mut impl FnMut(&ExprLoc)) { + match pattern { + Pattern::Value(expr) | Pattern::Singleton(expr) => f(expr), + Pattern::Sequence { patterns, .. } | Pattern::Or { patterns, .. } => { + for p in patterns { + for_each_pattern_expr(p, f); + } + } + Pattern::Mapping { keys, patterns, .. } => { + for key in keys { + f(key); + } + for p in patterns { + for_each_pattern_expr(p, f); + } + } + Pattern::Class { + cls, + patterns, + kwd_patterns, + .. + } => { + f(cls); + for p in patterns.iter().chain(kwd_patterns) { + for_each_pattern_expr(p, f); + } + } + Pattern::Star { .. } => {} + Pattern::As { pattern, .. } => { + if let Some(inner) = pattern { + for_each_pattern_expr(inner, f); + } + } + } +} + +/// Collects the names an unpack target binds into the given set. +/// +/// Recursively traverses nested tuples to find all identifier names. Attribute +/// and subscript targets bind no name; like their [`AssignTarget`] counterparts +/// they are scanned for walrus assignments instead. +fn collect_names_from_unpack_target( + target: &UnpackTarget, + names: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match target { + UnpackTarget::Name(ident) => { + names.insert(ident.name_id); + } + UnpackTarget::Starred(inner) => collect_names_from_unpack_target(inner, names, interner), + UnpackTarget::Tuple { targets, .. } => { + for t in targets { + collect_names_from_unpack_target(t, names, interner); + } + } + UnpackTarget::Attr { object, .. } => { + collect_assigned_names_from_expr(object, names, interner); + } + UnpackTarget::Subscript { container, index, .. } => { + collect_assigned_names_from_expr(container, names, interner); + collect_assigned_names_from_expr(index, names, interner); + } + } +} + +/// Collects names read by an unpack target's own expressions. +/// +/// Only attribute and subscript targets read anything: the object or container +/// must be evaluated at store time, so `obj.x, y = pair` references `obj`. +fn collect_referenced_names_from_unpack_target( + target: &UnpackTarget, + referenced: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match target { + UnpackTarget::Name(_) => {} + UnpackTarget::Starred(inner) => collect_referenced_names_from_unpack_target(inner, referenced, interner), + UnpackTarget::Tuple { targets, .. } => { + for t in targets { + collect_referenced_names_from_unpack_target(t, referenced, interner); + } + } + UnpackTarget::Attr { object, .. } => collect_referenced_names_from_expr(object, referenced, interner), + UnpackTarget::Subscript { container, index, .. } => { + collect_referenced_names_from_expr(container, referenced, interner); + collect_referenced_names_from_expr(index, referenced, interner); + } + } +} + +/// Collects cell vars captured by lambdas inside an unpack target's expressions. +fn collect_cell_vars_from_unpack_target( + target: &UnpackTarget, + our_locals: &AHashSet, + cell_vars: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match target { + UnpackTarget::Name(_) => {} + UnpackTarget::Starred(inner) => collect_cell_vars_from_unpack_target(inner, our_locals, cell_vars, interner), + UnpackTarget::Tuple { targets, .. } => { + for t in targets { + collect_cell_vars_from_unpack_target(t, our_locals, cell_vars, interner); + } + } + UnpackTarget::Attr { object, .. } => collect_cell_vars_from_expr(object, our_locals, cell_vars, interner), + UnpackTarget::Subscript { container, index, .. } => { + collect_cell_vars_from_expr(container, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(index, our_locals, cell_vars, interner); + } + } +} + +/// Collects newly-assigned names and walrus bindings introduced by a single chained-assign target. +/// +/// Mirrors the per-shape logic in `collect_scope_info_from_node` for the non-chained +/// assignment nodes: name/unpack targets bind new names, while subscript/attribute +/// targets only scan their sub-expressions for walrus bindings since they mutate an +/// existing container rather than introducing a new binding. +fn collect_assigned_names_from_assign_target( + target: &AssignTarget, + assigned_names: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match target { + AssignTarget::Name(ident) => { + assigned_names.insert(ident.name_id); + } + AssignTarget::Subscript { target, index, .. } => { + collect_assigned_names_from_expr(target, assigned_names, interner); + collect_assigned_names_from_expr(index, assigned_names, interner); + } + AssignTarget::Attr { object, .. } => { + collect_assigned_names_from_expr(object, assigned_names, interner); + } + AssignTarget::Unpack { targets, .. } => { + for t in targets { + collect_names_from_unpack_target(t, assigned_names, interner); + } + } + } +} + +/// Collects cell variables referenced by sub-expressions inside a chained-assign target. +/// +/// Subscript and attribute targets embed arbitrary expressions that may contain lambdas +/// capturing enclosing variables; pure name/unpack targets do not carry expressions and +/// therefore contribute nothing to the cell-variable set. +fn collect_cell_vars_from_assign_target( + target: &AssignTarget, + our_locals: &AHashSet, + cell_vars: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match target { + AssignTarget::Subscript { target, index, .. } => { + collect_cell_vars_from_expr(target, our_locals, cell_vars, interner); + collect_cell_vars_from_expr(index, our_locals, cell_vars, interner); + } + AssignTarget::Attr { object, .. } => { + collect_cell_vars_from_expr(object, our_locals, cell_vars, interner); + } + AssignTarget::Name(_) => {} + AssignTarget::Unpack { targets, .. } => { + for t in targets { + collect_cell_vars_from_unpack_target(t, our_locals, cell_vars, interner); + } + } + } +} + +/// Collects names referenced (read) by sub-expressions inside a chained-assign target. +/// +/// Only subscript and attribute targets read from surrounding state: the container or +/// object expression must be evaluated at store time. Name and unpack targets do not +/// reference any names on the read side. +fn collect_referenced_names_from_assign_target( + target: &AssignTarget, + referenced: &mut AHashSet, + interner: &CompileInterns<'_>, +) { + match target { + AssignTarget::Subscript { target, index, .. } => { + collect_referenced_names_from_expr(target, referenced, interner); + collect_referenced_names_from_expr(index, referenced, interner); + } + AssignTarget::Attr { object, .. } => { + collect_referenced_names_from_expr(object, referenced, interner); + } + AssignTarget::Name(_) => {} + AssignTarget::Unpack { targets, .. } => { + for t in targets { + collect_referenced_names_from_unpack_target(t, referenced, interner); + } + } + } +} diff --git a/crates/bashkit-monty/src/py_value.rs b/crates/bashkit-monty/src/py_value.rs new file mode 100644 index 000000000..c9b7aad72 --- /dev/null +++ b/crates/bashkit-monty/src/py_value.rs @@ -0,0 +1,582 @@ +//! Scoped Python values with storage differences hidden from operation dispatch. +//! +//! Arithmetic, method calls, subscription, containment, length, truth and repr use +//! this view. Unmigrated protocols still enter through `Value`; heap payloads are never copied. + +use std::{ + borrow::Cow, + fmt::{self, Write}, +}; + +use num_bigint::BigInt; + +use crate::{ + args::ArgValues, + builtins::{Builtins, BuiltinsFunctions}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult, SimpleException}, + fstring::FormatFloat, + heap::{DropWithContext, Heap, HeapData, HeapId, HeapObjectRead, HeapReadOutput}, + heap_data::{heap_payloads, heap_read_output_py_trait_forward}, + identity::Identity, + intern::{FunctionId, StaticStrings}, + modules::{ModuleFunctions, collections::defaultdict::defaultdict_missing}, + types::{ + GenericAlias, LazyHeapSet, LongInt, Property, PyTrait, Type, Union, allocate_string, + bytes::PyBytes, + long_int::{PyInt, arithmetic::float_binary}, + numeric::{round_digits, round_float}, + py_trait::PyObjectIdentity, + str::PyStr, + }, + value::{EitherStr, Marker, Value, float_divmod_tuple, float_pow_value, py_float_divmod, py_float_mod}, +}; + +/// Normalizes the three multi-representation types and keeps every other heap type flat. +macro_rules! define_py_value { + (@collect [$($variant:ident($payload:ty),)*]) => { + /// A scoped Python-type view retaining the original object's identity. + /// Drop it before releasing the owning `Value`, so no heap reader survives cleanup. + pub(crate) enum PyValue<'h> { + Str(PyStr<'h>), + Bytes(PyBytes<'h>), + Int(PyInt<'h>), + Undefined, + Ellipsis, + NotImplemented, + None, + Bool(bool), + Float(f64), + Builtin(Builtins), + ModuleFunction(ModuleFunctions), + DefFunction(FunctionId), + Marker(Marker), + Property(Property), + $($variant(HeapObjectRead<'h, $payload>),)* + } + + impl<'h> From> for PyValue<'h> { + fn from(value: HeapReadOutput<'h>) -> Self { + match value { + HeapReadOutput::Str(value) => Self::Str(PyStr::Heap(value)), + HeapReadOutput::Bytes(value) => Self::Bytes(PyBytes::Heap(value)), + HeapReadOutput::LongInt(value) => Self::Int(PyInt::Heap(value)), + $(HeapReadOutput::$variant(value) => Self::$variant(value),)* + } + } + } + + impl PyObjectIdentity for PyValue<'_> { + fn py_identity(&self) -> Identity { + match self { + Self::Str(value) => value.py_identity(), + Self::Bytes(value) => value.py_identity(), + Self::Int(value) => value.py_identity(), + Self::Undefined => Identity::Undefined, + Self::Ellipsis => Identity::Ellipsis, + Self::NotImplemented => Identity::NotImplemented, + Self::None => Identity::None, + Self::Bool(value) => Identity::Bool(*value), + Self::Float(value) => Identity::Float(value.to_bits()), + Self::Builtin(value) => Identity::Builtin(*value), + Self::ModuleFunction(value) => Identity::ModuleFunction(*value), + Self::DefFunction(id) => Identity::DefFunction(id.index()), + Self::Marker(value) => Identity::Marker(*value), + Self::Property(value) => Identity::Property(*value), + $(Self::$variant(value) => value.py_identity(),)* + } + } + } + + impl PyValue<'_> { + /// Identifies heap reprs needing cycle tracking; scalar views cannot contain cycles. + fn repr_heap_id(&self) -> Option { + match self { + Self::Str(_) | Self::Bytes(_) | Self::Int(_) + | Self::Undefined | Self::Ellipsis | Self::NotImplemented | Self::None + | Self::Bool(_) | Self::Float(_) | Self::Builtin(_) | Self::ModuleFunction(_) + | Self::DefFunction(_) | Self::Marker(_) | Self::Property(_) => None, + $(Self::$variant(value) => Some(value.id()),)* + } + } + } + }; + (@collect [$($out:tt)*] $(#[$meta:meta])* Str($storage:ident $payload:ty), $($rest:tt)*) => { + define_py_value!(@collect [$($out)*] $($rest)*); + }; + (@collect [$($out:tt)*] $(#[$meta:meta])* Bytes($storage:ident $payload:ty), $($rest:tt)*) => { + define_py_value!(@collect [$($out)*] $($rest)*); + }; + (@collect [$($out:tt)*] $(#[$meta:meta])* LongInt($storage:ident $payload:ty), $($rest:tt)*) => { + define_py_value!(@collect [$($out)*] $($rest)*); + }; + (@collect [$($out:tt)*] $(#[$meta:meta])* $variant:ident($storage:ident $payload:ty), $($rest:tt)*) => { + define_py_value!(@collect [$($out)* $variant($payload),] $($rest)*); + }; + ($($registry:tt)*) => { define_py_value!(@collect [] $($registry)*); }; +} +heap_payloads!(define_py_value); + +/// Combines concrete dispatch and custom arms in one match, allowing exhaustive protocols. +macro_rules! forward_py_value { + ($self:expr, |$value:ident| $body:expr, else $fallback:expr) => { + forward_py_value!($self, |$value| $body, { _ => $fallback, }) + }; + ($self:expr, |$value:ident| $body:expr, {$($custom:tt)*}) => { + heap_read_output_py_trait_forward!( + $self, |$value| $body, { + Self::Int($value) => $body, + $($custom)* + } + ) + }; +} + +/// Forwards numeric protocols while keeping bool promotion separate from its identity. +macro_rules! numeric_binary { + ($method:ident, $reflected:literal, |$lhs:ident, $rhs:ident, $vm:ident| $body:expr) => { + fn $method(&self, other: &Value, $vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.$method(other, $vm), { + Self::Bool(value) => PyInt::Small(i64::from(*value)).$method(other, $vm), + Self::Float(value) => float_binary(*value, other, $vm, $reflected, |$lhs, $rhs| $body), + _ => Ok(None), + }) + } + }; + ($method:ident) => { + fn $method(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.$method(other, vm), { + Self::Bool(value) => PyInt::Small(i64::from(*value)).$method(other, vm), + _ => Ok(None), + }) + } + }; +} + +impl<'h> PyValue<'h> { + /// Includes the mutating `defaultdict.__missing__` path outside `PyTrait`. + pub(crate) fn subscript(self, key: &Value, vm: &mut VM<'h>) -> RunResult { + match self { + Self::Dict(mut dict) if dict.get(vm.heap).is_defaultdict() => match dict.dict_get(key, vm)? { + Some(value) => Ok(value), + None => defaultdict_missing(&mut dict, key, vm), + }, + value => value.py_getitem(key, vm), + } + } + + /// Formats the payload after the caller has handled repr recursion. + fn repr_inner(&self, f: &mut impl Write, vm: &mut VM<'h>, heap_ids: &mut LazyHeapSet) -> RunResult<()> { + forward_py_value!(self, |value| value.py_repr_fmt(f, vm, heap_ids), { + Self::Undefined => Ok(f.write_str("Undefined")?), + Self::Ellipsis => Ok(f.write_str("Ellipsis")?), + Self::NotImplemented => Ok(f.write_str("NotImplemented")?), + Self::None => Ok(f.write_str("None")?), + Self::Bool(true) => Ok(f.write_str("True")?), + Self::Bool(false) => Ok(f.write_str("False")?), + Self::Float(value) => Ok(write!(f, "{}", FormatFloat(*value))?), + Self::Builtin(value) => Ok(value.py_repr_fmt(f)?), + Self::ModuleFunction(function) => { + let py_id = self.py_identity().into_value(vm.heap); + defer_drop!(py_id, vm); + Ok(function.py_repr_fmt(f, PythonIdDisplay::new(py_id, vm.heap))?) + } + Self::DefFunction(id) => { + let py_id = self.py_identity().into_value(vm.heap); + defer_drop!(py_id, vm); + Ok(vm.interns + .get_function(*id) + .py_repr_fmt(f, vm.interns, PythonIdDisplay::new(py_id, vm.heap))?) + } + Self::Marker(value) => Ok(value.py_repr_fmt(f)?), + Self::Property(value) => Ok(write!(f, "")?), + Self::Cell(cell) => Ok(write!(f, "", cell.get(vm.heap).0.py_type_name(vm))?), + Self::Exception(e) => Ok(e.get(vm.heap).py_repr_fmt(f)?), + Self::Module(m) => Ok(write!(f, "", m.get(vm.heap).name_str(vm.interns))?), + Self::Coroutine(coro) => { + let func = vm.interns.get_function(coro.get(vm.heap).func_id); + Ok(write!(f, "", vm.interns.get_str(func.name.name_id))?) + } + Self::GatherFuture(gather) => Ok(write!(f, "", gather.get(vm.heap).item_count())?), + Self::ExternalFuture(fut) => Ok(write!(f, "", fut.get(vm.heap).call_id.raw())?), + }) + } +} + +impl<'h> PyTrait<'h> for PyValue<'h> { + fn py_type(&self, vm: &VM<'h>) -> Type { + forward_py_value!(self, |value| value.py_type(vm), { + Self::Undefined => panic!("Cannot get type of undefined value"), + Self::Ellipsis => Type::Ellipsis, + Self::NotImplemented => Type::NotImplementedType, + Self::None => Type::NoneType, + Self::Bool(_) => Type::Bool, + Self::Float(_) => Type::Float, + Self::Builtin(value) => value.py_type(), + Self::ModuleFunction(_) => Type::BuiltinFunction, + Self::DefFunction(_) => Type::Function, + Self::Marker(value) => value.py_type(), + Self::Property(_) => Type::Property, + Self::Cell(_) => Type::Cell, + Self::Exception(e) => e.py_type(vm), + Self::Module(_) => Type::Module, + Self::Coroutine(_) | Self::GatherFuture(_) | Self::ExternalFuture(_) => Type::Coroutine, + }) + } + + fn py_type_name(&self, vm: &VM<'h>) -> Cow<'h, str> { + forward_py_value!(self, |value| value.py_type_name(vm), else self.py_type(vm).name(vm.heap, vm.interns)) + } + + fn py_len(&self, vm: &VM<'h>) -> Option { + forward_py_value!(self, |value| value.py_len(vm), else None) + } + + fn py_bool(&self, vm: &mut VM<'h>) -> RunResult { + forward_py_value!(self, |value| value.py_bool(vm), { + Self::NotImplemented => Err(SimpleException::new_msg( + ExcType::TypeError, "NotImplemented should not be used in a boolean context", + ).into()), + Self::Undefined | Self::None => Ok(false), + Self::Bool(value) => Ok(*value), + Self::Float(value) => Ok(*value != 0.0), + _ => Ok(true), + }) + } + + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, heap_ids: &mut LazyHeapSet) -> RunResult<()> { + if let Some(id) = self.repr_heap_id() { + if heap_ids.contains(&id) { + Ok(f.write_str(match self { + Self::List(_) | Self::Deque(_) => "[...]", + Self::Tuple(_) => "(...)", + Self::Dict(_) => "{...}", + _ => "...", + })?) + } else if matches!(self, Self::Instance(_)) { + // Dataclass reprs track cycles; user __repr__ recurses until the VM's guard raises. + self.repr_inner(f, vm, heap_ids) + } else { + heap_ids.insert(id); + let result = self.repr_inner(f, vm, heap_ids); + heap_ids.remove(&id); + result + } + } else { + self.repr_inner(f, vm, heap_ids) + } + } + + fn py_str(&self, vm: &mut VM<'h>) -> RunResult { + forward_py_value!(self, |value| value.py_str(vm), { + Self::Exception(value) => Ok(allocate_string(value.get(vm.heap).py_str(), vm.heap)), + _ => self.py_repr(vm), + }) + } + + fn py_contains_impl(&self, item: &Value, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_contains_impl(item, vm), else Ok(None)) + } + + fn py_eq_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_eq_impl(other, vm), { + Self::Undefined => Value::Undefined.py_eq_impl(other, vm), + Self::Ellipsis => Value::Ellipsis.py_eq_impl(other, vm), + Self::NotImplemented => Value::NotImplemented.py_eq_impl(other, vm), + Self::None => Value::None.py_eq_impl(other, vm), + Self::Bool(value) => Value::Bool(*value).py_eq_impl(other, vm), + Self::Float(value) => Value::Float(*value).py_eq_impl(other, vm), + Self::Builtin(value) => Value::Builtin(*value).py_eq_impl(other, vm), + Self::ModuleFunction(value) => Value::ModuleFunction(*value).py_eq_impl(other, vm), + Self::DefFunction(id) => Value::DefFunction(*id).py_eq_impl(other, vm), + Self::Marker(value) => Value::Marker(*value).py_eq_impl(other, vm), + Self::Property(value) => Value::Property(*value).py_eq_impl(other, vm), + _ => Ok(None), + }) + } + + fn py_add_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_add_impl(other, vm), { + Self::Bool(value) => PyInt::Small(i64::from(*value)).py_add_impl(other, vm), + Self::Float(lhs) => Ok(match other { + Value::Int(rhs) => Some(Value::Float(lhs + *rhs as f64)), + Value::Bool(rhs) => Some(Value::Float(lhs + f64::from(*rhs))), + Value::Float(rhs) => Some(Value::Float(lhs + rhs)), + _ => None, + }), + _ => Ok(None), + }) + } + + fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_mul_impl(other, vm), { + Self::Bool(value) => PyInt::Small(i64::from(*value)).py_mul_impl(other, vm), + Self::Float(lhs) => Ok(match other { + Value::Int(rhs) => Some(Value::Float(lhs * *rhs as f64)), + Value::Bool(rhs) => Some(Value::Float(lhs * f64::from(*rhs))), + Value::Float(rhs) => Some(Value::Float(lhs * rhs)), + _ => None, + }), + _ => Ok(None), + }) + } + + fn py_radd_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_radd_impl(other, vm), else Ok(None)) + } + + fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_rmul_impl(other, vm), else Ok(None)) + } + + numeric_binary!(py_sub_impl, false, |lhs, rhs, vm| Ok(Value::Float(lhs - rhs))); + numeric_binary!(py_rsub_impl, true, |lhs, rhs, vm| Ok(Value::Float(lhs - rhs))); + numeric_binary!(py_truediv_impl, false, |lhs, rhs, vm| { + if rhs == 0.0 { + Err(ExcType::zero_division().into()) + } else { + Ok(Value::Float(lhs / rhs)) + } + }); + numeric_binary!(py_rtruediv_impl, true, |lhs, rhs, vm| { + if rhs == 0.0 { + Err(ExcType::zero_division().into()) + } else { + Ok(Value::Float(lhs / rhs)) + } + }); + numeric_binary!(py_floordiv_impl, false, |lhs, rhs, vm| { + if rhs == 0.0 { + Err(ExcType::zero_division().into()) + } else { + Ok(Value::Float(py_float_divmod(lhs, rhs).0)) + } + }); + numeric_binary!(py_rfloordiv_impl, true, |lhs, rhs, vm| { + if rhs == 0.0 { + Err(ExcType::zero_division().into()) + } else { + Ok(Value::Float(py_float_divmod(lhs, rhs).0)) + } + }); + numeric_binary!(py_mod_impl, false, |lhs, rhs, vm| { + if rhs == 0.0 { + Err(ExcType::zero_division().into()) + } else { + Ok(Value::Float(py_float_mod(lhs, rhs))) + } + }); + numeric_binary!(py_rmod_impl, true, |lhs, rhs, vm| { + if rhs == 0.0 { + Err(ExcType::zero_division().into()) + } else { + Ok(Value::Float(py_float_mod(lhs, rhs))) + } + }); + numeric_binary!(py_divmod_impl, false, |lhs, rhs, vm| float_divmod_tuple( + lhs, rhs, vm.heap + )); + numeric_binary!(py_rdivmod_impl, true, |lhs, rhs, vm| float_divmod_tuple( + lhs, rhs, vm.heap + )); + numeric_binary!(py_rand_impl); + numeric_binary!(py_rxor_impl); + numeric_binary!(py_lshift_impl); + numeric_binary!(py_rlshift_impl); + numeric_binary!(py_rshift_impl); + numeric_binary!(py_rrshift_impl); + + fn py_index_impl(&self, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_index_impl(vm), { + Self::Bool(value) => Ok(Some(Value::Int(i64::from(*value)))), + _ => Ok(None), + }) + } + + fn py_neg_impl(&self, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_neg_impl(vm), { + Self::Bool(value) => PyInt::Small(i64::from(*value)).py_neg_impl(vm), + Self::Float(value) => Ok(Some(Value::Float(-value))), + _ => Ok(None), + }) + } + + fn py_abs_impl(&self, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_abs_impl(vm), { + Self::Bool(value) => Ok(Some(Value::Int(i64::from(*value)))), + Self::Float(value) => Ok(Some(Value::Float(value.abs()))), + _ => Ok(None), + }) + } + + fn py_invert_impl(&self, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_invert_impl(vm), { + Self::Bool(value) => Ok(Some(Value::Int(!i64::from(*value)))), + _ => Ok(None), + }) + } + + fn py_round_impl(&self, ndigits: Option<&Value>, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_round_impl(ndigits, vm), { + Self::Bool(value) => PyInt::Small(i64::from(*value)).py_round_impl(ndigits, vm), + Self::Float(value) => { + let digits = round_digits(ndigits, vm)?; + round_float(*value, digits, vm.heap).map(Some) + } + _ => Ok(None), + }) + } + + fn py_int_impl(&self, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_int_impl(vm), { + Self::Bool(value) => Ok(Some(Value::Int(i64::from(*value)))), + Self::Float(value) => LongInt::value_from_f64(*value, vm.heap).map(Some), + _ => Ok(None), + }) + } + + fn py_float_impl(&self, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_float_impl(vm), { + Self::Bool(value) => Ok(Some(f64::from(*value))), + Self::Float(value) => Ok(Some(*value)), + _ => Ok(None), + }) + } + + fn py_floor_impl(&self, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_floor_impl(vm), { + Self::Bool(value) => Ok(Some(Value::Int(i64::from(*value)))), + Self::Float(value) => LongInt::value_from_f64(value.floor(), vm.heap).map(Some), + _ => Ok(None), + }) + } + + fn py_ceil_impl(&self, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_ceil_impl(vm), { + Self::Bool(value) => Ok(Some(Value::Int(i64::from(*value)))), + Self::Float(value) => LongInt::value_from_f64(value.ceil(), vm.heap).map(Some), + _ => Ok(None), + }) + } + + fn py_trunc_impl(&self, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_trunc_impl(vm), { + Self::Bool(value) => Ok(Some(Value::Int(i64::from(*value)))), + Self::Float(value) => LongInt::value_from_f64(*value, vm.heap).map(Some), + _ => Ok(None), + }) + } + + fn py_pos_impl(&self, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_pos_impl(vm), { + Self::Bool(value) => Ok(Some(Value::Int(i64::from(*value)))), + Self::Float(value) => Ok(Some(Value::Float(*value))), + _ => Ok(None), + }) + } + + fn py_pow_impl(&self, other: &Value, modulus: Option<&Value>, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_pow_impl(other, modulus, vm), { + Self::Bool(value) => PyInt::Small(i64::from(*value)).py_pow_impl(other, modulus, vm), + Self::Float(_) if modulus.is_some() => Err(ExcType::type_error_pow_modulo()), + Self::Float(value) => float_binary(*value, other, vm, false, |base, exp| float_pow_value(base, exp, vm.heap)), + _ => Ok(None), + }) + } + + fn py_rpow_impl(&self, other: &Value, modulus: Option<&Value>, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_rpow_impl(other, modulus, vm), { + Self::Float(_) if modulus.is_some() => Err(ExcType::type_error_pow_modulo()), + _ => Ok(None), + }) + } + + fn py_and_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_and_impl(other, vm), { + Self::Bool(lhs) if let Value::Bool(rhs) = other => Ok(Some(Value::Bool(*lhs && *rhs))), + Self::Bool(value) => PyInt::Small(i64::from(*value)).py_and_impl(other, vm), + _ => Ok(None), + }) + } + + fn py_or_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_or_impl(other, vm), { + Self::Bool(lhs) if let Value::Bool(rhs) = other => Ok(Some(Value::Bool(*lhs || *rhs))), + Self::Bool(value) => PyInt::Small(i64::from(*value)).py_or_impl(other, vm), + Self::Builtin(value) => Union::try_or(&Value::Builtin(*value), other, vm), + Self::None => Union::try_or(&Value::None, other, vm), + Self::Marker(value) => Union::try_or(&Value::Marker(*value), other, vm), + _ => Ok(None), + }) + } + + fn py_ror_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_ror_impl(other, vm), { + Self::Builtin(value) => Union::try_or(other, &Value::Builtin(*value), vm), + Self::None => Union::try_or(other, &Value::None, vm), + Self::Marker(value) => Union::try_or(other, &Value::Marker(*value), vm), + _ => Ok(None), + }) + } + + fn py_xor_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + forward_py_value!(self, |value| value.py_xor_impl(other, vm), { + Self::Bool(lhs) if let Value::Bool(rhs) = other => Ok(Some(Value::Bool(*lhs ^ *rhs))), + Self::Bool(value) => PyInt::Small(i64::from(*value)).py_xor_impl(other, vm), + _ => Ok(None), + }) + } + + fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { + forward_py_value!(self, |value| value.py_call_attr(vm, attr, args), { + Self::Module(value) => value.py_call_attr(vm, attr, args), + Self::Builtin(Builtins::Type(ty)) if let EitherStr::Interned(id) = attr => ty.call_class_method(*id, args, vm), + _ => { + args.drop_with(vm); + Err(ExcType::attribute_error(self.py_type_name(vm), attr.as_str(vm.interns))) + } + }) + } + + fn py_getitem(&self, key: &Value, vm: &mut VM<'h>) -> RunResult { + forward_py_value!(self, |value| value.py_getitem(key, vm), { + Self::Builtin(Builtins::Type(t)) if t.has_class_getitem() => Ok(GenericAlias::subscript(*t, key.clone_with_heap(vm), vm)), + Self::Builtin(Builtins::Function(BuiltinsFunctions::Type)) => Ok(GenericAlias::subscript(Type::Type, key.clone_with_heap(vm), vm)), + Self::Builtin(Builtins::Type(Type::Union)) => Union::subscript(key.clone_with_heap(vm), vm), + Self::Marker(Marker(StaticStrings::Optional)) => Union::optional(key.clone_with_heap(vm), vm), + Self::Builtin(Builtins::Type(t)) => Err(ExcType::type_error_type_not_subscriptable(&t.name(vm.heap, vm.interns))), + Self::Builtin(Builtins::ExcType(exc_type)) => Err(ExcType::type_error_type_not_subscriptable((*exc_type).into())), + _ => Err(ExcType::type_error_not_sub(&self.py_type_name(vm))), + }) + } +} + +/// Borrowed integer payload used to format a Python `id()` in callable reprs. +enum PythonIdDisplay<'a> { + Int(i64), + LongInt(&'a BigInt), +} + +impl<'a> PythonIdDisplay<'a> { + /// Extracts the integer payload returned by the structural identity encoder. + fn new(value: &'a Value, heap: &'a Heap) -> Self { + match value { + Value::Int(value) => Self::Int(*value), + Value::Ref(id) => match heap.get(*id) { + HeapData::LongInt(value) => Self::LongInt(value.inner()), + _ => unreachable!("identity values are integers"), + }, + _ => unreachable!("identity values are integers"), + } + } +} + +impl fmt::LowerHex for PythonIdDisplay<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Int(value) => fmt::LowerHex::fmt(value, f), + Self::LongInt(value) => fmt::LowerHex::fmt(value, f), + } + } +} diff --git a/crates/bashkit-monty/src/repl.rs b/crates/bashkit-monty/src/repl.rs new file mode 100644 index 000000000..4a615c5e8 --- /dev/null +++ b/crates/bashkit-monty/src/repl.rs @@ -0,0 +1,1550 @@ +//! Stateful REPL execution support for Monty. +//! +//! This module implements incremental snippet execution where each new snippet +//! is compiled and executed against persistent heap/namespace state without +//! replaying previously executed snippets. +//! +//! The session's compiler tables (`NameMap`, `Interns`) are append-only and are +//! *moved* into each snippet's `Executor` and back via `commit_executor`, never +//! cloned, so the cost of a feed depends on the snippet, not on how much the +//! session has already run. + +use std::{mem, sync::Arc}; + +use ahash::AHashMap; +use monty_types::{ + CallArgs, ExcType, MontyException, MontyObject, MontyUuid, NamedValues, OsFunctionCall, OsPolicy, PrintWriter, + ResourceTracker, SOURCE_SCAN_THRESHOLD, SourceRange, + unstable::{self, MontyGraph, NodeId}, +}; +use ruff_python_ast::token::TokenKind; +use ruff_python_parser::{InterpolatedStringErrorType, LexicalErrorType, ParseErrorType, parse_module}; + +use crate::{ + args::{ArgValues, KwargsValues}, + bytecode::{FrameExit, VM, VMSnapshot}, + defer_drop, + exception_private::{ExcTypeExt, RunError}, + heap::{DropWithContext, Heap, HeapData, HeapReader}, + intern::Interns, + name_map::NameMap, + object_bridge::{MontyGraphExt, MontyObjectExt}, + parse::source_nesting_exception, + run::{CompileOptions, DEFAULT_CWD, Executor, Program, ReplSession, SessionTables}, + run_progress::{ + ConvertedExit, ExtFunctionResult, LookupAnswer, LookupScope, NameLookupResult, convert_frame_exit, + resume_lookup, resume_with_result, + }, + source_nesting::source_within_nesting_bound, + types::{SessionRandom, tuple::allocate_tuple}, + value::Value, + virtual_path::canonical_cwd, +}; + +/// Stateful REPL session that executes snippets incrementally without replay. +/// +/// [`MontyRepl`] preserves heap and global variable state between snippets. +/// Each [`feed_run`](Self::feed_run) or [`feed_start`](Self::feed_start) call compiles and executes only the new snippet against the current +/// state, avoiding the cost and semantic risks of replaying prior code. +/// Deserialization requires trusted, unmodified state; see [`crate::Dump::load`]. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct MontyRepl { + /// Script name used for runtime error messages and REPL identification, + /// and what `__file__` places under the working directory a snippet starts in. + /// + /// Incremental `feed()` / `start()` snippets intentionally use internal script names + /// like `` to match CPython's interactive traceback style. + script_name: Arc, + /// Counter for generated `` execution filenames. + next_input_id: u64, + /// Stable mapping of global variable names to namespace slot IDs. + /// + /// Moved into each snippet's `Executor` rather than cloned (see + /// [`commit_executor`](Self::commit_executor)); empty while a snippet is in + /// flight or suspended, when the executor's copy is authoritative. + global_names: NameMap, + /// Persistent intern table across snippets so intern/function IDs remain valid. + /// + /// Same ownership hand-off as `global_names`. + interns: Interns, + /// Source text of every snippet that has been fed, keyed by its + /// generated script name (``). + /// + /// Required because a traceback raised in snippet N can include frames + /// from functions defined in snippet M < N. Those frames carry + /// `CodeRange` byte offsets that index into snippet M's source, so the + /// diagnostic pass must be able to look that source up by filename — + /// the current snippet's `Executor.code` is not sufficient. + sources: AHashMap>, + /// [`CompileOptions`] applied to every snippet fed to this session, fixed + /// at construction so all snippets compile consistently. + options: CompileOptions, + /// OS-call policies shared with each snippet's executor. + /// See [`with_os_policy`](Self::with_os_policy). + os_policy: Arc, + /// Sandbox working directory the next snippet starts in: what + /// [`set_cwd`](Self::set_cwd) chose, then whatever `os.chdir` left the + /// last snippet in — the directory is session state, like the globals. + cwd: Arc, + /// The session's `random` state, carried between snippets like the + /// globals so a `random.seed()` in one feed governs the draws of the next. + random: SessionRandom, + /// Persistent heap across snippets. + heap: Heap, + /// Persistent global variable values across snippets. + /// + /// Indexed by `NamespaceId` slots from `global_names`. Between snippet + /// executions these are the only VM values that persist — stack and frames + /// are transient. + globals: Vec, +} + +impl MontyRepl { + /// The session heap and interns, for a dump upgrade of an idle session. + pub(crate) fn heap_and_interns(&mut self) -> (&mut Heap, &Interns) { + (&mut self.heap, &self.interns) + } + + /// Creates an empty REPL session with no code parsed or executed. + /// + /// All code execution is driven through [`feed_run`](Self::feed_run) or [`feed_start`](Self::feed_start). This separates + /// construction from execution, matching the pattern used by [`MontyRun::new`](crate::MontyRun::new). + /// The [`CompileOptions`] apply to every snippet fed to the session. + #[must_use] + pub fn new(script_name: &str, resource_tracker: ResourceTracker, options: CompileOptions) -> Self { + let heap = Heap::new(0, resource_tracker); + + Self { + script_name: Arc::from(script_name), + next_input_id: 0, + global_names: NameMap::new(), + interns: Interns::default(), + sources: AHashMap::new(), + options, + os_policy: Arc::new(OsPolicy::default()), + cwd: Arc::from(DEFAULT_CWD), + random: SessionRandom::default(), + heap, + globals: Vec::new(), + } + } + + /// The [`CompileOptions`] every snippet fed to this session compiles with. + #[must_use] + pub fn options(&self) -> CompileOptions { + self.options + } + + /// Rejects a snippet whose nesting would let the parser grow its stack past + /// the limit, with the `SyntaxError` compiling it would raise. + /// + /// For hosts that want the verdict before doing other work on the snippet + /// (the worker type-checks after it); the returned [`CheckedSource`] lets + /// [`feed_start_checked`](Self::feed_start_checked) skip the scan. Plain + /// feeds scan for themselves (see `limitations/language.md`). + /// + /// # Errors + /// The `SyntaxError: Source is too deeply nested` located in the snippet. + pub fn check_source<'a>(&self, code: &'a str) -> Result, MontyException> { + source_nesting_exception(code, &self.script_name, self.options.source_scan_threshold)?; + Ok(CheckedSource(code)) + } + + /// Replaces the default clock, sleep and random initialization policies + /// on every path, including [`feed_start`](Self::feed_start). See + /// [`MontyRun::with_os_policy`](crate::MontyRun::with_os_policy). + #[must_use] + pub fn with_os_policy(mut self, os_policy: OsPolicy) -> Self { + self.os_policy = Arc::new(os_policy); + self + } + + /// Switches the sandbox working directory (initially `/`). + /// + /// `cwd` is an absolute POSIX virtual path, normalized here like + /// [`MontyRun::set_cwd`](crate::MontyRun::set_cwd): `os.getcwd()` reports + /// it and relative paths in `open()` / `os` / `pathlib` calls resolve + /// against it before reaching the host. The directory then persists across + /// snippets, including a snippet's `os.chdir`, until the host switches it + /// again. + pub fn set_cwd(&mut self, cwd: &str) { + self.cwd = canonical_cwd(cwd); + } + + /// Returns the resource tracker that will be used for the next snippet. + /// + /// This is primarily intended for host integrations that need to attach + /// per-execution state, such as cancellation markers, to an existing REPL. + pub fn tracker(&self) -> &ResourceTracker { + &self.heap.tracker + } + + /// Returns mutable access to the resource tracker for the next snippet. + /// + /// REPL hosts use this to install ephemeral execution controls, such as + /// async cancellation flags, before calling [`feed_start`](Self::feed_start). + pub fn tracker_mut(&mut self) -> &mut ResourceTracker { + &mut self.heap.tracker + } + + /// Number of live heap entries (excluding the empty-tuple singleton) — + /// `ref-count-return`-only introspection for GC tests. + #[cfg(feature = "ref-count-return")] + #[must_use] + pub fn heap_entry_count(&self) -> usize { + self.heap.entry_count() + } + + /// Starts executing a new snippet and returns suspendable REPL progress. + /// + /// This is the REPL equivalent of [`MontyRun::start`](crate::MontyRun::start): execution may complete, + /// suspend at external calls / OS calls / unresolved futures, or raise a Python + /// exception. Resume with the returned state object and eventually recover the + /// updated REPL from [`ReplProgress::into_complete`]. + /// + /// Unlike [`MontyRepl::feed_run`], this method consumes `self` so runtime state can be + /// safely moved into snapshot objects for serialization and cross-process resume. + /// + /// On a Python-level runtime exception the REPL is **not** destroyed: it is + /// returned inside [`ReplStartError`] so the caller can continue feeding + /// subsequent snippets against the same heap and namespace state. + /// + /// The snippet is scanned for nesting first; [`feed_start_checked`](Self::feed_start_checked) + /// takes one [`check_source`](Self::check_source) already vetted. + /// + /// # Errors + /// Returns a boxed [`ReplStartError`] for syntax, compile-time, or runtime + /// failures — the REPL session is always preserved inside the error. + pub fn feed_start( + self, + code: &str, + inputs: impl Into, + print: PrintWriter<'_>, + ) -> Result> { + match self.check_source(code) { + Ok(checked_code) => self.feed_start_checked(checked_code, inputs, print), + Err(error) => Err(Box::new(ReplStartError { repl: self, error })), + } + } + + /// [`feed_start`](Self::feed_start) for a snippet [`check_source`](Self::check_source) + /// already vetted, so the scan is not repeated. + /// + /// # Errors + /// As [`feed_start`](Self::feed_start). + pub fn feed_start_checked( + self, + code: CheckedSource<'_>, + inputs: impl Into, + print: PrintWriter<'_>, + ) -> Result> { + let code = code.0; + let mut this = self; + if code.is_empty() { + return Ok(ReplProgress::Complete { + repl: this, + value: MontyObject::none(), + }); + } + + let (input_values, names) = unstable::into_named_values_parts(inputs.into()); + let (input_names, input_ids): (Vec<_>, Vec<_>) = names.into_iter().unzip(); + + let input_script_name = this.next_input_script_name(); + // Preserve this snippet's source (see `feed_run` for rationale). + let code: Arc = Arc::from(code); + this.sources.insert(input_script_name.clone(), Arc::clone(&code)); + let session = ReplSession { + script_name: &this.script_name, + cwd: &this.cwd, + os_policy: &this.os_policy, + }; + let mut executor = match Executor::new_repl_snippet( + code, + &input_script_name, + &mut this.global_names, + &mut this.interns, + &input_names, + this.options, + session, + ) { + Ok(exec) => exec, + Err(error) => return Err(Box::new(ReplStartError { repl: this, error })), + }; + + this.ensure_globals_size(executor.namespace_size()); + + this.heap.tracker.on_feed_start(); + match HeapReader::with( + &mut this.heap, + &mut (&mut executor, print), + |reader, (executor, print)| { + let mut vm = VM::new( + mem::take(&mut this.globals), + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + + vm.random = mem::take(&mut this.random); + + // Inject inputs with VM alive + if let Err(error) = inject_inputs_into_vm(&executor.program, input_values, &input_ids, &mut vm) { + reclaim_vm_state(&mut this.globals, &mut this.cwd, &mut this.random, &mut vm); + return Err(error); + } + + let vm_result = vm.run_external(); + + // Convert while VM alive, then snapshot or reclaim globals + let converted = convert_frame_exit(vm_result, &mut vm); + let vm_state = if converted.needs_snapshot() { + Some(vm.snapshot()) + } else { + reclaim_vm_state(&mut this.globals, &mut this.cwd, &mut this.random, &mut vm); + None + }; + Ok((converted, vm_state)) + }, + ) { + Ok((converted, vm_state)) => build_repl_progress(converted, vm_state, executor, this), + Err(error) => { + this.commit_executor(executor); + Err(Box::new(ReplStartError { repl: this, error })) + } + } + } + + /// Feeds and executes a new snippet against the current REPL state to completion. + /// + /// This compiles only `code` using the existing global slot map, extends the + /// global namespace if new names are introduced, and executes the snippet once. + /// Previously executed snippets are never replayed. If execution raises after + /// partially mutating globals, those mutations remain visible in later feeds, + /// matching Python REPL semantics. + /// + /// The snippet is scanned for nesting first. + /// + /// # Errors + /// Returns [`MontyException`] for syntax/compile/runtime failures. + pub fn feed_run( + &mut self, + code: &str, + inputs: impl Into, + print: PrintWriter<'_>, + ) -> Result { + if code.is_empty() { + return Ok(MontyObject::none()); + } + source_nesting_exception(code, &self.script_name, self.options.source_scan_threshold)?; + + let (input_values, names) = unstable::into_named_values_parts(inputs.into()); + let (input_names, input_ids): (Vec<_>, Vec<_>) = names.into_iter().unzip(); + + let input_script_name = self.next_input_script_name(); + // Preserve this snippet's source before anything can fail, so later + // tracebacks with frames from this snippet can still resolve line/ + // column/preview information — `Executor.code` only survives until + // the next feed. The one copy of the text is shared with the executor. + let code: Arc = Arc::from(code); + self.sources.insert(input_script_name.clone(), Arc::clone(&code)); + let session = ReplSession { + script_name: &self.script_name, + cwd: &self.cwd, + os_policy: &self.os_policy, + }; + let mut executor = Executor::new_repl_snippet( + code, + &input_script_name, + &mut self.global_names, + &mut self.interns, + &input_names, + self.options, + session, + )?; + + self.ensure_globals_size(executor.namespace_size()); + + self.heap.tracker.on_feed_start(); + let result = HeapReader::with( + &mut self.heap, + &mut (&mut executor, print), + |reader, (executor, print)| { + let mut vm = VM::new( + mem::take(&mut self.globals), + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + + vm.random = mem::take(&mut self.random); + + if let Err(e) = inject_inputs_into_vm(&executor.program, input_values, &input_ids, &mut vm) { + reclaim_vm_state(&mut self.globals, &mut self.cwd, &mut self.random, &mut vm); + return Err(e); + } + + let result = Program::run_to_completion(&mut vm); + + // Reclaim globals (and any directory change or seed) before cleanup. + reclaim_vm_state(&mut self.globals, &mut self.cwd, &mut self.random, &mut vm); + Ok(result) + }, + ); + + // Commit compiler metadata even on runtime errors. + // Snippets can mutate globals before raising, and those values may contain + // FunctionId/StringId values that must be interpreted with the updated tables. + self.commit_executor(executor); + + // Resolve every traceback frame against the source of the snippet that + // produced it — frames from earlier snippets live in `self.sources`. + result?.map_err(|e| { + e.into_python_exception(&self.interns, |fname| self.sources.get(fname).map(|source| &**source)) + }) + } + + /// Calls a Python function defined in the session by name. + /// + /// Looks up the function, then executes a synthetic `` + /// call expression so failures include a visible host call site. + /// + /// # Errors + /// Returns [`MontyException`] if the function is not found, not callable, + /// raises an exception, or encounters an external function call. + pub fn call_function( + &mut self, + name: &str, + args: impl Into, + print: PrintWriter<'_>, + ) -> Result { + let args: CallArgs = args.into(); + // The synthetic call site is `name(*args)`: keyword arguments have + // no slot, so they are refused rather than silently dropped. + if args.kwargs().len() != 0 { + return Err(ExcType::type_error("call_function() takes positional arguments only") + .into_python_exception(&self.interns, |fname| self.sources.get(fname).map(|source| &**source))); + } + let Some(name_id) = self.interns.get_string_id_by_name(name) else { + return Err(RunError::from(ExcType::name_error(name)) + .into_python_exception(&self.interns, |fname| self.sources.get(fname).map(|source| &**source))); + }; + let Some(slot_idx) = self.global_names.get(name_id) else { + return Err(RunError::from(ExcType::name_error(name)) + .into_python_exception(&self.interns, |fname| self.sources.get(fname).map(|source| &**source))); + }; + if matches!(self.globals.get(slot_idx.index()), None | Some(Value::Undefined)) { + return Err(RunError::from(ExcType::name_error(name)) + .into_python_exception(&self.interns, |fname| self.sources.get(fname).map(|source| &**source))); + } + + let input_script_name = self.next_input_script_name(); + // The name map is cloned (it is small) so a failed setup leaves the + // session's intact; both it and the interns come back after the call. + let mut executor = Executor::new_repl_function_call( + name, + name_id, + slot_idx, + args.args().len(), + &input_script_name, + self.global_names.clone(), + &mut self.interns, + self.options, + ReplSession { + script_name: &self.script_name, + cwd: &self.cwd, + os_policy: &self.os_policy, + }, + )?; + self.sources.insert(input_script_name, executor.program.code.clone()); + + self.ensure_globals_size(executor.namespace_size()); + // A host-driven call is its own unit of work, so it opens a fresh feed. + self.heap.tracker.on_feed_start(); + let result = HeapReader::with( + &mut self.heap, + &mut (&mut executor, print), + |reader, (executor, print)| { + let vm = &mut VM::new( + mem::take(&mut self.globals), + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + + vm.random = mem::take(&mut self.random); + let result = match convert_args(args, vm) { + Ok(args) => { + let (args, kwargs) = args.into_parts(); + debug_assert!(kwargs.is_empty(), "host function calls only have positional arguments"); + kwargs.drop_with(vm); + let args_tuple = allocate_tuple(args.collect(), vm.heap); + let args_slot = executor.program.input_slots[0].index(); + let old = mem::replace(&mut vm.globals[args_slot], args_tuple); + old.drop_with(vm); + + let mut run_result = vm.run_external(); + loop { + run_result = match run_result { + Ok(FrameExit::Return(value)) => break Ok(MontyObject::export(value, vm)), + // No host answers inside a host-driven call, so the + // lookup is `Undefined`: `hasattr()` is False, + // `getattr()` yields its default. + Ok(FrameExit::AttrLookup { + effect: Some(effect), .. + }) => { + let value = effect.apply(None, vm); + vm.push(value); + vm.run_external() + } + Ok(exit) => { + let error = vm.unsupported_frame_exit(exit); + vm.resume_with_exception(error) + } + Err(error) => { + break Err(error.into_python_exception(vm.interns, |fname| { + self.sources.get(fname).map(|source| &**source) + })); + } + }; + } + } + Err(error) => Err(error), + }; + + // The call may have bound new globals (`exec()` in the function), + // so the whole namespace is kept; only the argument tuple goes. + let mut globals = vm.take_globals(); + let args_slot = executor.program.input_slots[0].index(); + mem::replace(&mut globals[args_slot], Value::Undefined).drop_with(vm); + self.random = mem::take(&mut vm.random); + self.globals = globals; + if let Some(cwd) = vm.take_changed_cwd() { + self.cwd = Arc::from(cwd); + } + result + }, + ); + self.global_names = executor.tables.global_names; + self.interns = executor.tables.interns; + result + } + + /// Returns a list of all callable function names defined in the session. + /// + /// Includes functions, closures, and functions with default arguments. + /// Does not include builtins or external functions. + #[must_use] + pub fn function_names(&self) -> Vec<&str> { + self.global_names + .iter() + .filter_map(|(ns_id, name_id)| { + let idx = ns_id.index(); + if idx < self.globals.len() && is_callable(&self.globals[idx], &self.heap) { + Some(self.interns.get_str(name_id)) + } else { + None + } + }) + .collect() + } + + /// Returns whether a function with the given name exists in the session. + #[must_use] + pub fn has_function(&self, name: &str) -> bool { + let Some(name_id) = self.interns.get_string_id_by_name(name) else { + return false; + }; + self.global_names.get(name_id).is_some_and(|ns_id| { + let idx = ns_id.index(); + idx < self.globals.len() && is_callable(&self.globals[idx], &self.heap) + }) + } + + /// Takes the session's compiler tables back from a finished snippet's executor. + /// + /// [`Executor::new_repl_snippet`] moves `global_names` and `interns` into the + /// executor instead of cloning them, so this must run on *every* path that + /// is done with an executor — success, runtime error, or abandoning a + /// suspended snippet. Skipping it would leave the session with empty + /// tables while globals still hold `FunctionId`/`StringId` values from + /// the snippet. + fn commit_executor(&mut self, executor: Executor) { + let SessionTables { global_names, interns } = executor.tables; + self.global_names = global_names; + self.interns = interns; + } + + /// Grows the globals vector to at least `size` slots. + /// + /// Newly introduced slots are initialized to `Undefined` to keep slot alignment + /// with the compiler's global-name map. + fn ensure_globals_size(&mut self, size: usize) { + if self.globals.len() < size { + self.globals.resize_with(size, || Value::Undefined); + } + } + + /// The filename the next snippet will run as, which a host can name in a + /// [`SourceRange`] it reports ahead of that snippet. + /// + /// CPython labels interactive inputs as ``. Snippets and + /// host function calls share this sequence so every traceback call site + /// can be correlated with the session's execution history. + #[must_use] + pub fn next_script_name(&self) -> String { + format!("", self.next_input_id) + } + + /// Takes the next interactive execution's filename; see [`Self::next_script_name`]. + fn next_input_script_name(&mut self) -> String { + let name = self.next_script_name(); + self.next_input_id += 1; + name + } +} + +/// A snippet [`MontyRepl::check_source`] found within the nesting bound, +/// which [`MontyRepl::feed_start_checked`] therefore need not scan again. +/// +/// The verdict used the checking REPL's `source_scan_threshold`, so feed it +/// to that REPL (or one configured alike), as the worker does. +#[derive(Debug, Clone, Copy)] +pub struct CheckedSource<'a>(&'a str); + +impl<'a> CheckedSource<'a> { + /// The checked snippet, for the type checker and import scan that run before the feed. + #[must_use] + pub fn code(&self) -> &'a str { + self.0 + } +} + +impl Drop for MontyRepl { + fn drop(&mut self) { + self.globals.drain(..).drop_with(&mut self.heap); + } +} + +// --------------------------------------------------------------------------- +// ReplProgress and per-variant structs +// --------------------------------------------------------------------------- + +/// Result of a single suspendable REPL snippet execution. +/// +/// This mirrors [`RunProgress`](crate::RunProgress) but returns the updated [`MontyRepl`] on completion +/// so callers can continue feeding additional snippets without replaying prior code. +/// Each variant (except [`Complete`](Self::Complete)) wraps a dedicated struct with only the relevant +/// resume methods. Deserialization requires trusted, unmodified state; see [`crate::Dump::load`]. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub enum ReplProgress { + /// Execution paused at an external function call or dataclass method call. + FunctionCall(ReplFunctionCall), + /// Execution paused for an OS-level operation. + OsCall(ReplOsCall), + /// All async tasks are blocked waiting for external futures to resolve. + ResolveFutures(ReplResolveFutures), + /// Execution paused for an unresolved name lookup. + NameLookup(ReplNameLookup), + /// Snippet execution completed with the updated REPL and result value. + Complete { + /// Updated REPL session state to continue feeding snippets. + repl: MontyRepl, + /// Final result produced by the snippet. + value: MontyObject, + }, +} + +/// Error returned when a REPL snippet raises a Python exception during [`feed_start`](MontyRepl::feed_start) or a `resume()`. +/// +/// Unlike syntax/compile errors which consume the REPL, runtime errors preserve +/// the full session state so the caller can inspect the error and continue feeding +/// subsequent snippets. Any global mutations that occurred before the exception +/// remain visible in the returned `repl`. +#[derive(Debug)] +pub struct ReplStartError { + /// REPL session state after the failed snippet — ready for further use. + pub repl: MontyRepl, + /// The Python exception that was raised. + pub error: MontyException, +} + +impl ReplProgress { + /// The session heap and the interns its values refer to, for a dump upgrade. + /// While a snippet is in flight the executor holds the session's interns. + pub(crate) fn heap_and_interns(&mut self) -> (&mut Heap, &Interns) { + match self { + Self::FunctionCall(ReplFunctionCall { snapshot, .. }) + | Self::OsCall(ReplOsCall { snapshot, .. }) + | Self::NameLookup(ReplNameLookup { snapshot, .. }) => { + (&mut snapshot.repl.heap, &snapshot.executor.tables.interns) + } + Self::ResolveFutures(ReplResolveFutures { repl, executor, .. }) => { + (&mut repl.heap, &executor.tables.interns) + } + Self::Complete { repl, .. } => repl.heap_and_interns(), + } + } + + /// Consumes the progress and returns the [`ReplFunctionCall`] struct. + #[must_use] + pub fn into_function_call(self) -> Option { + match self { + Self::FunctionCall(call) => Some(call), + _ => None, + } + } + + /// Consumes the progress and returns the [`ReplResolveFutures`] struct. + #[must_use] + pub fn into_resolve_futures(self) -> Option { + match self { + Self::ResolveFutures(state) => Some(state), + _ => None, + } + } + + /// Consumes the progress and returns the [`ReplNameLookup`] struct. + #[must_use] + pub fn into_name_lookup(self) -> Option { + match self { + Self::NameLookup(lookup) => Some(lookup), + _ => None, + } + } + + /// Consumes the progress and returns the completed REPL and value. + #[must_use] + pub fn into_complete(self) -> Option<(MontyRepl, MontyObject)> { + match self { + Self::Complete { repl, value } => Some((repl, value)), + _ => None, + } + } + + /// Extracts the REPL session from any progress variant, discarding + /// the in-flight execution state. + /// + /// Use this to recover the REPL when you need to abandon the current + /// snippet (e.g. because [`feed_run`](MontyRepl::feed_run) doesn't support async futures). + /// The REPL state reflects any mutations that occurred before the + /// snapshot was taken. + #[must_use] + pub fn into_repl(self) -> MontyRepl { + match self { + Self::FunctionCall(call) => call.into_repl(), + Self::OsCall(call) => call.into_repl(), + Self::ResolveFutures(state) => state.into_repl(), + Self::NameLookup(lookup) => lookup.into_repl(), + Self::Complete { repl, .. } => repl, + } + } + + /// Returns the session's resource tracker, whatever the progress state. + /// + /// Lets hosts read resource accounting — e.g. cumulative execution time + /// to report as telemetry — at any suspension point without consuming the + /// progress. + pub fn tracker(&self) -> &ResourceTracker { + match self { + Self::FunctionCall(call) => call.snapshot.repl.tracker(), + Self::OsCall(call) => call.snapshot.repl.tracker(), + Self::ResolveFutures(state) => state.repl.tracker(), + Self::NameLookup(lookup) => lookup.snapshot.repl.tracker(), + Self::Complete { repl, .. } => repl.tracker(), + } + } + + /// Returns the mutable tracker so hosts can tighten restored limits before resuming execution. + pub fn tracker_mut(&mut self) -> &mut ResourceTracker { + match self { + Self::FunctionCall(call) => call.snapshot.repl.tracker_mut(), + Self::OsCall(call) => call.snapshot.repl.tracker_mut(), + Self::ResolveFutures(state) => state.repl.tracker_mut(), + Self::NameLookup(lookup) => lookup.snapshot.repl.tracker_mut(), + Self::Complete { repl, .. } => repl.tracker_mut(), + } + } +} + +// --------------------------------------------------------------------------- +// ReplFunctionCall +// --------------------------------------------------------------------------- + +/// REPL execution paused at an external function call or host-class method call. +/// +/// Resume with [`resume`](Self::resume) to provide the return value and continue, +/// or [`resume_pending`](Self::resume_pending) to push an `ExternalFuture` for async resolution. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct ReplFunctionCall { + /// The name of the function or method being called. + pub function_name: String, + /// The arguments: one arena holding every positional and keyword value. + pub args: CallArgs, + /// Unique identifier for this call (used for async correlation). + pub call_id: u32, + /// Uuid of the routed receiver — an instance, or a class type (a + /// classmethod call, or construction spelled `__call__`); `None` for + /// plain external function calls. The receiver is NOT included in `args`. + pub object_id: Option, + /// The host may await a coroutine and answer with [`Self::resume_eager`]. + pub allow_eager_await: bool, + /// Where the call expression is in the source. + pub position: SourceRange, + /// Internal REPL execution snapshot. + snapshot: ReplSnapshot, +} + +impl ReplFunctionCall { + /// Extracts the REPL session, discarding the in-flight execution state. + /// + /// Restores globals from the VM snapshot so the REPL remains usable. + #[must_use] + pub fn into_repl(self) -> MontyRepl { + self.snapshot.into_repl() + } + + /// Resumes snippet execution with an external result. + pub fn resume( + self, + result: impl Into, + print: PrintWriter<'_>, + ) -> Result> { + self.snapshot.run(result.into(), print) + } + + /// Resumes execution by pushing an `ExternalFuture` for async resolution. + /// + /// Uses `self.call_id` internally — no need to pass it again. + pub fn resume_pending(self, print: PrintWriter<'_>) -> Result> { + self.snapshot.run(ExtFunctionResult::Future(self.call_id), print) + } + + /// Resumes with a settled coroutine, preserving its awaitable value and exception timing. + /// Only use when [`Self::allow_eager_await`] is true; synchronous returns use [`Self::resume`]. + pub fn resume_eager( + self, + result: Result, + print: PrintWriter<'_>, + ) -> Result> { + self.snapshot.run_inner( + result.map_or_else(ExtFunctionResult::Error, ExtFunctionResult::Return), + Some(self.call_id), + print, + ) + } + + /// Aborts the snippet with an uncatchable exception; see [`ReplOsCall::abort`]. + pub fn abort(self, exc: MontyException, print: PrintWriter<'_>) -> Result> { + self.snapshot.abort(exc, print) + } +} + +// --------------------------------------------------------------------------- +// ReplOsCall +// --------------------------------------------------------------------------- + +/// REPL execution paused for an OS-level operation. +/// +/// Resume with `resume(result, print)` to provide the OS call result and continue. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct ReplOsCall { + /// Typed OS-call dispatch value (variant + args). + pub function_call: OsFunctionCall, + /// Unique identifier for this call (used for async correlation). + pub call_id: u32, + /// The host may await its wait and answer with [`Self::resume_eager`]; + /// see [`OsCall::allow_eager_await`](crate::OsCall::allow_eager_await). + pub allow_eager_await: bool, + /// Where the call expression is in the source. + pub position: SourceRange, + /// Internal REPL execution snapshot. + snapshot: ReplSnapshot, +} + +impl ReplOsCall { + /// Extracts the REPL session, discarding the in-flight execution state. + /// + /// Restores globals from the VM snapshot so the REPL remains usable. + #[must_use] + pub fn into_repl(self) -> MontyRepl { + self.snapshot.into_repl() + } + + /// Resumes snippet execution with the OS call result. + pub fn resume( + self, + result: impl Into, + print: PrintWriter<'_>, + ) -> Result> { + self.snapshot.run(result.into(), print) + } + + /// REPL mirror of [`crate::OsCall::resume_with`] — dispatches the call + /// to `handler` (which receives the [`OsFunctionCall`] by value, so + /// write payloads move without cloning) and resumes with its result. + pub fn resume_with( + self, + print: PrintWriter<'_>, + handler: impl FnOnce(OsFunctionCall) -> ExtFunctionResult, + ) -> Result> { + let result = handler(self.function_call); + self.snapshot.run(result, print) + } + + /// Raises `exc` uncatchably at the suspended call. + /// + /// Resumes with the wait already performed; see + /// [`OsCall::resume_eager`](crate::OsCall::resume_eager). Only use when + /// [`Self::allow_eager_await`] is true. + pub fn resume_eager( + self, + result: Result, + print: PrintWriter<'_>, + ) -> Result> { + self.snapshot.run_inner( + result.map_or_else(ExtFunctionResult::Error, ExtFunctionResult::Return), + Some(self.call_id), + print, + ) + } + + /// Always returns `Err` with a reusable session; see [`crate::OsCall::abort`]. + pub fn abort(self, exc: MontyException, print: PrintWriter<'_>) -> Result> { + self.snapshot.abort(exc, print) + } +} + +// --------------------------------------------------------------------------- +// ReplNameLookup +// --------------------------------------------------------------------------- + +/// REPL execution paused for an unresolved name lookup, or — when +/// [`object_id`](Self::object_id) is set — a lazy attribute lookup on a +/// host-backed object (a class instance or class type). +/// +/// The host should check if the name corresponds to a known external function, +/// value, or instance attribute. Call [`resume`](Self::resume) with the +/// appropriate [`NameLookupResult`]. The namespace slot and scope are managed +/// internally. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct ReplNameLookup { + /// The name being looked up. + pub name: String, + /// Where the name (or attribute access) is in the source. + pub position: SourceRange, + /// Where the resolved value lands (namespace slot or host attribute). + scope: LookupScope, + /// Internal REPL execution snapshot. + snapshot: ReplSnapshot, +} + +impl ReplNameLookup { + /// Extracts the REPL session, discarding the in-flight execution state. + /// + /// Restores globals from the VM snapshot so the REPL remains usable. + #[must_use] + pub fn into_repl(self) -> MontyRepl { + self.snapshot.into_repl() + } + + /// Identity of the receiver for a lazy attribute lookup; `None` for a + /// plain global/local name lookup. + #[must_use] + pub fn object_id(&self) -> Option { + self.scope.object_id() + } + + /// Aborts the snippet with an uncatchable exception; see [`ReplOsCall::abort`]. + pub fn abort(self, exc: MontyException, print: PrintWriter<'_>) -> Result> { + self.snapshot.abort(exc, print) + } + + /// Resumes execution after name resolution. + /// + /// For a plain lookup, caches the resolved value in the namespace slot and + /// `Undefined` raises `NameError`; for a host attribute lookup (instance + /// or class type) the value is pushed uncached and `Undefined` raises + /// `AttributeError`. `Error` raises the host's exception in the sandbox, + /// bypassing any `hasattr()` / `getattr()` default. + pub fn resume(self, result: NameLookupResult, print: PrintWriter<'_>) -> Result> { + let Self { + name, scope, snapshot, .. + } = self; + + let ReplSnapshot { + mut repl, + mut executor, + vm_state, + } = snapshot; + + repl.heap.tracker.on_turn_start(); + let (converted, vm_state) = HeapReader::with( + &mut repl.heap, + &mut (&mut executor, print), + |reader, (executor, print)| { + // Restore the VM first, then convert inside its lifetime + let mut vm = VM::restore( + vm_state, + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + + // Resolve the name lookup result with the VM alive + let answer = LookupAnswer::new(result, &mut vm); + let effect = vm.pending_lookup_effect.take(); + let vm_result = resume_lookup(&mut vm, answer, effect, &scope, &name); + + // Convert while VM alive, then snapshot or reclaim globals + let converted = convert_frame_exit(vm_result, &mut vm); + let vm_state = if converted.needs_snapshot() { + Some(vm.snapshot()) + } else { + reclaim_vm_state(&mut repl.globals, &mut repl.cwd, &mut repl.random, &mut vm); + None + }; + (converted, vm_state) + }, + ); + build_repl_progress(converted, vm_state, executor, repl) + } +} + +// --------------------------------------------------------------------------- +// ReplResolveFutures +// --------------------------------------------------------------------------- + +/// REPL execution state blocked on unresolved external futures. +/// +/// This is the REPL-aware counterpart to [`ResolveFutures`](crate::ResolveFutures). +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct ReplResolveFutures { + /// Persistent REPL session state while this snippet is suspended. + repl: MontyRepl, + /// Compiled snippet and intern/function tables for this execution. + executor: Executor, + /// VM stack/frame state at suspension. + vm_state: VMSnapshot, + /// Pending call IDs expected by this snapshot. + pending_call_ids: Vec, + /// Where the main task's blocked `await` is in the source. + position: SourceRange, +} + +impl ReplResolveFutures { + /// Extracts the REPL session, restoring globals from the suspended VM state. + /// + /// As with the other REPL snapshot types, globals live inside the VM + /// snapshot while execution is suspended. Recovering the REPL for a + /// cancelled or abandoned async snippet must put those globals back so + /// previously defined REPL bindings remain available, and releases the + /// suspended tasks and stack so nothing leaks into the session heap. + /// The compiler tables are committed too: the abandoned snippet may have + /// rebound a global to a function or literal only they can resolve. + #[must_use] + pub fn into_repl(self) -> MontyRepl { + let Self { + mut repl, + executor, + vm_state, + .. + } = self; + let (globals, cwd, random) = vm_state.abandon(&mut repl.heap); + repl.globals = globals; + repl.cwd = Arc::from(cwd); + repl.random = random; + repl.commit_executor(executor); + repl + } + + /// Returns unresolved call IDs for this suspended state. + #[must_use] + pub fn pending_call_ids(&self) -> &[u32] { + &self.pending_call_ids + } + + /// Returns where the main task's blocked `await` is in the source. + #[must_use] + pub fn position(&self) -> &SourceRange { + &self.position + } + + /// Aborts with an uncatchable exception and abandons pending futures. + pub fn abort(self, exc: MontyException, print: PrintWriter<'_>) -> Result> { + let Self { + repl, + executor, + vm_state, + .. + } = self; + abort_restored(repl, executor, vm_state, exc, print) + } + + /// Resumes snippet execution with zero or more resolved futures. + /// + /// Supports incremental resolution: callers can provide only a subset of + /// pending call IDs and continue resolving over multiple resumes. + /// + /// All errors — including API misuse (unknown `call_id`) and Python-level + /// runtime failures — are returned as a boxed [`ReplStartError`] so the REPL + /// session is always preserved. + pub fn resume( + self, + results: Vec<(u32, ExtFunctionResult)>, + print: PrintWriter<'_>, + ) -> Result> { + let Self { + mut repl, + mut executor, + vm_state, + pending_call_ids, + .. + } = self; + + let invalid_call_id = results + .iter() + .find(|(call_id, _)| !pending_call_ids.contains(call_id)) + .map(|(call_id, _)| *call_id); + + repl.heap.tracker.on_turn_start(); + match HeapReader::with( + &mut repl.heap, + &mut (&mut executor, print), + |reader, (executor, print)| { + let mut vm = VM::restore( + vm_state, + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + + if let Some(call_id) = invalid_call_id { + reclaim_vm_state(&mut repl.globals, &mut repl.cwd, &mut repl.random, &mut vm); + return Err(MontyException::runtime_error(format!( + "unknown call_id {call_id}, expected one of: {pending_call_ids:?}" + ))); + } + + let vm_result = vm.resume_with_resolved_futures(results); + + // Convert while VM alive, then snapshot or reclaim globals + let converted = convert_frame_exit(vm_result, &mut vm); + let vm_state = if converted.needs_snapshot() { + Some(vm.snapshot()) + } else { + reclaim_vm_state(&mut repl.globals, &mut repl.cwd, &mut repl.random, &mut vm); + None + }; + Ok((converted, vm_state)) + }, + ) { + Ok((converted, vm_state)) => build_repl_progress(converted, vm_state, executor, repl), + Err(error) => { + repl.commit_executor(executor); + Err(Box::new(ReplStartError { repl, error })) + } + } + } +} + +// --------------------------------------------------------------------------- +// ReplContinuationMode — public utility for interactive input collection +// --------------------------------------------------------------------------- + +/// Parse-derived continuation state for interactive REPL input collection. +/// +/// `monty-runtime` uses this to decide whether to execute the buffered snippet +/// immediately, keep collecting continuation lines, or require a terminating +/// blank line for block statements (`if:`, `def:`, etc.). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReplContinuationMode { + /// The current snippet is syntactically complete and can run now. + Complete, + /// The snippet is incomplete and needs more continuation lines. + IncompleteImplicit, + /// The snippet opened an indented block and should wait for a trailing blank + /// line before execution, matching CPython interactive behavior. + IncompleteBlock, +} + +/// Detects whether REPL source is complete or needs more input. +/// +/// This mirrors CPython's broad interactive behavior: +/// - Incomplete bracketed / parenthesized / triple-quoted constructs continue. +/// - Decorators continue until their class or function definition arrives. +/// - Clause headers (`if:`, `def:`, etc.) require an indented body and then a +/// terminating blank line before execution. +/// - All other parse outcomes are treated as complete (either valid code or a +/// syntax error that should be shown immediately). +#[must_use] +pub fn detect_repl_continuation_mode(source: &str) -> ReplContinuationMode { + // Complete because feeding it raises the SyntaxError; parsing it here would grow the stack unguarded. + if !source_within_nesting_bound(source, SOURCE_SCAN_THRESHOLD) { + return ReplContinuationMode::Complete; + } + let Err(error) = parse_module(source) else { + return ReplContinuationMode::Complete; + }; + let error_is_at_end = error.location.is_empty() && error.location.start().to_usize() == source.len(); + let error_source = source + .get(error.location.start().to_usize()..error.location.end().to_usize()) + .unwrap_or_default(); + + match error.error { + ParseErrorType::OtherError(msg) => { + if msg.starts_with("Expected an indented block after ") { + ReplContinuationMode::IncompleteBlock + } else if msg == "Expected class, function definition or async function definition after decorator" + && error_is_at_end + { + ReplContinuationMode::IncompleteImplicit + } else { + ReplContinuationMode::Complete + } + } + ParseErrorType::Lexical( + LexicalErrorType::Eof + | LexicalErrorType::FStringError(InterpolatedStringErrorType::UnterminatedTripleQuotedString) + | LexicalErrorType::TStringError(InterpolatedStringErrorType::UnterminatedTripleQuotedString), + ) + | ParseErrorType::ExpectedToken { + found: TokenKind::EndOfFile, + .. + } + | ParseErrorType::FStringError(InterpolatedStringErrorType::UnterminatedTripleQuotedString) + | ParseErrorType::TStringError(InterpolatedStringErrorType::UnterminatedTripleQuotedString) => { + ReplContinuationMode::IncompleteImplicit + } + ParseErrorType::Lexical(LexicalErrorType::UnclosedStringError) if starts_with_triple_quote(error_source) => { + ReplContinuationMode::IncompleteImplicit + } + _ => ReplContinuationMode::Complete, + } +} + +fn starts_with_triple_quote(source: &str) -> bool { + // Ruff uses `UnclosedStringError` for both single- and triple-quoted plain + // strings. Its error range starts at the optional prefix, so the first + // quote distinguishes the forms without treating `"unfinished` as input + // that should continue. + let bytes = source.as_bytes(); + bytes + .iter() + .position(|byte| matches!(byte, b'\'' | b'"')) + .is_some_and(|quote_start| matches!(bytes.get(quote_start..quote_start + 3), Some(b"'''" | b"\"\"\""))) +} + +// --------------------------------------------------------------------------- +// ReplSnapshot — internal execution state for suspend/resume +// --------------------------------------------------------------------------- + +/// Restores the REPL VM and aborts uncatchably, preserving its globals. +/// +/// Any armed OS effect is rolled back. +fn abort_restored( + mut repl: MontyRepl, + mut executor: Executor, + vm_state: VMSnapshot, + exc: MontyException, + print: PrintWriter<'_>, +) -> Result> { + repl.heap.tracker.on_turn_start(); + let converted = HeapReader::with( + &mut repl.heap, + &mut (&mut executor, print), + |reader, (executor, print)| { + let mut vm = VM::restore( + vm_state, + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + let vm_result = vm.abort(exc); + let converted = convert_frame_exit(vm_result, &mut vm); + // Uncatchable exceptions cannot suspend, so no snapshot is needed. + reclaim_vm_state(&mut repl.globals, &mut repl.cwd, &mut repl.random, &mut vm); + converted + }, + ); + build_repl_progress(converted, None, executor, repl) +} + +/// REPL execution state that can resume after suspension. +/// +/// This is the internal REPL-aware counterpart to `Snapshot`. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct ReplSnapshot { + /// Persistent REPL session state while this snippet is suspended. + repl: MontyRepl, + /// Compiled snippet and intern/function tables for this execution. + executor: Executor, + /// VM stack/frame state at suspension. + vm_state: VMSnapshot, +} + +impl ReplSnapshot { + /// Raises `exc` uncatchably at the suspension point. + fn abort(self, exc: MontyException, print: PrintWriter<'_>) -> Result> { + let Self { + repl, + executor, + vm_state, + } = self; + abort_restored(repl, executor, vm_state, exc, print) + } + + /// Extracts the REPL session, restoring globals and the working directory + /// from the VM snapshot. + /// + /// When a snapshot is taken, globals live inside the `VMSnapshot`; the rest + /// of the in-flight state is released so the abandoned snippet leaks nothing + /// into the session heap. The compiler tables are committed because the + /// restored globals may reference ids the abandoned snippet appended. + fn into_repl(self) -> MontyRepl { + let Self { + mut repl, + executor, + vm_state, + } = self; + let (globals, cwd, random) = vm_state.abandon(&mut repl.heap); + repl.globals = globals; + repl.cwd = Arc::from(cwd); + repl.random = random; + repl.commit_executor(executor); + repl + } + + /// Continues snippet execution with an external result. + fn run( + self, + result: impl Into, + print: PrintWriter<'_>, + ) -> Result> { + self.run_inner(result.into(), None, print) + } + + /// Shared body of [`Self::run`] and [`ReplFunctionCall::resume_eager`]; + /// `eager_call_id` is set only for the latter. + fn run_inner( + self, + ext_result: ExtFunctionResult, + eager_call_id: Option, + print: PrintWriter<'_>, + ) -> Result> { + let Self { + mut repl, + mut executor, + vm_state, + } = self; + + repl.heap.tracker.on_turn_start(); + let (converted, vm_state) = HeapReader::with( + &mut repl.heap, + &mut (&mut executor, print), + |reader, (executor, print)| { + let mut vm = VM::restore( + vm_state, + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + + let vm_result = resume_with_result(&mut vm, ext_result, eager_call_id); + + // Convert while VM alive, then snapshot or reclaim globals + let converted = convert_frame_exit(vm_result, &mut vm); + let vm_state = if converted.needs_snapshot() { + Some(vm.snapshot()) + } else { + reclaim_vm_state(&mut repl.globals, &mut repl.cwd, &mut repl.random, &mut vm); + None + }; + (converted, vm_state) + }, + ); + build_repl_progress(converted, vm_state, executor, repl) + } +} + +// --------------------------------------------------------------------------- +// Private helper functions +// --------------------------------------------------------------------------- + +/// Reclaims what outlives a snippet from its finished VM: the globals, the +/// `random` generator, and the working directory when the snippet (or the +/// snapshot it resumed from) owns one, so an `os.chdir` or a `random.seed()` +/// persists into later feeds like the globals do. +fn reclaim_vm_state(globals: &mut Vec, cwd: &mut Arc, random: &mut SessionRandom, vm: &mut VM<'_>) { + *globals = vm.take_globals(); + if let Some(changed) = vm.take_changed_cwd() { + *cwd = Arc::from(changed); + } + *random = mem::take(&mut vm.random); +} + +/// Injects input values into the VM's global namespace slots. +/// +/// Imports the inputs' shared arena while the VM is alive, then stores each +/// input at the namespace slot that `Executor::new_repl_snippet` pre-resolved +/// for its name (`input_ids` are in that order). Each store is O(1) — the +/// per-input name → slot lookup happens once at snippet construction, not +/// here on the call path. +fn inject_inputs_into_vm( + program: &Program, + input_values: MontyGraph, + input_ids: &[NodeId], + vm: &mut VM<'_>, +) -> Result<(), MontyException> { + let values = input_values + .to_values(vm) + .map_err(|e| MontyException::runtime_error(format!("invalid input type: {e}")))?; + defer_drop!(values, vm); + for (&slot, id) in program.input_slots.iter().zip(input_ids) { + let value = values[id.index()].clone_with_heap(vm.heap); + let old = mem::replace(&mut vm.globals[slot.index()], value); + old.drop_with(vm); + } + Ok(()) +} + +/// Assembles a `ReplProgress` from already-converted data. +/// +/// This is the REPL equivalent of `build_run_progress`. On completion/error, +/// compiler metadata is committed to the REPL so subsequent snippets see +/// updated intern tables and name maps. +fn build_repl_progress( + converted: ConvertedExit, + vm_state: Option, + executor: Executor, + mut repl: MontyRepl, +) -> Result> { + macro_rules! new_repl_snapshot { + () => { + ReplSnapshot { + repl, + executor, + vm_state: vm_state.expect("snapshot should exist"), + } + }; + } + + match converted { + ConvertedExit::Complete(obj) => { + repl.commit_executor(executor); + Ok(ReplProgress::Complete { repl, value: obj }) + } + ConvertedExit::FunctionCall { + function_name, + args, + call_id, + object_id, + allow_eager_await, + position, + } => Ok(ReplProgress::FunctionCall(ReplFunctionCall { + function_name, + args, + call_id, + object_id, + allow_eager_await, + position, + snapshot: new_repl_snapshot!(), + })), + ConvertedExit::OsCall { + function_call, + call_id, + allow_eager_await, + position, + } => Ok(ReplProgress::OsCall(ReplOsCall { + function_call, + call_id, + allow_eager_await, + position, + snapshot: new_repl_snapshot!(), + })), + ConvertedExit::ResolveFutures { + pending_call_ids, + position, + } => Ok(ReplProgress::ResolveFutures(ReplResolveFutures { + repl, + executor, + vm_state: vm_state.expect("snapshot should exist for ResolveFutures"), + pending_call_ids, + position, + })), + ConvertedExit::NameLookup { name, scope, position } => Ok(ReplProgress::NameLookup(ReplNameLookup { + name, + position, + scope, + snapshot: new_repl_snapshot!(), + })), + ConvertedExit::Error(err) => { + // Resolve traceback frames against every snippet the REPL has + // seen, not just the currently-executing one. `executor.interns` + // is still required because it holds the StringIds referenced by + // the in-flight frames; `repl.sources` holds every snippet's + // source text and is what owns any older snippets' sources. + let error = err.into_python_exception(&executor.tables.interns, |fname| { + repl.sources.get(fname).map(|source| &**source) + }); + // Commit compiler metadata even on runtime errors, matching feed() behavior. + // Snippets can create new variables or functions before raising, and those + // values may reference FunctionId/StringId values from the new tables. + repl.commit_executor(executor); + Err(Box::new(ReplStartError { repl, error })) + } + } +} + +/// Converts host call arguments to internal `ArgValues` for function calls; +/// `call_function` has already refused keyword arguments. +fn convert_args(args: CallArgs, vm: &mut VM<'_>) -> Result { + let (graph, arg_ids, _) = unstable::into_call_args_parts(args); + let values = graph + .to_values(vm) + .map_err(|e| MontyException::runtime_error(format!("invalid argument type: {e}")))?; + defer_drop!(values, vm); + let mut positional: Vec = arg_ids + .iter() + .map(|id| values[id.index()].clone_with_heap(vm.heap)) + .collect(); + Ok(match positional.len() { + 0 => ArgValues::Empty, + 1 => ArgValues::One(positional.pop().expect("checked len")), + 2 => { + let b = positional.pop().expect("checked len"); + let a = positional.pop().expect("checked len"); + ArgValues::Two(a, b) + } + _ => ArgValues::ArgsKargs { + args: positional, + kwargs: KwargsValues::Empty, + }, + }) +} + +/// Whether a session global should be surfaced as a "function" by +/// [`function_names`](MontyRepl::function_names) / [`has_function`](MontyRepl::has_function). +/// +/// Deliberately narrower than [`Value::is_callable`]: it keeps only plain +/// function-like values and omits `Class`, `NamedTupleClass`, and `BoundMethod`, +/// which are callable but not what a host means by "a function it can invoke". +fn is_callable(value: &Value, heap: &Heap) -> bool { + match value { + Value::Builtin(_) | Value::ModuleFunction(_) | Value::DefFunction(_) => true, + // A `Class`, `NamedTupleClass`, or `BoundMethod` is also callable but is + // not a function, so keep only the function-like heap variants. + Value::Ref(id) => matches!( + heap.get(*id), + HeapData::Closure(_) | HeapData::FunctionDefaults(_) | HeapData::ExtFunction(_) + ), + _ => false, + } +} diff --git a/crates/bashkit-monty/src/resource_checks.rs b/crates/bashkit-monty/src/resource_checks.rs new file mode 100644 index 000000000..472ef9278 --- /dev/null +++ b/crates/bashkit-monty/src/resource_checks.rs @@ -0,0 +1,200 @@ +use hashbrown::HashTable; +use monty_types::{ExcType, LARGE_RESULT_THRESHOLD, ResourceError, ResourceTracker}; + +use crate::{ + bytecode::VM, + exception_private::{RunError, RunResult, SimpleException}, + value::{VALUE_SIZE, Value}, +}; + +/// Pre-checks that an operation producing `item_len * count` bytes won't exceed resource limits. +/// +/// Used for sequence repeats (`'x' * 999_999_999`), padding operations +/// (`str.ljust`, `str.center`, `str.zfill`, etc.), and any other operation +/// where the result size is a simple product of two known values. +pub fn check_repeat_size(item_len: usize, count: usize, tracker: &ResourceTracker) -> Result<(), ResourceError> { + check_estimated_size(item_len.saturating_mul(count), tracker) +} + +/// Pre-checks that `base ** exponent` won't exceed resource limits before computing. +/// +/// The result of `base ** exp` has approximately `base_bits * exp` bits. +/// For bases with 0 or 1 significant bits (0, 1, -1), the result is always +/// small regardless of exponent, so the check is skipped. +/// +/// The estimate includes a 4× safety multiplier because `BigInt::pow` uses repeated squaring. +/// At peak, old/new base and old/new accumulator coexist during each multiplication step, +/// requiring roughly 4× the final result size in memory. +pub fn check_pow_size(base_bits: u64, exponent: u64, tracker: &ResourceTracker) -> Result<(), ResourceError> { + // 0**n = 0, 1**n = 1, (-1)**n = ±1 — always small + if base_bits <= 1 { + return Ok(()); + } + let result_bytes = estimate_bits_to_bytes(base_bits.saturating_mul(exponent)); + // Repeated squaring needs ~4× result size in peak memory because old/new base and + // old/new accumulator coexist during each multiplication step. + check_estimated_size(result_bytes.saturating_mul(4), tracker) +} + +/// Pre-checks that an integer product of at most `result_bits` bits won't exceed resource +/// limits — used by `math.factorial`, `comb` and `perm`, which each bound their own result. +/// +/// The estimate is doubled because the last multiplication holds its operands, which +/// together are about the result's size, alongside the result itself. +pub fn check_product_size(result_bits: u64, tracker: &ResourceTracker) -> Result<(), ResourceError> { + check_estimated_size(estimate_bits_to_bytes(result_bits).saturating_mul(2), tracker) +} + +/// Pre-checks that an integer multiplication won't exceed resource limits. +/// +/// The result of multiplying two numbers has at most `a_bits + b_bits` bits. +pub fn check_mult_size(a_bits: u64, b_bits: u64, tracker: &ResourceTracker) -> Result<(), ResourceError> { + check_estimated_size(estimate_bits_to_bytes(a_bits.saturating_add(b_bits)), tracker) +} + +/// Pre-checks that a left shift won't exceed resource limits. +/// +/// The result of `value << shift` has approximately `value_bits + shift` bits. +/// For zero values the result is always zero, so the check is skipped. +pub fn check_lshift_size(value_bits: u64, shift_amount: u64, tracker: &ResourceTracker) -> Result<(), ResourceError> { + if value_bits == 0 { + return Ok(()); + } + check_estimated_size(estimate_bits_to_bytes(value_bits.saturating_add(shift_amount)), tracker) +} + +/// Pre-checks that an integer division overflow promotion won't exceed resource limits. +/// +/// Division results are bounded by the dividend size, but we still check for consistency +/// with other BigInt promotion paths. +pub fn check_div_size(dividend_bits: u64, tracker: &ResourceTracker) -> Result<(), ResourceError> { + check_estimated_size(estimate_bits_to_bytes(dividend_bits), tracker) +} + +/// Pre-checks that a string/bytes replace won't exceed resource limits before allocating. +/// +/// Expanding replacements use the maximum possible match count. Shrinking +/// replacements use `input_len`, since zero matches still copies the full input. +pub fn check_replace_size( + input_len: usize, + old_len: usize, + new_len: usize, + count: i64, + tracker: &ResourceTracker, +) -> Result<(), ResourceError> { + let estimated = if new_len < old_len { + input_len + } else { + // Empty pattern (old_len == 0): inserts before each element + after the last = input_len + 1 + let max_replacements = input_len + .checked_div(old_len) + .unwrap_or_else(|| input_len.saturating_add(1)); + + let replacements = if count < 0 { + max_replacements + } else { + max_replacements.min(usize::try_from(count).unwrap_or(usize::MAX)) + }; + + // Result = input_len - (replacements * old_len) + (replacements * new_len) + let removed = replacements.saturating_mul(old_len); + let added = replacements.saturating_mul(new_len); + input_len.saturating_sub(removed).saturating_add(added) + }; + + check_estimated_size(estimated, tracker) +} + +/// Pre-checks the reallocation a push into a full `Value` buffer causes, +/// dropping `item` if the container cannot grow. +/// +/// Callers reach it only at a capacity boundary, hence `#[cold]`. Without it the +/// doubling that straddles the soft memory limit lands past the allocator's hard +/// ceiling in one allocation, killing the worker instead of raising `MemoryError`. +/// Buffers of other element types call [`ResourceTracker::check_growth`] directly. +#[cold] +pub(crate) fn check_value_buffer_growth(vm: &mut VM<'_>, len: usize, capacity: usize, item: Value) -> RunResult { + match vm.heap.tracker.check_growth(len, capacity, VALUE_SIZE) { + Ok(()) => Ok(item), + Err(err) => { + item.drop_with(vm); + Err(err.into()) + } + } +} + +/// Pre-checks the reallocation one insertion into a dict or set would cause, +/// summing both of the buffers it grows. +/// +/// The dense entry vector and the `HashTable` indexing it reallocate +/// independently, with no allocation in between, so checking each increment +/// against the same pre-insertion usage lets both pass while their sum clears +/// the allocator's hard headroom. +pub(crate) fn check_entry_table_growth( + entries_len: usize, + entries_capacity: usize, + entry_size: usize, + indices: &HashTable, + tracker: &ResourceTracker, +) -> Result<(), ResourceError> { + let pending = + ResourceTracker::growth_bytes(entries_len, entries_capacity, entry_size).saturating_add(table_growth(indices)); + tracker.check_pending_allocation(pending) +} + +/// The bytes an insertion into a full index table would allocate, and zero if +/// the table has room. +/// +/// hashbrown rehashes into a table of roughly double the current allocation and +/// keeps the old one live until the move finishes, so the increment is about +/// twice `allocation_size()`. +fn table_growth(indices: &HashTable) -> usize { + let current = indices.allocation_size(); + // An unallocated table reports `allocation_size() == 0` with `len == capacity == 0`, + // so the doubling model has nothing to work from; its first table is a few dozen + // bytes, far below the headroom this check guards. + if current == 0 || indices.len() < indices.capacity() { + 0 + } else { + current.saturating_mul(2) + } +} + +/// Checks an estimated result size against the resource tracker. +/// +/// Only calls the tracker when the estimate exceeds `LARGE_RESULT_THRESHOLD` +/// to avoid overhead on small operations. +pub(crate) fn check_estimated_size(estimated_bytes: usize, tracker: &ResourceTracker) -> Result<(), ResourceError> { + if estimated_bytes > LARGE_RESULT_THRESHOLD { + tracker.check_large_result(estimated_bytes)?; + } + Ok(()) +} + +/// Converts an estimated bit count to bytes, saturating to `usize::MAX` on overflow. +/// +/// Overflow means the result is astronomically large, so saturating ensures +/// the resource limit check always triggers rather than being silently skipped. +fn estimate_bits_to_bytes(bits: u64) -> usize { + usize::try_from(bits.saturating_add(7) / 8).unwrap_or(usize::MAX) +} + +/// Converts a resource error to its host-visible Python exception. +/// +/// Recursion errors remain catchable for CPython compatibility; terminal +/// memory and time errors cannot be suppressed by sandboxed code. +impl From for RunError { + fn from(err: ResourceError) -> Self { + let (exc_type, catchable) = match &err { + ResourceError::Memory { .. } => (ExcType::MemoryError, false), + ResourceError::Time { .. } => (ExcType::TimeoutError, false), + ResourceError::Recursion { .. } => (ExcType::RecursionError, true), + }; + let exc = SimpleException::new_msg(exc_type, err).into(); + if catchable { + Self::Exc(exc) + } else { + Self::UncatchableExc(exc) + } + } +} diff --git a/crates/bashkit-monty/src/run.rs b/crates/bashkit-monty/src/run.rs new file mode 100644 index 000000000..2e4cb7ac9 --- /dev/null +++ b/crates/bashkit-monty/src/run.rs @@ -0,0 +1,895 @@ +//! Public interface for running Monty code. +use std::{ + borrow::Cow, + mem, + sync::{Arc, LazyLock}, +}; + +use monty_types::{ + AssertMessageAnnotations, ExcType, ExtFunctionResult, MontyException, MontyObject, OsFunctionCall, PrintWriter, + ResourceTracker, +}; +pub use monty_types::{CompileOptions, OsPolicy}; +use ruff_python_stdlib::identifiers::is_identifier; + +use crate::{ + bytecode::{Code, CodeBuilder, Compiler, FrameExit, Opcode, VM}, + exception_private::{ExcTypeExt, RunError, RunResult}, + heap::{DropWithContext, Heap, HeapReader}, + intern::{CompileInterns, Interns, StringId}, + name_map::NameMap, + namespace::NamespaceId, + object_bridge::MontyObjectExt, + parse::{CodeRange, parse_with_interner, source_nesting_exception}, + prepare::prepare_with_existing_names, + run_progress::{ + RunProgress, answer_unserved_lookups, build_run_progress, check_snapshot_from_converted, convert_frame_exit, + resume_with_result, + }, + types::str::StringRepr, + value::Value, + virtual_path::{canonical_cwd, posix_join}, +}; + +/// Primary interface for running Monty code. +/// +/// [`MontyRun`] supports two execution modes: +/// - **Simple execution**: Use [`run`](Self::run) or [`run_no_limits`](Self::run_no_limits) to run code to completion +/// - **Iterative execution**: Use [`start`](Self::start) to start execution which will pause at external function calls and +/// can be resumed later +/// +/// Deserialization requires trusted, unmodified state; see [`crate::Dump::load`]. +/// +/// # Example +/// ``` +/// use monty::MontyRun; +/// use monty_types::{CompileOptions, MontyObject}; +/// +/// let mut runner = MontyRun::new( +/// "x + 1".to_owned(), +/// "test.py", +/// vec!["x".to_owned()], +/// CompileOptions::default(), +/// ) +/// .unwrap(); +/// let result = runner.run_no_limits(vec![MontyObject::int(41)]).unwrap(); +/// assert_eq!(result, MontyObject::int(42)); +/// ``` +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct MontyRun { + /// The underlying executor containing compiled bytecode and interns. + executor: Executor, +} + +impl MontyRun { + /// Creates a new run snapshot by parsing the given code. + /// + /// This only parses and prepares the code - no heap or namespaces are created yet. + /// Call [`run`](Self::run) or [`start`](Self::start) with inputs to execute it. + /// + /// # Arguments + /// * `code` - The Python code to execute + /// * `script_name` - The script name for error messages; its final path + /// component is what `__file__` places under the working directory + /// (`/main.py` for `main.py` or `src/main.py` at the root) + /// * `input_names` - Names of input variables + /// * `options` - [`CompileOptions`] controlling CPython divergences; usually `CompileOptions::default()` + /// + /// # Errors + /// Returns [`MontyException`] if the code cannot be parsed. + pub fn new( + code: String, + script_name: &str, + input_names: Vec, + options: CompileOptions, + ) -> Result { + Executor::new(code, script_name, input_names, options).map(|executor| Self { executor }) + } + + /// Returns the code that was parsed to create this snapshot. + #[must_use] + pub fn code(&self) -> &str { + &self.executor.program.code + } + + /// Replaces the default clock, sleep and random initialization policies. + /// Applies to [`run`](Self::run) and [`start`](Self::start); `CallHost` + /// suspends to the host. Wall-clock access exposes timing information; + /// see `docs/security.md`. + /// + /// ``` + /// use monty::MontyRun; + /// use monty_types::{OsPolicy, CompileOptions, DateTimeSource, MontyObject}; + /// + /// let code = "from datetime import date\ndate.today().year".to_owned(); + /// let datetime = DateTimeSource::Fixed { unix_seconds: 1_700_000_000, microsecond: 0 }; + /// let calls = OsPolicy { datetime, ..OsPolicy::default() }; + /// let mut runner = MontyRun::new(code, "today.py", vec![], CompileOptions::default()).unwrap().with_os_policy(calls); + /// assert_eq!(runner.run_no_limits(vec![]).unwrap(), MontyObject::int(2023)); + /// ``` + #[must_use] + pub fn with_os_policy(mut self, os_policy: OsPolicy) -> Self { + self.executor.program.os_policy = Arc::new(os_policy); + self + } + + /// Sets the sandbox working directory the run starts in (default `/`). + /// + /// `cwd` is an absolute POSIX virtual path, passed through + /// [`normalize_virtual_path`](monty_types::normalize_virtual_path) so + /// `os.getcwd()` reports a canonical directory: it is what relative paths + /// in `open()` / `os` / `pathlib` calls resolve against before reaching + /// the host. Hosts typically pass the first mount's virtual path. + pub fn set_cwd(&mut self, cwd: &str) { + self.executor.program.cwd = canonical_cwd(cwd); + } + + /// Executes the code and returns both the result and reference count data, used for testing only. + #[cfg(feature = "ref-count-return")] + pub fn run_ref_counts(&mut self, inputs: Vec) -> Result { + self.executor.run_ref_counts(inputs) + } + + /// Executes the code and returns reference count data while using a custom tracker, used for testing only. + #[cfg(feature = "ref-count-return")] + pub fn run_ref_counts_with_tracker( + &mut self, + inputs: Vec, + resource_tracker: ResourceTracker, + ) -> Result { + self.executor.run_ref_counts_with_tracker(inputs, resource_tracker) + } + + /// Executes the code to completion assuming not external functions or snapshotting. + /// + /// This is marginally faster than running with snapshotting enabled since we don't need + /// to track the position in code, but does not allow calling of external functions. + /// + /// Takes `&mut self` because a run extends the compiled program: `eval()` / + /// `exec()` append the code they compile to the runner's tables. + /// + /// # Arguments + /// * `inputs` - Values to fill the first N slots of the namespace + /// * `resource_tracker` - Custom resource tracker implementation + /// * `print` - print output writer + pub fn run( + &mut self, + inputs: Vec, + resource_tracker: ResourceTracker, + print: PrintWriter<'_>, + ) -> Result { + self.executor.run(inputs, resource_tracker, print) + } + + /// Executes the code to completion with no resource limits specified (will use the default), + /// printing to stdout/stderr. + pub fn run_no_limits(&mut self, inputs: Vec) -> Result { + self.run(inputs, ResourceTracker::default(), PrintWriter::Stdout) + } + + /// Starts execution with the given inputs and resource tracker, consuming self. + /// + /// Creates the heap and namespaces, then begins execution. + /// + /// For iterative execution, [`start`](Self::start) consumes self and returns a [`RunProgress`]: + /// - [`RunProgress::FunctionCall`] - external function call, call [`FunctionCall::resume`](crate::FunctionCall::resume) to resume + /// - [`RunProgress::Complete`] - execution finished + /// + /// This enables snapshotting execution state and returning control to the host + /// application during long-running computations. + /// + /// # Arguments + /// * `inputs` - Initial input values (must match length of `input_names` from [`new`](Self::new)) + /// * `resource_tracker` - Resource tracker for the execution + /// * `print` - Writer for print output + /// + /// # Errors + /// Returns [`MontyException`] if: + /// - The number of inputs doesn't match the expected count + /// - An input value is invalid (e.g. a [`MontyObject::repr`] value) + /// - A runtime error occurs during execution + /// + /// # Panics + /// This method should not panic under normal operation. Internal assertions + /// may panic if the VM reaches an inconsistent state (indicating a bug). + pub fn start( + self, + inputs: Vec, + resource_tracker: ResourceTracker, + print: PrintWriter<'_>, + ) -> Result { + let mut executor = self.executor; + + // Create heap and VM with empty globals, then populate inputs with VM alive + let mut heap = Heap::new(executor.namespace_size(), resource_tracker); + let globals = executor.empty_globals(); + let (converted, vm_state) = + HeapReader::with(&mut heap, &mut (&mut executor, print), |reader, (executor, print)| { + let mut vm = VM::new( + globals, + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + populate_inputs(inputs, &mut vm)?; + + // Start execution + let vm_result = vm.run_external(); + + // Three-phase conversion: convert while VM alive, then snapshot, then build progress + let converted = convert_frame_exit(vm_result, &mut vm); + let vm_state = check_snapshot_from_converted(&converted, vm); + Ok((converted, vm_state)) + })?; + build_run_progress(converted, vm_state, executor, heap) + } +} + +/// Compiled program and session tables used by `MontyRun`, `run_progress` and `repl`. +/// The VM borrows the program and committed intern entries immutably, but the +/// global-name map mutably so runtime compilation can add module slots. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) struct Executor { + /// Compiler tables the run may extend. + pub(crate) tables: SessionTables, + /// Everything else a run needs, fixed once compiled. + pub(crate) program: Program, + /// Estimated heap capacity for pre-allocation on subsequent runs. + heap_capacity: usize, +} + +/// Session-owned compiler tables, transferred to each snippet's executor. +/// The VM borrows names mutably and committed intern entries immutably. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub(crate) struct SessionTables { + /// Module-level global names, slot by slot. + pub(crate) global_names: NameMap, + /// Interned strings and compiled functions used during execution. + pub(crate) interns: Interns, +} + +/// The module code, source and environment, borrowed immutably during execution. +/// Separate from [`SessionTables`] so global names can grow without moving the module's code. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) struct Program { + /// Immutable module bytecode, shared by runner clones and borrowed by module frames. + pub(crate) module_code: Arc, + /// Source code for error reporting (extracting preview lines for + /// tracebacks). Shared with the REPL's per-snippet source table rather + /// than copied, since a snippet's text is the largest thing a feed carries. + pub(crate) code: Arc, + /// Pre-resolved input slots, avoiding name lookups during REPL input injection. + /// Empty for the standard execution path. + pub(crate) input_slots: Vec, + /// UTF-8 byte cap for each operand repr in introspected assert messages. + /// Stored with the compiled program and passed to every VM. + pub(crate) assert_repr_max_bytes: u32, + /// The options the program was compiled with; `eval()` / `exec()` compile + /// their snippets the same way. + pub(crate) options: CompileOptions, + /// OS-call policies shared with the REPL session; see [`MontyRun::with_os_policy`]. + pub(crate) os_policy: Arc, + /// The user-facing script name (`main.py`), whose final component + /// `__file__` is derived from. For REPL snippets this is the session's + /// name (shared with it, not copied per feed), not the `` + /// name the snippet was parsed under. + pub(crate) script_name: Arc, + /// Sandbox working directory every VM built from this executor starts in; + /// `/` unless the host set one (see [`MontyRun::set_cwd`]). Shared with + /// the REPL session like `script_name`. + pub(crate) cwd: Arc, +} + +/// Per-run environment handed to a fresh VM: the sandbox working directory, +/// what `__file__` derives from and the assert-repr cap. Built by +/// [`Program::vm_env`] so every `VM::new` call site agrees on how the +/// values derive from the executor. Borrows rather than clones: a VM is +/// built per run, so this must not allocate. +pub(crate) struct VmEnv<'h> { + /// Working directory `os.getcwd()` reports and relative paths resolve + /// against. Borrowed from the executor until `os.chdir` replaces it. + pub(crate) cwd: Cow<'h, str>, + /// Working directory the run started in; `__file__` is `script_name`'s + /// final component placed under it, unaffected by a later `os.chdir`. + pub(crate) initial_cwd: &'h str, + /// User-facing script name (`main.py`), the basis of `__file__`. + pub(crate) script_name: &'h str, + /// UTF-8 byte cap for each operand repr in introspected assert messages. + pub(crate) assert_repr_max_bytes: u32, + /// Compile options for code compiled at runtime by `eval()` / `exec()`. + pub(crate) options: CompileOptions, + /// Clock, sleep and random initialization policies. + pub(crate) os_policy: &'h OsPolicy, +} + +impl VmEnv<'_> { + /// `__file__`: the script name under the starting working directory, + /// computed on read since most runs never look at it. + pub(crate) fn file(&self) -> String { + posix_join(self.initial_cwd, self.script_basename()) + } + + /// The script name as the sandbox sees it — what `sys.argv[0]` reports and + /// what [`file`](Self::file) places under the working directory. + /// + /// Only the final path component is kept because the script name is a + /// host-side label that may be a host path (`monty /home/me/app.py`), and + /// host directory structure must not leak into the sandbox. + pub(crate) fn script_basename(&self) -> &str { + self.script_name.rsplit(['/', '\\']).next().unwrap_or_default() + } +} + +impl Default for VmEnv<'static> { + /// The environment of a VM built without an executor (in-module tests): + /// root working directory, no script. + fn default() -> Self { + Self { + cwd: Cow::Borrowed(DEFAULT_CWD), + initial_cwd: DEFAULT_CWD, + script_name: "", + assert_repr_max_bytes: AssertMessageAnnotations::DEFAULT_MAX_BYTES.get(), + options: CompileOptions::default(), + os_policy: &DEFAULT_OS_POLICY, + } + } +} + +/// Policies for VMs constructed without an executor. +static DEFAULT_OS_POLICY: LazyLock = LazyLock::new(OsPolicy::default); + +/// The sandbox working directory used until a host sets one. +pub(crate) const DEFAULT_CWD: &str = "/"; + +/// Session identity a REPL snippet executor inherits: the user-facing script +/// name and the working directory the snippet starts in. Both are shared +/// (`Arc`) so building a snippet executor allocates neither. +#[derive(Clone, Copy)] +pub(crate) struct ReplSession<'a> { + /// User-facing script name (`main.py`), the basis of `__file__`. + pub(crate) script_name: &'a Arc, + /// Absolute virtual working directory for the snippet. + pub(crate) cwd: &'a Arc, + /// Clock, sleep and random initialization policies. + pub(crate) os_policy: &'a Arc, +} + +impl Executor { + /// Creates a new executor with the given code, filename, input names, and compile options. + pub(crate) fn new( + code: String, + script_name: &str, + input_names: Vec, + options: CompileOptions, + ) -> Result { + check_identifier(&input_names)?; + source_nesting_exception(&code, script_name, options.source_scan_threshold)?; + let mut interns = Interns::new(&code); + let mut globals = NameMap::new(); + let (module_code, _) = compile_module_source( + &code, + script_name, + &mut globals, + CompileInterns::direct(&mut interns), + input_names, + options, + )?; + let namespace_size = globals.len(); + + Ok(Self { + tables: SessionTables { + global_names: globals, + interns, + }, + program: Program { + module_code: Arc::new(module_code), + code: Arc::from(code), + input_slots: Vec::new(), + assert_repr_max_bytes: options.assert_message_annotations.max_bytes(), + options, + os_policy: Arc::new(OsPolicy::default()), + script_name: Arc::from(script_name), + cwd: Arc::from(DEFAULT_CWD), + }, + heap_capacity: namespace_size, + }) + } + + /// Returns the size of the module's global namespace (number of slots). + #[inline] + pub(crate) fn namespace_size(&self) -> usize { + self.tables.global_names.len() + } + + /// Compiles privately against the session's existing IDs and global slots. + /// On success the tables move into the executor; on failure they remain unchanged. + /// `script_name` identifies this feed's source; `session` supplies the user-facing + /// filename and working directory. + pub(crate) fn new_repl_snippet( + code: Arc, + script_name: &str, + globals: &mut NameMap, + interns: &mut Interns, + input_names: &[String], + options: CompileOptions, + session: ReplSession<'_>, + ) -> Result { + check_identifier(input_names)?; + + // Preparation assigns provisional global slots alongside the private intern IDs. + let globals_len = globals.len(); + let compiled = compile_module_source( + &code, + script_name, + globals, + CompileInterns::new(interns), + input_names, + options, + ); + if compiled.is_err() { + globals.truncate(globals_len); + } + let (module_code, input_slots) = compiled?; + + Ok(Self { + tables: SessionTables { + global_names: mem::take(globals), + interns: interns.take(), + }, + program: Program { + module_code: Arc::new(module_code), + code, + input_slots, + assert_repr_max_bytes: options.assert_message_annotations.max_bytes(), + options, + os_policy: Arc::clone(session.os_policy), + script_name: Arc::clone(session.script_name), + cwd: Arc::clone(session.cwd), + }, + heap_capacity: 0, + }) + } + + /// Builds a synthetic REPL input that calls one existing global with host arguments. + /// + /// The argument tuple occupies a namespace slot named ``, + /// which no Python source can spell; the caller commits the map back after + /// the call (the function may have bound new globals) and clears that slot, + /// so it is reused by the next call. The session's [`Interns`] are extended + /// in place (two ids, no parse) and moved into the executor on success; on + /// failure they stay with the caller. + #[expect( + clippy::too_many_arguments, + reason = "synthetic calls combine existing REPL and call-site metadata" + )] + pub(crate) fn new_repl_function_call( + name: &str, + name_id: StringId, + callable_slot: NamespaceId, + arg_count: usize, + script_name: &str, + mut existing_globals: NameMap, + interns: &mut Interns, + options: CompileOptions, + session: ReplSession<'_>, + ) -> Result { + const CALL_ARGS_NAME: &str = ""; + + let code = if arg_count == 0 { + format!("{name}()") + } else { + format!("{name}(...)") + }; + let mut overlay = CompileInterns::new(interns); + let filename = overlay.intern(script_name); + let range = CodeRange { + filename, + start_byte: 0, + end_byte: u32::try_from(code.len()).unwrap_or(u32::MAX), + }; + let args_name_id = overlay.intern(CALL_ARGS_NAME); + let args_slot = existing_globals + .ensure_slot(args_name_id, range) + .map_err(|e| e.into_python_exc(script_name, &code))?; + + let mut builder = CodeBuilder::new(); + builder.new_code_region(0); + builder.set_location(range, None); + builder + .emit_load_global_callable(callable_slot.as_u16(), name_id) + .map_err(|e| e.into_python_exc(script_name, &code))?; + builder + .emit_u16(Opcode::LoadGlobal, args_slot.as_u16()) + .map_err(|e| e.into_python_exc(script_name, &code))?; + builder + .emit_u8(Opcode::CallFunctionExtended, 0) + .map_err(|e| e.into_python_exc(script_name, &code))?; + builder + .emit(Opcode::ReturnValue) + .map_err(|e| e.into_python_exc(script_name, &code))?; + + let module_code = builder.build(); + overlay.commit(); + let tables = SessionTables { + global_names: existing_globals, + interns: interns.take(), + }; + + Ok(Self { + tables, + program: Program { + module_code: Arc::new(module_code), + code: Arc::from(code), + input_slots: vec![args_slot], + assert_repr_max_bytes: options.assert_message_annotations.max_bytes(), + options, + os_policy: Arc::clone(session.os_policy), + script_name: Arc::clone(session.script_name), + cwd: Arc::clone(session.cwd), + }, + heap_capacity: 0, + }) + } + + /// Executes the code with a custom resource tracker. + /// + /// This provides full control over resource tracking and garbage collection + /// scheduling. The tracker is called on each allocation and periodically + /// during execution to check time limits and trigger GC. + /// + /// # Arguments + /// * `inputs` - Values to fill the first N slots of the namespace + /// * `resource_tracker` - Custom resource tracker implementation + /// * `print` - Print output writer + fn run( + &mut self, + inputs: Vec, + resource_tracker: ResourceTracker, + print: PrintWriter<'_>, + ) -> Result { + let heap_capacity = self.heap_capacity; + let mut heap = Heap::new(heap_capacity, resource_tracker); + let globals = self.empty_globals(); + + // Create VM first, then populate inputs with VM alive + let result = HeapReader::with(&mut heap, &mut (&mut *self, print), |reader, (executor, print)| { + let mut vm = VM::new( + globals, + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + populate_inputs(inputs, &mut vm)?; + Program::run_to_completion(&mut vm) + }); + + if heap.size() > heap_capacity { + self.heap_capacity = heap.size(); + } + + // Non-REPL execution has exactly one source, so every frame's filename + // resolves to the same `self.code`. + result.map_err(|e| e.into_python_exception(&self.tables.interns, |_| Some(&*self.program.code))) + } + + /// Executes the code and returns both the result and reference count data, used for testing only. + #[cfg(feature = "ref-count-return")] + fn run_ref_counts(&mut self, inputs: Vec) -> Result { + self.run_ref_counts_with_tracker(inputs, ResourceTracker::default()) + } + + /// Executes the code and returns both the result and reference count data with a custom tracker, + /// used for testing only. + /// + /// This is used for testing reference counting behavior with a custom tracker. Returns + /// the execution result plus, in [`RefCountOutput`], a map from variable names to their + /// reference counts (heap-allocated values only), any live-but-unreachable heap entries, + /// and the total live heap population. + /// + /// For strict-matching validation, assert that `unreachable` is empty: every live heap + /// object should be reachable from a named variable, so anything left over is a leak. + /// + /// Only available when the `ref-count-return` feature is enabled. + #[cfg(feature = "ref-count-return")] + fn run_ref_counts_with_tracker( + &mut self, + inputs: Vec, + resource_tracker: ResourceTracker, + ) -> Result { + let mut heap = Heap::new(self.namespace_size(), resource_tracker); + let globals = self.empty_globals(); + + HeapReader::with(&mut heap, self, |reader, executor| { + // Create VM, populate inputs, and run + let mut vm = VM::new( + globals, + &mut executor.tables, + &executor.program, + reader, + PrintWriter::Stdout, + ); + populate_inputs(inputs, &mut vm)?; + // Lookups are answered before the globals are taken below: an + // armed `hasattr()` / `getattr()` effect runs the module on. + let frame_exit_result = answer_unserved_lookups(vm.run_external(), &mut vm); + + // Tasks the module left running (a sibling detached from a failed + // gather, say) hold real references, and are not reachable from + // any name — so tear the scheduler down first and hold the + // leak check to what survives that. + vm.__finalize_tasks_for_tests(); + vm.__force_gc_for_tests(); + + // Take globals out of the VM so we can inspect them, but keep VM alive + // for heap access and later conversion. + let globals = vm.take_globals(); + + // Read refcounts BEFORE converting the return value, because + // `frame_exit_to_object` drops the return value (decrementing its refcount). + let mut counts = ahash::AHashMap::new(); + let mut roots = Vec::new(); + + for (namespace_id, name_id) in vm.global_names.iter() { + let idx = namespace_id.index(); + if idx < globals.len() + && let Value::Ref(id) = &globals[idx] + { + counts.insert(vm.interns.get_str(name_id).to_owned(), vm.heap.get_refcount(*id)); + roots.push(*id); + } + } + // The module's result is a root too: it is still owned by the pending + // `FrameExit::Return` here, since `frame_exit_to_object` below is what drops it. + if let Ok(FrameExit::Return(Value::Ref(id))) = &frame_exit_result { + roots.push(*id); + } + // Those are the only roots: locals are gone once the module frame exits, so + // anything still live must hang off a name or the result to not be a leak. + let unreachable: Vec = vm + .heap + .unreachable_entries(roots) + .into_iter() + .map(|(id, ty)| format!("{} (id {})", ty.name(vm.heap, vm.interns), id.index())) + .collect(); + let heap_count = vm.heap.entry_count(); + + // Convert return value while VM is still alive (needs access to interns). + // Non-REPL: single source, so every frame resolves to `executor.code`. + let value = frame_exit_to_object(frame_exit_result, &mut vm) + .map_err(|e| e.into_python_exception(vm.interns, |_| Some(&*executor.program.code)))?; + + // Drop globals with proper ref counting + globals.drop_with(vm.heap); + + let allocations_since_gc = vm.heap.get_allocations_since_gc(); + + Ok(RefCountOutput { + value, + counts, + unreachable, + heap_count, + allocations_since_gc, + }) + }) + } + + /// Creates an empty globals vector with all slots set to `Undefined`. + /// + /// Used to initialize global storage before input population. The VM is created + /// with these empty globals, then [`populate_inputs`] fills + /// the input slots while the VM is alive. + pub(crate) fn empty_globals(&self) -> Vec { + (0..self.namespace_size()).map(|_| Value::Undefined).collect() + } +} + +impl Program { + /// Builds the [`VmEnv`] a VM run from this program starts with. + pub(crate) fn vm_env(&self) -> VmEnv<'_> { + VmEnv { + cwd: Cow::Borrowed(&self.cwd), + initial_cwd: &self.cwd, + script_name: &self.script_name, + assert_repr_max_bytes: self.assert_repr_max_bytes, + options: self.options, + os_policy: &self.os_policy, + } + } + + /// A program with no code, for in-module tests that need a VM. + #[cfg(test)] + pub(crate) fn for_tests() -> Self { + Self { + module_code: Arc::new(Code::empty()), + code: Arc::from(""), + input_slots: Vec::new(), + assert_repr_max_bytes: AssertMessageAnnotations::DEFAULT_MAX_BYTES.get(), + options: CompileOptions::default(), + os_policy: Arc::new(OsPolicy::default()), + script_name: Arc::from(""), + cwd: Arc::from(DEFAULT_CWD), + } + } + + /// Runs module code on an already-configured VM to completion. + /// + /// Executes [`VM::run_external`], then answers the lookup and `ExternalCall` + /// exits no host will serve by raising `NameError` / `AttributeError` + /// through the VM so tracebacks are properly captured. Finally converts + /// the result via [`frame_exit_to_object`]. + /// + /// This is the shared non-iterative execution core used by both the standard + /// `run` path and the REPL's `feed_run` path. + pub(crate) fn run_to_completion(vm: &mut VM<'_>) -> RunResult { + let mut frame_exit_result = vm.run_external(); + + // In the non-iterative path there's no host to resolve names, lazy + // attributes or external functions, so lookups are answered `Undefined` + // and a called external function is an undefined name. + loop { + match answer_unserved_lookups(frame_exit_result, vm) { + Ok(FrameExit::ExternalCall { + function_name, + args, + name_load_ip, + .. + }) => { + // In non-iterative execution no host answers, so the name was + // undefined. Restore the frame IP to the load instruction so the + // traceback points to the name reference, not the call expression. + if let Some(load_ip) = name_load_ip { + vm.set_instruction_ip(load_ip); + } + let err = ExcType::name_error(function_name.as_str(vm.interns)).into(); + args.drop_with(vm); + frame_exit_result = vm.resume_with_exception(err); + } + // An import nobody serves is a missing module. + Ok(FrameExit::OsCall { + function_call: call @ OsFunctionCall::Import(_), + .. + }) => { + frame_exit_result = resume_with_result(vm, ExtFunctionResult::Error(call.on_no_handler()), None); + } + // Standard execution waits inline, excluding sleep from execution time. + Ok(FrameExit::OsCall { + function_call: OsFunctionCall::SystemSleep(delay) | OsFunctionCall::AsyncSystemSleep(delay), + effect, + .. + }) => { + vm.pending_effect = effect; + vm.heap.tracker.sandbox_sleep(delay); + frame_exit_result = resume_with_result(vm, ExtFunctionResult::Return(MontyObject::none()), None); + } + other => return frame_exit_to_object(other, vm), + } + } + } +} + +/// Converts `MontyObject` inputs to `Value`s and writes them into the VM's globals. +/// +/// This runs with the VM alive so that `to_value` has access to the full VM context. +/// On error partway through, the VM's `Drop` impl will drain globals and +/// properly decrement refcounts for any already-converted values. +fn populate_inputs(inputs: Vec, vm: &mut VM<'_>) -> Result<(), MontyException> { + if inputs.len() > vm.globals.len() { + return Err(MontyException::runtime_error("too many inputs for namespace")); + } + for (i, input) in inputs.into_iter().enumerate() { + let value = input + .to_value(vm) + .map_err(|e| MontyException::runtime_error(format!("invalid input type: {e}")))?; + vm.globals[i] = value; + } + Ok(()) +} + +/// Converts module/frame exit results into exported `MontyObject` outputs. +/// +/// Used by non-iterative execution paths: lookups are answered as no host +/// would (see [`answer_unserved_lookups`]) and the remaining suspendable +/// outcomes (external calls, futures) produce errors. +pub(crate) fn frame_exit_to_object(frame_exit_result: RunResult, vm: &mut VM<'_>) -> RunResult { + // Suspensions this path cannot service. The error is built from a borrow + // so one `drop_with` releases whatever the exit owns, fields added later + // included. + let exit = match answer_unserved_lookups(frame_exit_result, vm)? { + FrameExit::Return(return_value) => return Ok(MontyObject::export(return_value, vm)), + exit => exit, + }; + let error: RunError = match &exit { + FrameExit::Return(_) => unreachable!("returns are handled above"), + FrameExit::ExternalCall { function_name, .. } => ExcType::not_implemented(format!( + "External function '{}' not implemented with standard execution", + function_name.as_str(vm.interns) + )) + .into(), + FrameExit::OsCall { function_call, .. } => ExcType::not_implemented(format!( + "OS function '{}' not implemented with standard execution", + function_call.name() + )) + .into(), + FrameExit::MethodCall { method_name, .. } => { + let name = method_name.as_str(vm.interns); + ExcType::not_implemented(format!("Method call '{name}' not implemented with standard execution")).into() + } + FrameExit::ResolveFutures(_) => { + ExcType::not_implemented("async futures not supported by standard execution.").into() + } + FrameExit::NameLookup { .. } | FrameExit::AttrLookup { .. } => unreachable!("lookups are answered above"), + }; + exit.drop_with(vm); + Err(error) +} + +/// Output from `run_ref_counts` containing reference count and heap information. +/// +/// Used for testing GC behavior and reference counting correctness. +#[cfg(feature = "ref-count-return")] +#[derive(Debug)] +pub struct RefCountOutput { + pub value: MontyObject, + pub counts: ahash::AHashMap, + /// Live heap entries reachable from no named variable, described as + /// `" (id N)"`. Non-empty means the run leaked: a missed `drop_with` + /// left an object alive that nothing can reach. Reachability is transitive, + /// so objects owned by another object are accounted for by their owner. + pub unreachable: Vec, + pub heap_count: usize, + /// Number of GC-tracked allocations since the last cycle collection. + /// + /// If the collector ran during execution, this will be much lower than + /// the total number of GC-tracked allocations performed. Compare against + /// the configured `gc_interval` to verify GC fired at the expected + /// cadence. + pub allocations_since_gc: u32, +} + +/// Compiles module source through the supplied tables, committing any overlay on success. +/// On failure the caller restores provisional global slots or discards a fresh program's tables. +/// The source must already have passed the nesting scan; `MontyRun::new` and +/// the REPL feeds run it. +fn compile_module_source( + code: &str, + script_name: &str, + globals: &mut NameMap, + mut interns: CompileInterns<'_>, + input_names: impl IntoIterator>, + options: CompileOptions, +) -> Result<(Code, Vec), MontyException> { + let input_names = input_names.into_iter(); + let mut input_slots = Vec::with_capacity(input_names.size_hint().0); + for name in input_names { + let name_id = interns.intern(name.as_ref()); + let slot = globals + .ensure_slot(name_id, CodeRange::default()) + .map_err(|e| e.into_python_exc(script_name, code))?; + input_slots.push(slot); + } + let nodes = + parse_with_interner(code, script_name, &mut interns).map_err(|e| e.into_python_exc(script_name, code))?; + let nodes = + prepare_with_existing_names(nodes, &interns, globals).map_err(|e| e.into_python_exc(script_name, code))?; + let module_code = Compiler::compile_module(&nodes, &mut interns, globals, options) + .map_err(|e| e.into_python_exc(script_name, code))?; + interns.commit(); + Ok((module_code, input_slots)) +} + +/// Check if input names are valid Python identifiers. +/// +/// `is_identifier` also checks that the names are not keywords. +fn check_identifier(input_names: &[String]) -> Result<(), MontyException> { + for name in input_names { + if !is_identifier(name) { + return Err(MontyException::new( + ExcType::SyntaxError, + Some(format!("Input name {} not a valid identifier", StringRepr(name))), + )); + } + } + Ok(()) +} diff --git a/crates/bashkit-monty/src/run_progress.rs b/crates/bashkit-monty/src/run_progress.rs new file mode 100644 index 000000000..f3901106b --- /dev/null +++ b/crates/bashkit-monty/src/run_progress.rs @@ -0,0 +1,1301 @@ +//! This module defines the public types returned by [`MontyRun::start()`](crate::MontyRun::start) +//! and their resume methods. Each variant of [`RunProgress`] wraps a dedicated struct +//! (`FunctionCall`, `OsCall`, `NameLookup`, `ResolveFutures`) that carries only the +//! fields and resume methods relevant to that suspension point. +//! +//! The internal [`Snapshot`] type is `pub(crate)` — callers interact exclusively with +//! the per-variant structs. + +use std::mem; + +use monty_types::{ + CallArgs, ExcType, InvalidInputError, MontyException, MontyObject, MontyUuid, OsFunctionCall, PrintWriter, + ResourceTracker, SourceRange, +}; + +use crate::{ + asyncio::CallId, + bytecode::{FrameExit, PendingLookupEffect, VM, VMSnapshot}, + exception_private::{ExcTypeExt, ExceptionRaise, RunError, RunResult, SimpleException}, + heap::{DropWithContext, Heap, HeapReader}, + intern::{Interns, StringId}, + object_bridge::MontyObjectExt, + os_dispatch::{PendingEffect, PostConversionEffect, release_pending_effect}, + run::Executor, + value::Value, +}; + +// --------------------------------------------------------------------------- +// RunProgress enum +// --------------------------------------------------------------------------- + +/// Result of a single step of iterative execution. +/// +/// Each variant wraps a dedicated struct that owns the execution state and +/// exposes only the resume methods relevant to that suspension reason. +/// Deserialization requires trusted, unmodified state; see [`crate::Dump::load`]. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub enum RunProgress { + /// Execution paused at an external function call, or a method call on a + /// host object (`object_id` set). + FunctionCall(FunctionCall), + /// Execution paused for an OS-level operation (filesystem, network, etc.). + OsCall(OsCall), + /// All async tasks are blocked waiting for external futures to resolve. + ResolveFutures(ResolveFutures), + /// Execution paused for an unresolved name lookup. + NameLookup(NameLookup), + /// Execution completed with a final result. + Complete(MontyObject), +} + +impl RunProgress { + /// The execution heap and its interns for a dump upgrade, or `None` once + /// execution has completed. + pub(crate) fn heap_and_interns(&mut self) -> Option<(&mut Heap, &Interns)> { + match self { + Self::FunctionCall(FunctionCall { snapshot, .. }) + | Self::OsCall(OsCall { snapshot, .. }) + | Self::NameLookup(NameLookup { snapshot, .. }) => { + Some((&mut snapshot.heap, &snapshot.executor.tables.interns)) + } + Self::ResolveFutures(ResolveFutures { heap, executor, .. }) => Some((heap, &executor.tables.interns)), + Self::Complete(_) => None, + } + } + + /// Consumes the progress and returns the [`FunctionCall`] struct if this is a function call. + #[must_use] + pub fn into_function_call(self) -> Option { + match self { + Self::FunctionCall(call) => Some(call), + _ => None, + } + } + + /// Consumes the progress and returns the [`OsCall`] struct if this is an OS call. + #[must_use] + pub fn into_os_call(self) -> Option { + match self { + Self::OsCall(call) => Some(call), + _ => None, + } + } + + /// Consumes the progress and returns the final value if execution completed. + #[must_use] + pub fn into_complete(self) -> Option { + match self { + Self::Complete(value) => Some(value), + _ => None, + } + } + + /// Consumes the progress and returns the [`ResolveFutures`] struct. + #[must_use] + pub fn into_resolve_futures(self) -> Option { + match self { + Self::ResolveFutures(state) => Some(state), + _ => None, + } + } + + /// Consumes the progress and returns the [`NameLookup`] struct. + #[must_use] + pub fn into_name_lookup(self) -> Option { + match self { + Self::NameLookup(lookup) => Some(lookup), + _ => None, + } + } +} + +// --------------------------------------------------------------------------- +// FunctionCall +// --------------------------------------------------------------------------- + +/// Execution paused at an external function call or dataclass method call. +/// +/// The host can choose how to handle this: +/// - **Sync resolution**: Call [`resume`](Self::resume) to push the result and continue. +/// - **Async resolution**: Call [`resume_pending`](Self::resume_pending) to push an `ExternalFuture` and continue. +/// +/// When using async resolution, the code continues and may `await` the future later. +/// If the future isn't resolved when awaited, execution yields with [`ResolveFutures`]. +/// +/// When `object_id` is set, this represents a method call on a host-backed +/// object (construction of a host class is a `__call__` method call): route +/// it to the host object with that uuid — the receiver is NOT in `args`. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct FunctionCall { + /// The name of the function or method being called. + pub function_name: String, + /// The arguments: one arena holding every positional and keyword value. + pub args: CallArgs, + /// Unique identifier for this call (used for async correlation). + pub call_id: u32, + /// Uuid of the routed receiver — an instance, or a class type (a + /// classmethod call, or construction spelled `__call__`); `None` for + /// plain external function calls. + pub object_id: Option, + /// The host may await a coroutine and answer with [`Self::resume_eager`]. + pub allow_eager_await: bool, + /// Where the call expression is in the source. + pub position: SourceRange, + /// Internal execution snapshot. + snapshot: Snapshot, +} + +impl FunctionCall { + /// Creates a new `FunctionCall` from its parts. + fn new( + function_name: String, + args: CallArgs, + call_id: u32, + object_id: Option, + allow_eager_await: bool, + position: SourceRange, + snapshot: Snapshot, + ) -> Self { + Self { + function_name, + args, + call_id, + object_id, + allow_eager_await, + position, + snapshot, + } + } + + /// Returns a mutable reference to the resource tracker. + /// + /// This allows modifying resource limits between execution phases, + /// e.g. setting a time limit before resuming after an external function call. + pub fn tracker_mut(&mut self) -> &mut ResourceTracker { + &mut self.snapshot.heap.tracker + } + + /// Returns the resource tracker while execution is suspended. + #[must_use] + pub fn tracker(&self) -> &ResourceTracker { + &self.snapshot.heap.tracker + } + + /// Resumes execution with the return value or exception from the external function. + /// + /// Consumes self and returns the next execution progress. + /// + /// # Arguments + /// * `result` — The return value, exception, or pending future marker. + /// * `print` — Writer for `print()` output. + pub fn resume( + self, + result: impl Into, + print: PrintWriter<'_>, + ) -> Result { + self.snapshot.run(result.into(), print) + } + + /// Resumes execution by pushing an `ExternalFuture` instead of a concrete value. + /// + /// This is the async resolution pattern: the host continues execution with a + /// pending future. The code can then `await` this future later. If the code + /// awaits the future before it's resolved, execution will yield with + /// [`RunProgress::ResolveFutures`]. + /// + /// Uses `self.call_id` internally — no need to pass it again. + /// + /// # Arguments + /// * `print` — Writer for print output. + pub fn resume_pending(self, print: PrintWriter<'_>) -> Result { + self.snapshot.run(ExtFunctionResult::Future(self.call_id), print) + } + + /// Resumes with a settled coroutine, preserving its awaitable value and exception timing. + /// Only use when [`Self::allow_eager_await`] is true; synchronous returns use [`Self::resume`]. + pub fn resume_eager( + self, + result: Result, + print: PrintWriter<'_>, + ) -> Result { + self.snapshot.run_inner( + result.map_or_else(ExtFunctionResult::Error, ExtFunctionResult::Return), + Some(self.call_id), + print, + ) + } + + /// Aborts the feed with an uncatchable exception; see [`OsCall::abort`]. + pub fn abort(self, exc: MontyException, print: PrintWriter<'_>) -> Result { + self.snapshot.abort(exc, print) + } +} + +// --------------------------------------------------------------------------- +// OsCall +// --------------------------------------------------------------------------- + +/// Execution paused for an OS-level operation. +/// +/// The host should execute the OS operation (filesystem, network, etc.) and +/// call `resume(return_value, print)` to provide the result and continue. +/// +/// This enables sandboxed execution where the interpreter never directly performs I/O. +/// +/// `function_call` is a tagged [`OsFunctionCall`] whose variants carry the +/// typed args directly. Host bindings that need a generic +/// `(positional, keyword)` `MontyObject` view can call [`OsFunctionCall::to_args`] +/// (the public projection method). +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct OsCall { + /// Typed OS-call dispatch value (variant + args). + pub function_call: OsFunctionCall, + /// Unique identifier for this call (used for async correlation). + pub call_id: u32, + /// The host may await its wait and answer with [`Self::resume_eager`]. + /// Only ever true for `asyncio.sleep`, the one call a future may answer. + pub allow_eager_await: bool, + /// Where the call expression is in the source. + pub position: SourceRange, + /// Internal execution snapshot. + snapshot: Snapshot, +} + +impl OsCall { + /// Creates a new `OsCall` from its parts. + fn new( + function_call: OsFunctionCall, + call_id: u32, + allow_eager_await: bool, + position: SourceRange, + snapshot: Snapshot, + ) -> Self { + Self { + function_call, + call_id, + allow_eager_await, + position, + snapshot, + } + } + + /// Resumes execution with the OS call result. + /// + /// # Arguments + /// * `result` — The return value or exception from the OS operation. + /// * `print` — Writer for `print()` output. + pub fn resume( + self, + result: impl Into, + print: PrintWriter<'_>, + ) -> Result { + self.snapshot.run(result.into(), print) + } + + /// Dispatches the call to `handler` and resumes execution with its result. + /// + /// `handler` receives the [`OsFunctionCall`] by value, so large + /// `WriteText` / `WriteBytes` payloads move into the host without + /// cloning. Prefer this over reading [`Self::function_call`] and calling + /// [`Self::resume`] separately when the handler consumes the call. + pub fn resume_with( + self, + print: PrintWriter<'_>, + handler: impl FnOnce(OsFunctionCall) -> ExtFunctionResult, + ) -> Result { + let result = handler(self.function_call); + self.snapshot.run(result, print) + } + + /// Resumes with the wait already performed, as [`FunctionCall::resume_eager`] + /// does for a settled coroutine: the `await` that follows finds the sleep + /// settled without a `ResolveFutures` round trip. Only use when + /// [`Self::allow_eager_await`] is true. + pub fn resume_eager( + self, + result: Result, + print: PrintWriter<'_>, + ) -> Result { + self.snapshot.run_inner( + result.map_or_else(ExtFunctionResult::Error, ExtFunctionResult::Return), + Some(self.call_id), + print, + ) + } + + /// Ends the feed by raising `exc` uncatchably at the suspended call. + /// + /// The exception builds a traceback but bypasses sandbox handlers. Pending + /// file effects roll back. Always returns `Err`. + pub fn abort(self, exc: MontyException, print: PrintWriter<'_>) -> Result { + self.snapshot.abort(exc, print) + } + + /// Returns the resource tracker while execution is suspended. + #[must_use] + pub fn tracker(&self) -> &ResourceTracker { + &self.snapshot.heap.tracker + } +} + +// --------------------------------------------------------------------------- +// NameLookup +// --------------------------------------------------------------------------- + +/// Where a resumed name-lookup value lands, and what an `Undefined` answer +/// raises. +/// +/// `Namespace` is the classic global/local lookup (the value is cached in the +/// slot, `Undefined` raises `NameError`). `Instance` is a lazy attribute +/// lookup on a host class instance: the value becomes the result of the +/// attribute expression — never cached, so every access re-consults the host — +/// and `Undefined` raises `AttributeError` naming the real class. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) enum LookupScope { + /// Plain global/local name — cache into the namespace slot. + Namespace { + /// The namespace slot where the resolved value should be cached. + namespace_slot: u16, + /// Whether this is a global slot or a local/function slot. + is_global: bool, + }, + /// Lazy attribute on a host-backed object (instance or class type). + Attr { + /// Host identity of the object whose attribute is read. + object_id: MontyUuid, + /// Class name captured at suspension for the AttributeError message. + class_name: String, + /// True for a class type receiver — selects CPython's + /// `type object '...' has no attribute ...` message. + type_object: bool, + }, +} + +impl LookupScope { + /// The receiver uuid when this is a lazy attribute lookup. + pub(crate) fn object_id(&self) -> Option { + match self { + Self::Namespace { .. } => None, + Self::Attr { object_id, .. } => Some(*object_id), + } + } +} + +/// Execution paused for an unresolved name lookup, or — when +/// [`object_id`](Self::object_id) is set — a lazy attribute lookup on a +/// host-backed object. +/// +/// The host should check if the name corresponds to a known external function, +/// value, or instance attribute. Call [`resume`](Self::resume) with +/// [`NameLookupResult::Value`] to continue, [`NameLookupResult::Undefined`] +/// to raise `NameError` (plain lookups) / `AttributeError` (instance lookups), +/// or [`NameLookupResult::Error`] to raise a host exception in the sandbox. +/// +/// The namespace slot and scope are managed internally — the host only needs to +/// provide the name resolution result. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct NameLookup { + /// The name being looked up. + pub name: String, + /// Where the name (or attribute access) is in the source. + pub position: SourceRange, + /// Where the resolved value lands (namespace slot or instance attribute). + scope: LookupScope, + /// Internal execution snapshot. + snapshot: Snapshot, +} + +impl NameLookup { + /// Creates a new `NameLookup` from its parts. + fn new(name: String, position: SourceRange, scope: LookupScope, snapshot: Snapshot) -> Self { + Self { + name, + position, + scope, + snapshot, + } + } + + /// Host identity of the receiver for a lazy attribute lookup; `None` for + /// a plain global/local name lookup. + #[must_use] + pub fn object_id(&self) -> Option { + self.scope.object_id() + } + + /// Returns the resource tracker while execution is suspended. + #[must_use] + pub fn tracker(&self) -> &ResourceTracker { + &self.snapshot.heap.tracker + } + + /// Aborts the feed with an uncatchable exception; see [`OsCall::abort`]. + pub fn abort(self, exc: MontyException, print: PrintWriter<'_>) -> Result { + self.snapshot.abort(exc, print) + } + + /// Resumes execution after name resolution. + /// + /// For a plain lookup, caches the resolved value in the appropriate slot + /// (globals or stack) before pushing it, and `Undefined` raises + /// `NameError`. For an instance attribute lookup, the value is pushed as + /// the attribute expression's result (never cached), and `Undefined` + /// raises `AttributeError`. `Error` raises the host's exception in the + /// sandbox, bypassing any `hasattr()` / `getattr()` default. + /// + /// # Arguments + /// * `result` — The resolved value, [`Undefined`](NameLookupResult::Undefined), or a host exception. + /// * `print` — Writer for print output. + pub fn resume( + self, + result: impl Into, + print: PrintWriter<'_>, + ) -> Result { + let result = result.into(); + + let Snapshot { + mut heap, + mut executor, + vm_state: snapshot_vm_state, + } = self.snapshot; + let scope = self.scope; + let name = self.name; + + heap.tracker.on_turn_start(); + let (converted, vm_state) = + HeapReader::with(&mut heap, &mut (&mut executor, print), |reader, (executor, print)| { + // Restore the VM first, then convert inside its lifetime + let mut vm = VM::restore( + snapshot_vm_state, + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + + // Resolve the name lookup result with the VM alive + let answer = LookupAnswer::new(result, &mut vm); + let effect = vm.pending_lookup_effect.take(); + let vm_result = resume_lookup(&mut vm, answer, effect, &scope, &name); + + // Three-phase: convert while VM alive, snapshot, build progress + let converted = convert_frame_exit(vm_result, &mut vm); + let vm_state = check_snapshot_from_converted(&converted, vm); + (converted, vm_state) + }); + build_run_progress(converted, vm_state, executor, heap) + } +} + +/// A host's [`NameLookupResult`] in interpreter terms, ready for +/// [`resume_lookup`]. +pub(crate) enum LookupAnswer { + /// The host served this value. + Value(Value), + /// The name / attribute does not exist. + Undefined, + /// Resolving it failed — a host exception, or a value the heap could not + /// take — to be raised in the sandbox where the lookup suspended. + Error(RunError), +} + +impl LookupAnswer { + /// Converts the host's answer while the VM is alive. + /// + /// A value the heap cannot take becomes an in-sandbox error with the + /// mapping [`VM::resume`] applies to external call results: a resource + /// limit raises `MemoryError`, an unconvertible object `RuntimeError`. + pub(crate) fn new(result: NameLookupResult, vm: &mut VM<'_>) -> Self { + match result { + NameLookupResult::Value(obj) => match obj.to_value(vm) { + Ok(value) => Self::Value(value), + Err(InvalidInputError::Resource(err)) => Self::Error(err.into()), + Err(other @ InvalidInputError::InvalidType(_)) => Self::Error( + SimpleException::new( + ExcType::RuntimeError, + Some(format!("invalid name lookup result: {other}")), + ) + .into(), + ), + }, + NameLookupResult::Undefined => Self::Undefined, + NameLookupResult::Error(exc) => Self::Error(exc.into()), + } + } +} + +/// Resumes a suspended lookup with the host's answer and runs on. +/// +/// `effect` is the `hasattr()` / `getattr()` default armed for the lookup, if +/// any. An error is raised as-is, dropping the effect — CPython only swallows +/// `AttributeError` there, and the host reported something else. A served +/// value or `Undefined` goes through the effect when one is armed; otherwise +/// the value is pushed (a namespace lookup also caches it in its slot), or +/// `Undefined` raises the `NameError` / `AttributeError` an unanswered +/// lookup gets. +pub(crate) fn resume_lookup( + vm: &mut VM<'_>, + answer: LookupAnswer, + effect: Option, + scope: &LookupScope, + name: &str, +) -> RunResult { + let value = match (answer, effect) { + (LookupAnswer::Error(err), effect) => { + effect.drop_with(vm); + return vm.resume_with_exception(import_from_error(err, name, vm)); + } + (LookupAnswer::Value(value), Some(effect)) => effect.apply(Some(value), vm), + (LookupAnswer::Undefined, Some(effect)) => effect.apply(None, vm), + (LookupAnswer::Value(value), None) => { + if let LookupScope::Namespace { + namespace_slot, + is_global, + } = scope + { + // Cache the resolved value in the appropriate slot + let slot_idx = *namespace_slot as usize; + let cloned = value.clone_with_heap(vm); + let slot = if *is_global { + &mut vm.globals[slot_idx] + } else { + let stack_base = vm.current_stack_base(); + &mut vm.stack[stack_base + slot_idx] + }; + let old = mem::replace(slot, cloned); + old.drop_with(vm); + } + value + } + (LookupAnswer::Undefined, None) => { + return vm.resume_with_exception(import_from_error(undefined_lookup_error(scope, name), name, vm)); + } + }; + vm.push(value); + vm.run_external() +} + +/// Converts missing import attributes to `ImportError` for `from` imports or +/// `ModuleNotFoundError` for dotted modules, matching synchronous loads. +/// Other errors and non-import lookups pass through unchanged. +fn import_from_error(err: RunError, name: &str, vm: &VM<'_>) -> RunError { + let RunError::Exc(exc) = &err else { + return err; + }; + if exc.exc.exc_type() != ExcType::AttributeError { + return err; + } + if let Some(module) = vm.suspended_import_from() { + ExcType::cannot_import_name(name, vm.interns.get_str(module)) + } else if let Some(path) = vm.suspended_submodule() { + ExcType::module_not_found_error(vm.interns.get_str(path), None) + } else { + err + } +} + +/// Answers every lookup exit no host will serve — the non-iterative paths — +/// as `Undefined`, running on until execution reaches some other exit. +/// +/// An armed `hasattr()` / `getattr()` effect yields `False` / its default; a +/// bare name or attribute read raises `NameError` / `AttributeError` through +/// the VM so the traceback is captured. Any other exit passes through. +pub(crate) fn answer_unserved_lookups(mut result: RunResult, vm: &mut VM<'_>) -> RunResult { + loop { + let (scope, name, effect) = match result? { + FrameExit::NameLookup { + name_id, + namespace_slot, + is_global, + } => { + let scope = LookupScope::Namespace { + namespace_slot, + is_global, + }; + (scope, vm.interns.get_str(name_id).to_owned(), None) + } + FrameExit::AttrLookup { + name, + class_name, + object_id, + type_object, + effect, + } => { + let scope = LookupScope::Attr { + object_id, + class_name, + type_object, + }; + (scope, name.into_string(vm.interns), effect) + } + other => return Ok(other), + }; + result = resume_lookup(vm, LookupAnswer::Undefined, effect, &scope, &name); + } +} + +/// The exception an `Undefined` answer raises: `NameError` for a plain name +/// lookup, `AttributeError` naming the real class for an instance attribute. +fn undefined_lookup_error(scope: &LookupScope, name: &str) -> RunError { + match scope { + LookupScope::Namespace { .. } => ExcType::name_error(name).into(), + LookupScope::Attr { + class_name, + type_object: false, + .. + } => ExcType::attribute_error(class_name, name), + LookupScope::Attr { + class_name, + type_object: true, + .. + } => ExcType::attribute_error_type(class_name, name), + } +} + +// --------------------------------------------------------------------------- +// ResolveFutures +// --------------------------------------------------------------------------- + +/// Execution state paused while waiting for external future results. +/// +/// Supports incremental resolution — you can provide partial results and Monty +/// will continue running until all tasks are blocked again. +/// +/// Use [`pending_call_ids`](Self::pending_call_ids) to see which calls are pending, then call +/// [`resume`](Self::resume) with some or all of the results. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct ResolveFutures { + /// The executor containing compiled code and interns. + executor: Executor, + /// The VM state containing stack, frames, globals, and exception state. + vm_state: VMSnapshot, + /// The heap containing all allocated objects. + heap: Heap, + /// The pending call_ids that this snapshot is waiting on. + pending_call_ids: Vec, + /// Where the main task's blocked `await` is in the source. + position: SourceRange, +} + +impl ResolveFutures { + /// Creates a new `ResolveFutures` from its parts. + fn new( + executor: Executor, + vm_state: VMSnapshot, + heap: Heap, + pending_call_ids: Vec, + position: SourceRange, + ) -> Self { + Self { + executor, + vm_state, + heap, + pending_call_ids, + position, + } + } + + /// Returns unresolved call IDs for this suspended state. + #[must_use] + pub fn pending_call_ids(&self) -> &[u32] { + &self.pending_call_ids + } + + /// Returns where the main task's blocked `await` is in the source. + #[must_use] + pub fn position(&self) -> &SourceRange { + &self.position + } + + /// Returns the resource tracker while execution is suspended. + #[must_use] + pub fn tracker(&self) -> &ResourceTracker { + &self.heap.tracker + } + + /// Aborts with an uncatchable exception and abandons pending futures. + pub fn abort(self, exc: MontyException, print: PrintWriter<'_>) -> Result { + let Self { + executor, + vm_state, + heap, + .. + } = self; + abort_restored(executor, vm_state, heap, exc, print) + } + + /// Forces a GC cycle against the exact root walk used by the live VM. + /// + /// This is test-only support for reproducing GC bugs while execution is + /// suspended in a `ResolveFutures` snapshot. The method round-trips through + /// `VM::restore()` and `VM::snapshot()` so the production scheduler/stack root + /// logic is exercised rather than duplicated in the test. + #[cfg(feature = "test-hooks")] + #[doc(hidden)] + #[must_use] + pub fn __force_gc_for_tests(self) -> Self { + let Self { + mut executor, + vm_state, + mut heap, + pending_call_ids, + position, + } = self; + + let vm_state = HeapReader::with(&mut heap, &mut executor, |reader, executor| { + let mut vm = VM::restore( + vm_state, + &mut executor.tables, + &executor.program, + reader, + PrintWriter::Stdout, + ); + vm.__force_gc_for_tests(); + vm.snapshot() + }); + + Self::new(executor, vm_state, heap, pending_call_ids, position) + } + + /// Number of tasks still live while this snapshot is suspended. + /// + /// Test-only: lets a test assert that a gather child whose external call + /// failed was dropped rather than left parked forever on a future that + /// can no longer be resolved. + #[cfg(feature = "test-hooks")] + #[doc(hidden)] + #[must_use] + pub fn __live_task_count_for_tests(&self) -> usize { + self.vm_state.live_task_count() + } + + /// Resumes execution with results for some or all pending futures. + /// + /// **Incremental resolution**: You don't need to provide all results at once. + /// If you provide a partial list, Monty will: + /// 1. Mark those futures as resolved + /// 2. Unblock any tasks waiting on those futures + /// 3. Continue running until all tasks are blocked again + /// 4. Return [`ResolveFutures`] with the remaining pending calls + /// + /// # Arguments + /// * `results` — List of `(call_id, result)` pairs. Can be a subset of pending calls. + /// * `print` — Writer for print output. + /// + /// # Errors + /// Returns [`MontyException`] if any `call_id` in `results` is not in the pending set. + pub fn resume( + self, + results: Vec<(u32, ExtFunctionResult)>, + print: PrintWriter<'_>, + ) -> Result { + let Self { + mut executor, + vm_state, + mut heap, + pending_call_ids, + .. + } = self; + + // Validate that all provided call_ids are in the pending set before restoring VM. + let invalid_call_id = results + .iter() + .find(|(call_id, _)| !pending_call_ids.contains(call_id)) + .map(|(call_id, _)| *call_id); + + heap.tracker.on_turn_start(); + let (converted, vm_state) = + HeapReader::with(&mut heap, &mut (&mut executor, print), |reader, (executor, print)| { + // Restore the VM from the snapshot (must happen before any error return to clean up properly). + let mut vm = VM::restore( + vm_state, + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + + // Now check for invalid call_ids after VM is restored. + if let Some(call_id) = invalid_call_id { + return Err(MontyException::runtime_error(format!( + "unknown call_id {call_id}, expected one of: {pending_call_ids:?}" + ))); + } + + let result = vm.resume_with_resolved_futures(results); + + // Three-phase: convert while VM alive, snapshot, build progress + let converted = convert_frame_exit(result, &mut vm); + let vm_state = check_snapshot_from_converted(&converted, vm); + Ok((converted, vm_state)) + })?; + build_run_progress(converted, vm_state, executor, heap) + } +} + +// --------------------------------------------------------------------------- +// Snapshot (pub(crate)) +// --------------------------------------------------------------------------- + +/// Internal execution state that can be resumed after suspension. +/// +/// This is a `pub(crate)` implementation detail wrapped by the per-variant +/// structs (`FunctionCall`, `OsCall`, `NameLookup`). It is not exposed in the +/// public API. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct Snapshot { + /// The executor containing compiled code and interns. + pub(crate) executor: Executor, + /// The VM state containing stack, frames, globals, and exception state. + pub(crate) vm_state: VMSnapshot, + /// The heap containing all allocated objects. + pub(crate) heap: Heap, +} + +impl Snapshot { + /// Continues execution with the return value or exception from the external call. + pub(crate) fn run( + self, + result: impl Into, + print: PrintWriter<'_>, + ) -> Result { + self.run_inner(result.into(), None, print) + } + + /// Shared body of [`Self::run`] and [`FunctionCall::resume_eager`]; + /// `eager_call_id` is set only for the latter. + fn run_inner( + self, + ext_result: ExtFunctionResult, + eager_call_id: Option, + print: PrintWriter<'_>, + ) -> Result { + let Self { + mut executor, + vm_state, + mut heap, + } = self; + + heap.tracker.on_turn_start(); + let (converted, vm_state) = + HeapReader::with(&mut heap, &mut (&mut executor, print), |reader, (executor, print)| { + let mut vm = VM::restore( + vm_state, + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + + let vm_result = resume_with_result(&mut vm, ext_result, eager_call_id); + + // Three-phase: convert while VM alive, snapshot, build progress + let converted = convert_frame_exit(vm_result, &mut vm); + let vm_state = check_snapshot_from_converted(&converted, vm); + (converted, vm_state) + }); + build_run_progress(converted, vm_state, executor, heap) + } + + /// Raises `exc` uncatchably at the suspension point. + pub(crate) fn abort(self, exc: MontyException, print: PrintWriter<'_>) -> Result { + let Self { + executor, + vm_state, + heap, + } = self; + abort_restored(executor, vm_state, heap, exc, print) + } +} + +/// Feeds the host's answer to a paused external or OS call into the restored +/// VM and runs on. Shared by the one-shot and REPL resume paths so both treat +/// every [`ExtFunctionResult`] the same way. +/// +/// `eager_call_id` marks a coroutine the host already settled at an eligible +/// `await` (see [`FunctionCall::resume_eager`]): the call's future is +/// registered and resolved in one step, so the `Await` that follows finds it +/// settled without a `ResolveFutures` round trip. +/// +/// Calls whose result must be postprocessed before execution continues +/// (`os.chdir`, `Path.iterdir`, `open`) refuse a future: the effect runs in +/// `VM::resume`, which a future bypasses. The future is not registered, so +/// nothing waits on a call id no task will ever await. +pub(crate) fn resume_with_result( + vm: &mut VM<'_>, + result: ExtFunctionResult, + eager_call_id: Option, +) -> Result { + if let Some(module_id) = vm.suspended_import() { + return resume_import(vm, module_id, result, eager_call_id); + } + // An eager answer and a future both register the call's future; the + // eager one settles it in the same step. + let future_call_id = match (&result, eager_call_id) { + (_, Some(call_id)) => Some(call_id), + (ExtFunctionResult::Future(call_id), None) => Some(*call_id), + _ => None, + }; + match (result, future_call_id) { + (result, Some(call_id)) => { + if let Some(name) = vm + .pending_effect + .as_ref() + .and_then(PendingEffect::immediate_result_name) + { + return vm.resume_with_exception( + SimpleException::new_msg( + ExcType::RuntimeError, + format!("{name} cannot be answered with a future"), + ) + .into(), + ); + } + // `asyncio.sleep` hands its result to the awaitable; no other + // effect survives a future answer. + match vm.pending_effect.take() { + Some(PendingEffect::Post(PostConversionEffect::SleepResult { result })) => { + vm.add_pending_sleep(CallId::new(call_id), result); + } + effect => { + release_pending_effect(effect, vm.heap); + vm.add_pending_call(CallId::new(call_id)); + } + } + if eager_call_id.is_some() { + vm.apply_future_results(vec![(call_id, result)])?; + } + vm.run_external() + } + (ExtFunctionResult::Return(obj), None) => vm.resume(obj), + (ExtFunctionResult::Error(exc), None) => vm.resume_with_exception(exc.into()), + (ExtFunctionResult::NotFound(function_name), None) => { + vm.resume_with_exception(ExtFunctionResult::not_found_exc(&function_name)) + } + (ExtFunctionResult::Future(_), None) => unreachable!("a future answer always carries its call id"), + } +} + +/// Resumes an import with the host's module value or raises its exception without carets. +/// `NotFound` raises `ModuleNotFoundError`; futures are rejected because imports cannot await. +fn resume_import( + vm: &mut VM<'_>, + module_id: StringId, + result: ExtFunctionResult, + eager_call_id: Option, +) -> Result { + match (result, eager_call_id) { + (ExtFunctionResult::Return(obj), None) => vm.resume(obj), + (ExtFunctionResult::Error(exc), None) => { + let mut raise = ExceptionRaise::from(exc); + raise.hide_caret = true; + vm.resume_with_exception(RunError::Exc(raise)) + } + (ExtFunctionResult::NotFound(_), None) => { + vm.resume_with_exception(ExcType::module_not_found_error(vm.interns.get_str(module_id), None)) + } + (ExtFunctionResult::Future(_), _) | (_, Some(_)) => { + let message = format!( + "import of '{}' cannot be answered with a future", + vm.interns.get_str(module_id) + ); + vm.resume_with_exception(SimpleException::new_msg(ExcType::RuntimeError, message).into()) + } + } +} + +/// Restores the VM and aborts uncatchably, rolling back any armed OS effect. +fn abort_restored( + mut executor: Executor, + vm_state: VMSnapshot, + mut heap: Heap, + exc: MontyException, + print: PrintWriter<'_>, +) -> Result { + heap.tracker.on_turn_start(); + let (converted, vm_state) = + HeapReader::with(&mut heap, &mut (&mut executor, print), |reader, (executor, print)| { + let mut vm = VM::restore( + vm_state, + &mut executor.tables, + &executor.program, + reader, + print.reborrow(), + ); + let vm_result = vm.abort(exc); + let converted = convert_frame_exit(vm_result, &mut vm); + let vm_state = check_snapshot_from_converted(&converted, vm); + (converted, vm_state) + }); + build_run_progress(converted, vm_state, executor, heap) +} + +pub use monty_types::{ExtFunctionResult, NameLookupResult}; + +/// Crate-internal extension for [`ExtFunctionResult`] (which lives in +/// `monty-types`): builds the interpreter-side `RunError` for a missing +/// external function. +pub(crate) trait ExtFunctionResultExt { + /// The `NameError` raised when the host reports the function isn't defined. + fn not_found_exc(function_name: &str) -> RunError { + let msg = format!("name '{function_name}' is not defined"); + MontyException::new(ExcType::NameError, Some(msg)).into() + } +} + +impl ExtFunctionResultExt for ExtFunctionResult {} + +// --------------------------------------------------------------------------- +// handle_vm_result +// --------------------------------------------------------------------------- + +/// Pre-converted frame exit data, produced while the VM is still alive. +/// +/// This intermediate enum holds `MontyObject`s and `String`s instead of `Value`s +/// and `StringId`s. It exists to separate the conversion phase (needs `&mut VM`) +/// from the snapshot/progress construction phase (needs owned `Heap`). +pub(crate) enum ConvertedExit { + /// Execution completed with a final result. + Complete(MontyObject), + /// External function call, or a host-routed method call (`object_id` + /// set; construction of a host class is a `__call__` method call). + FunctionCall { + function_name: String, + args: CallArgs, + call_id: u32, + object_id: Option, + allow_eager_await: bool, + /// The call expression. + position: SourceRange, + }, + /// OS-level operation. + OsCall { + function_call: OsFunctionCall, + call_id: u32, + /// See [`OsCall::allow_eager_await`]. + allow_eager_await: bool, + position: SourceRange, + }, + /// All async tasks are blocked waiting for external futures. + ResolveFutures { + pending_call_ids: Vec, + /// The main task's blocked `await`. + position: SourceRange, + }, + /// Unresolved name lookup or lazy instance attribute lookup. + NameLookup { + name: String, + scope: LookupScope, + position: SourceRange, + }, + /// Runtime error. + Error(RunError), +} + +impl ConvertedExit { + /// Returns true if this exit requires a VM snapshot for later resumption. + pub(crate) fn needs_snapshot(&self) -> bool { + !matches!(self, Self::Complete(_) | Self::Error(_)) + } +} + +/// Converts a `FrameExit` into a `ConvertedExit` while the VM is still alive. +/// +/// All `Value` → `MontyObject` and `StringId` → `String` conversions happen here, +/// while the VM (and its heap/interns) are still accessible. +pub(crate) fn convert_frame_exit(result: RunResult, vm: &mut VM<'_>) -> ConvertedExit { + // An effect still armed on arrival belongs to an OS call that was answered + // without consuming it — an eager `resume_with_resolved_futures` never + // takes it. It can never apply to whatever suspends next, so release it + // here rather than let it reshape an unrelated result (or leak what it + // holds when the next OS call overwrites the slot). + // Arming for *this* exit happens below, after the slot is clear. + release_pending_effect(vm.pending_effect.take(), vm.heap); + vm.pending_lookup_effect.take().drop_with(vm.heap); + // `instruction_ip` still names the opcode that suspended, so the current + // position is the suspending expression for every exit but `ResolveFutures`. + match result { + Ok(FrameExit::Return(value)) => ConvertedExit::Complete(MontyObject::export(value, vm)), + Ok(FrameExit::ExternalCall { + function_name, + args, + call_id, + .. + }) => { + let position = vm.suspension_position(); + let name = function_name.into_string(vm.interns); + let args = args.into_call_args(vm); + ConvertedExit::FunctionCall { + function_name: name, + args, + call_id: call_id.raw(), + object_id: None, + allow_eager_await: vm.allow_eager_await(), + position, + } + } + Ok(FrameExit::OsCall { + function_call, + call_id, + effect, + }) => { + let position = vm.suspension_position(); + // The point of no return: the call is the host's, so a matching + // `resume` is guaranteed. Every other destination drops it. + vm.pending_effect = effect; + // Only a call a future may answer can be answered eagerly. + let allow_eager_await = OsFunctionCall::accepts_future(function_call.name()) && vm.allow_eager_await(); + ConvertedExit::OsCall { + function_call, + call_id: call_id.raw(), + allow_eager_await, + position, + } + } + Ok(FrameExit::MethodCall { + method_name, + args, + call_id, + object_id, + }) => { + let position = vm.suspension_position(); + let name = method_name.into_string(vm.interns); + let args = args.into_call_args(vm); + ConvertedExit::FunctionCall { + function_name: name, + args, + call_id: call_id.raw(), + object_id: Some(object_id), + allow_eager_await: vm.allow_eager_await(), + position, + } + } + Ok(FrameExit::ResolveFutures(pending_call_ids)) => ConvertedExit::ResolveFutures { + pending_call_ids: pending_call_ids.iter().map(|id| id.raw()).collect(), + position: vm.main_task_position(), + }, + Ok(FrameExit::NameLookup { + name_id, + namespace_slot, + is_global, + }) => { + let position = vm.suspension_position(); + let name = vm.interns.get_str(name_id).to_owned(); + ConvertedExit::NameLookup { + name, + scope: LookupScope::Namespace { + namespace_slot, + is_global, + }, + position, + } + } + Ok(FrameExit::AttrLookup { + name, + class_name, + object_id, + type_object, + effect, + }) => { + let position = vm.suspension_position(); + // The lookup is the host's now, so a `resume` is guaranteed to + // consume the effect (or the next `convert_frame_exit` releases it). + vm.pending_lookup_effect = effect; + ConvertedExit::NameLookup { + name: name.into_string(vm.interns), + scope: LookupScope::Attr { + object_id, + class_name, + type_object, + }, + position, + } + } + Err(err) => ConvertedExit::Error(err), + } +} + +/// Decides whether to snapshot or clean up the VM based on the converted exit. +/// +/// Consumes the VM. Returns `Some(VMSnapshot)` for suspendable exits, `None` for +/// completion/error (in which case the VM's `Drop` impl handles cleanup). +pub(crate) fn check_snapshot_from_converted(converted: &ConvertedExit, vm: VM<'_>) -> Option { + if converted.needs_snapshot() { + Some(vm.snapshot()) + } else { + None + } +} + +/// Assembles a `RunProgress` from already-converted data and owned heap. +/// +/// This runs after the VM has been dropped (releasing the heap borrow), +/// so the heap can be moved into `Snapshot` structs. +pub(crate) fn build_run_progress( + converted: ConvertedExit, + vm_state: Option, + executor: Executor, + heap: Heap, +) -> Result { + macro_rules! new_snapshot { + () => { + Snapshot { + executor, + vm_state: vm_state.expect("snapshot should exist"), + heap, + } + }; + } + + match converted { + ConvertedExit::Complete(obj) => Ok(RunProgress::Complete(obj)), + ConvertedExit::FunctionCall { + function_name, + args, + call_id, + object_id, + allow_eager_await, + position, + } => Ok(RunProgress::FunctionCall(FunctionCall::new( + function_name, + args, + call_id, + object_id, + allow_eager_await, + position, + new_snapshot!(), + ))), + ConvertedExit::OsCall { + function_call, + call_id, + allow_eager_await, + position, + } => Ok(RunProgress::OsCall(OsCall::new( + function_call, + call_id, + allow_eager_await, + position, + new_snapshot!(), + ))), + ConvertedExit::ResolveFutures { + pending_call_ids, + position, + } => Ok(RunProgress::ResolveFutures(ResolveFutures::new( + executor, + vm_state.expect("snapshot should exist for ResolveFutures"), + heap, + pending_call_ids, + position, + ))), + ConvertedExit::NameLookup { name, scope, position } => Ok(RunProgress::NameLookup(NameLookup::new( + name, + position, + scope, + new_snapshot!(), + ))), + ConvertedExit::Error(err) => { + Err(err.into_python_exception(&executor.tables.interns, |_| Some(&*executor.program.code))) + } + } +} diff --git a/crates/bashkit-monty/src/sorting.rs b/crates/bashkit-monty/src/sorting.rs new file mode 100644 index 000000000..371ec4abd --- /dev/null +++ b/crates/bashkit-monty/src/sorting.rs @@ -0,0 +1,171 @@ +//! Shared sorting utilities for `sorted()` and `list.sort()`. +//! +//! Both `sorted()` and `list.sort()` use index-based sorting: they build +//! a vector of indices `[0, 1, 2, ...]`, sort the indices by comparing the +//! corresponding items (or key values), then rearrange items according to +//! the sorted indices. +//! +//! This module provides [`sort_indices`] for the comparison step and +//! [`apply_permutation`] for the in-place rearrangement step. + +use std::cmp::Ordering; + +use crate::{ + args::{ArgValues, FromArgs, LaxBool}, + bytecode::VM, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + types::{CmpOrder, PyTrait}, + value::Value, +}; + +/// Argument shape for `list.sort(*, key=None, reverse=False)` and, by +/// extension, the kwargs accepted by the `sorted()` builtin. Both fields +/// are keyword-only (CPython rejects positional `key`/`reverse`). `key` is +/// held as a raw `Option` so callers can normalise `key=None` to +/// "no key"; `reverse` uses [`LaxBool`] to match CPython's `bool()`-style +/// truth test (so `reverse=[]` is `False`, not a `TypeError`). +#[derive(FromArgs)] +#[from_args(name = "sort")] +struct ListSortArgs { + #[from_args(kw_only, default)] + key: Option, + #[from_args(kw_only, default = LaxBool::new(false))] + reverse: LaxBool, +} + +/// Parses `key`/`reverse` kwargs and sorts `items` in place. The single +/// entry point for sorting used by both `list.sort` and the `sorted()` +/// builtin — sharing here is what makes unknown-kwarg errors uniformly +/// read `sort() got an unexpected keyword argument 'X'` (matching +/// CPython, whose `sorted` delegates to `list.sort` internally). +pub fn parse_and_sort(items: &mut [Value], args: ArgValues, vm: &mut VM<'_>) -> RunResult<()> { + let ListSortArgs { key, reverse } = ListSortArgs::from_args(args, vm)?; + let key_fn = match key { + Some(v) if matches!(v, Value::None) => { + v.drop_with(vm); + None + } + other => other, + }; + defer_drop!(key_fn, vm); + sort_values(items, key_fn.as_ref(), reverse.bool(), vm) +} + +/// Sorts a vector of values, with optional key function. +pub fn sort_values(values: &mut [Value], key_fn: Option<&Value>, reverse: bool, vm: &mut VM<'_>) -> RunResult<()> { + if let Some(f) = key_fn { + // Sort by key function: compute all the keys, sort an index buffer, then + // rearrange the original values in-place according to the sorted indices. + let mut indices = (0..values.len()).collect::>(); + let keys: Vec = Vec::with_capacity(values.len()); + defer_drop_mut!(keys, vm); + + // Each key call re-enters `run()` with a fresh dispatch countdown, so a + // short key reaches no checkpoint: this is the pass's only clock poll. + for (i, item) in values.iter().enumerate() { + vm.heap.tracker.check_time_every(i)?; + let item = item.clone_with_heap(vm); + keys.push(vm.evaluate_function(f, ArgValues::One(item))?); + } + + // 2. Sort indices by comparing key values (or values themselves if no key) + sort_indices(&mut indices, keys, reverse, vm)?; + + // 3. Rearrange values in-place in the detached buffer. + apply_permutation(values, &mut indices); + + Ok(()) + } else { + // With no key function can sort directly on the original array + let mut sort_result: RunResult<()> = Ok(()); + let mut n = 0usize; + values.sort_by(|a, b| { + n += 1; + compare_values(n, a, b, reverse, &mut sort_result, vm) + }); + sort_result + } +} + +/// Sorts a vector of indices by comparing items at those positions. +/// +/// Compares `values[a]` vs `values[b]` using `py_cmp`, optionally reversing +/// the ordering. If any comparison fails (type error or runtime error), the +/// sort finishes early and the error is returned. +/// +/// The `values` slice is typically either the items themselves (no key function) +/// or the pre-computed key values. +pub fn sort_indices(indices: &mut [usize], values: &[Value], reverse: bool, vm: &mut VM<'_>) -> Result<(), RunError> { + let mut sort_result: RunResult<()> = Ok(()); + let mut n = 0usize; + indices.sort_by(|&a, &b| { + n += 1; + compare_values(n, &values[a], &values[b], reverse, &mut sort_result, vm) + }); + sort_result +} + +/// Rearranges `items` in-place according to a permutation of indices. +/// +/// After calling this, `items[i]` will hold the element that was originally at +/// `items[indices[i]]`. The algorithm chases permutation cycles and swaps +/// elements into their final positions, using O(1) extra memory beyond the +/// `indices` slice (which is mutated to track visited positions). +/// +/// The helper is generic so callers can avoid allocating a second buffer when +/// reordering either raw `Value`s or compound structures that already own their +/// contents. Each element is moved at most twice (one swap = two moves), so +/// the total work is O(n) moves while preserving the target permutation. +pub fn apply_permutation(items: &mut [T], indices: &mut [usize]) { + for i in 0..items.len() { + if indices[i] == i { + continue; + } + let mut current = i; + loop { + let target = indices[current]; + indices[current] = current; + if target == i { + break; + } + items.swap(current, target); + current = target; + } + } +} + +/// Helper for the sort functions which compares two values, handling any exceptions and timeouts. +/// `n` is the caller's running comparison count, keying the amortized time check. +fn compare_values( + n: usize, + a: &Value, + b: &Value, + reverse: bool, + sort_result: &mut RunResult<()>, + vm: &mut VM<'_>, +) -> Ordering { + if sort_result.is_err() { + // short-circuit if we've already encountered an error in a previous comparison + return Ordering::Equal; + } + if let Err(e) = vm.heap.tracker.check_time_every(n) { + *sort_result = Err(e.into()); + return Ordering::Equal; + } + let err = match a.py_cmp(b, vm) { + Ok(CmpOrder::Ordered(ord)) => return if reverse { ord.reverse() } else { ord }, + // A `NaN` (or `NaN`-carrying container) has no ordering but must not + // raise: CPython's `sorted`/`list.sort` leave such elements wherever the + // comparisons happen to place them. Treat it as "equal" — no swap. + Ok(CmpOrder::Unordered) => return Ordering::Equal, + Ok(CmpOrder::Incomparable) => ExcType::type_error(format!( + "'<' not supported between instances of '{}' and '{}'", + a.py_type_name(vm), + b.py_type_name(vm) + )), + Err(e) => e, + }; + *sort_result = Err(err); + Ordering::Equal +} diff --git a/crates/bashkit-monty/src/source_map.rs b/crates/bashkit-monty/src/source_map.rs new file mode 100644 index 000000000..bcd038314 --- /dev/null +++ b/crates/bashkit-monty/src/source_map.rs @@ -0,0 +1,266 @@ +use std::{collections::HashMap, sync::Arc}; + +use monty_types::{CodeLoc, StackFrame}; + +use crate::{exception_private::RawStackFrame, intern::Interns, parse::CodeRange}; + +/// Lazy resolver from raw byte offsets (stored on every [`CodeRange`]) back to +/// human-readable line/column/preview-line information. +/// +/// Monty's parser stores only byte offsets per AST node to keep the post-parse +/// hot path O(1) per node. `SourceMap` is built once at the diagnostic +/// boundary — when converting an internal error into a public +/// [`MontyException`] — and used to resolve every frame in the traceback. +/// Building it scans the source once to index line starts; with a 100k-line +/// source this is a few hundred microseconds and fires only when an exception +/// is actually raised. +/// +/// Column semantics remain exactly CPython-compatible: columns count Unicode +/// scalar values, not bytes. The ASCII fast path (the overwhelmingly common +/// case for Python source) skips the `chars()` iterator entirely. +pub struct SourceMap<'s> { + source: &'s str, + /// Byte offset of the start of each line. Length equals the number of + /// lines; `line_starts[0]` is always 0. + line_starts: Vec, + /// Cache of preview lines, keyed by 0-based line index. + /// + /// Lets every `StackFrame` referencing the same source line share a + /// single `Arc` allocation rather than each cloning the line into + /// its own `String`. This matters for deep recursion: without the + /// cache, a 1 MiB line referenced by 1000 frames would allocate ~1 GiB; + /// with the cache it allocates ~1 MiB. Built lazily — entries materialize + /// only as `resolve_range` actually requests them. + line_cache: HashMap>, +} + +impl<'s> SourceMap<'s> { + /// Builds a line-start index over `source`. + /// + /// Amortizes across every frame in the traceback — one O(n) scan, then + /// O(log n) lookups per frame. + #[must_use] + pub fn new(source: &'s str) -> Self { + let mut line_starts = Vec::with_capacity(source.len() / 40 + 1); + line_starts.push(0); + for (i, b) in source.bytes().enumerate() { + if b == b'\n' { + // source should never exceed 4 GB + let start = u32::try_from(i + 1).unwrap_or(u32::MAX); + line_starts.push(start); + } + } + Self { + source, + line_starts, + line_cache: HashMap::new(), + } + } + + /// Resolves a `CodeRange` into `(start, end, preview_line)`. + /// + /// When `start` and `end` lie on the same line, `preview_line` is that + /// single source line. The returned `Arc` is shared with any other + /// frame in this traceback resolving to the same line, so repeated + /// lookups for the same line are O(1) and allocate only on the first + /// lookup. + /// + /// When the range spans multiple lines, `preview_line` holds a + /// pre-rendered CPython-style block (see + /// [`multiline_preview`](Self::multiline_preview)); the renderer + /// distinguishes the two cases by comparing `start`/`end` lines. + pub(crate) fn resolve_range(&mut self, range: CodeRange) -> (CodeLoc, CodeLoc, Option>) { + let (start_line_idx, start) = self.resolve_byte(range.start_byte); + let (end_line_idx, end) = self.resolve_byte(range.end_byte); + let preview_line = if start_line_idx == end_line_idx { + // Cache materializes lazily — first request for a given line allocates + // the `Arc`, subsequent requests for the same line clone the Arc. + let line_text = self.line_text(start_line_idx); + Some(Arc::clone( + self.line_cache + .entry(start_line_idx) + .or_insert_with(|| Arc::from(line_text)), + )) + } else { + // Multi-line ranges are rare (e.g. a traceback frame covering a + // whole `class` statement), so no caching. + Some(Arc::from(self.multiline_preview(start_line_idx, end_line_idx))) + }; + (start, end, preview_line) + } + + /// Renders the source preview for a range spanning several lines, + /// mirroring CPython's traceback formatting: all lines when the range + /// covers at most three, otherwise the first and last around a + /// `......` elision marker. Displayed lines are dedented by + /// their common leading whitespace; the caller adds the 4-space frame + /// indent (and no caret markers — CPython omits them for these + /// full-statement ranges). + fn multiline_preview(&self, start_line_idx: usize, end_line_idx: usize) -> String { + let total = end_line_idx - start_line_idx + 1; + let displayed: Vec<&str> = if total <= 3 { + (start_line_idx..=end_line_idx).map(|i| self.line_text(i)).collect() + } else { + vec![self.line_text(start_line_idx), self.line_text(end_line_idx)] + }; + // Common leading-whitespace prefix across non-blank displayed lines, + // comparing actual characters (not just lengths) so mixed tab/space + // indentation never strips mismatched whitespace. + let dedent = displayed + .iter() + .filter(|line| !line.trim().is_empty()) + .map(|line| &line[..line.len() - line.trim_start().len()]) + .reduce(|a, b| common_prefix(a, b)) + .map_or(0, str::len); + let stripped = |line: &str| line.get(dedent..).unwrap_or("").to_owned(); + if total <= 3 { + displayed + .iter() + .map(|line| stripped(line)) + .collect::>() + .join("\n") + } else { + format!( + "{}\n...<{} lines>...\n{}", + stripped(displayed[0]), + total - 2, + stripped(displayed[1]) + ) + } + } + + /// Resolves a raw byte offset to `(0-based line index, CodeLoc)`. + /// + /// Column is the number of Unicode scalar values between the line start + /// and the offset; uses an ASCII fast path when the preceding slice is + /// pure ASCII. + fn resolve_byte(&self, byte: u32) -> (usize, CodeLoc) { + // partition_point(|&s| s <= byte) gives the index of the first line + // whose start is strictly greater than `byte`; subtracting one maps + // `byte` back to the line it actually lies on. + let line_idx = self.line_starts.partition_point(|&s| s <= byte).saturating_sub(1); + let line_start = self.line_starts[line_idx]; + let slice_start = line_start as usize; + let slice_end = (byte as usize).min(self.source.len()); + let slice = &self.source[slice_start..slice_end]; + // Ruff caps source files at 4 GiB, so any byte-based column count fits + // comfortably in `u32`; saturate defensively if that ever changes. + let col = if slice.is_ascii() { + u32::try_from(slice.len()).unwrap_or(u32::MAX) + } else { + u32::try_from(slice.chars().count()).unwrap_or(u32::MAX) + }; + ( + line_idx, + CodeLoc::new(u32::try_from(line_idx).expect("line number exceeds u32"), col), + ) + } + + /// Returns the raw text of a 0-based line index, without the trailing + /// newline. + fn line_text(&self, line_idx: usize) -> &'s str { + let start = self.line_starts[line_idx] as usize; + let end = self + .line_starts + .get(line_idx + 1) + .map_or(self.source.len(), |&next| next.saturating_sub(1) as usize); + // Guard against a trailing empty "line" past the last newline with no + // content (e.g. when `start == source.len()`). + let end = end.max(start); + // Strip a trailing `\r` if the source uses CRLF line endings. + let line = &self.source[start..end]; + line.strip_suffix('\r').unwrap_or(line) + } +} + +/// Returns the longest common prefix of `a` and `b`, always cut on a char +/// boundary. Used by [`SourceMap::multiline_preview`] to find the shared +/// indentation of the displayed lines. +fn common_prefix<'a>(a: &'a str, b: &str) -> &'a str { + let end = a + .char_indices() + .zip(b.chars()) + .find(|&((_, ca), cb)| ca != cb) + // All zipped chars equal: the shorter string is the common prefix, and + // equal chars encode identically so its byte length indexes `a` safely. + .map_or(a.len().min(b.len()), |((i, _), _)| i); + &a[..end] +} + +/// Crate-internal builders for [`StackFrame`] (which lives in `monty-types`): +/// they resolve interned names and raw byte offsets via [`Interns`] / +/// [`SourceMap`], which only exist interpreter-side. +pub(crate) trait StackFrameExt { + /// Builds a runtime `StackFrame` from an internal `RawStackFrame`. + /// + /// Resolves the raw filename/frame-name `StringId`s via `interns` and + /// expands the position's byte offsets to line/column and a preview + /// line via `source_map`. + fn from_raw(f: &RawStackFrame, interns: &Interns, source_map: &mut SourceMap<'_>) -> StackFrame { + let filename = interns.get_filename(f.position.filename).to_string(); + let (start, end, preview_line) = source_map.resolve_range(f.position); + StackFrame { + filename, + start, + end, + frame_name: f.frame_name.map(|id| interns.get_str(id).to_string()), + preview_line, + hide_caret: f.hide_caret, + hide_frame_name: false, + } + } + + /// Builds a `StackFrame` for a `SyntaxError`. + /// + /// Sets `hide_frame_name: true` because CPython's SyntaxError format + /// omits the trailing `, in ` part. + fn from_position_syntax_error(position: CodeRange, filename: &str, source_map: &mut SourceMap<'_>) -> StackFrame { + let (start, end, preview_line) = source_map.resolve_range(position); + StackFrame { + filename: filename.to_string(), + start, + end, + frame_name: None, + preview_line, + hide_caret: false, + hide_frame_name: true, + } + } + + /// Builds a generic `StackFrame` from a `CodeRange` and filename. + /// + /// Used for runtime-style errors raised outside the VM's frame tracking + /// (e.g. parse-phase `NotImplementedError`) where caret markers and the + /// `, in ` suffix are both shown. + fn from_position(position: CodeRange, filename: &str, source_map: &mut SourceMap<'_>) -> StackFrame { + let (start, end, preview_line) = source_map.resolve_range(position); + StackFrame { + filename: filename.to_string(), + start, + end, + frame_name: None, + preview_line, + hide_caret: false, + hide_frame_name: false, + } + } + + /// Builds a `StackFrame` with caret markers suppressed. + /// + /// Used for errors like `ImportError` and `ModuleNotFoundError`, where + /// CPython shows the source preview line but no `~~~` carets beneath it. + fn from_position_no_caret(position: CodeRange, filename: &str, source_map: &mut SourceMap<'_>) -> StackFrame { + let (start, end, preview_line) = source_map.resolve_range(position); + StackFrame { + filename: filename.to_string(), + start, + end, + frame_name: None, + preview_line, + hide_caret: true, + hide_frame_name: false, + } + } +} + +impl StackFrameExt for StackFrame {} diff --git a/crates/bashkit-monty/src/source_nesting.rs b/crates/bashkit-monty/src/source_nesting.rs new file mode 100644 index 000000000..4973307e3 --- /dev/null +++ b/crates/bashkit-monty/src/source_nesting.rs @@ -0,0 +1,427 @@ +//! Pre-parse bound on how deeply ruff's parser may recurse on long sources. +//! +//! ruff grows its parser stack on demand (via `stacker`), in segments the +//! sandbox allocator never sees, so a source of N bytes could otherwise cost +//! O(N) untracked memory before Monty's own nesting check +//! ([`MAX_NESTING_DEPTH`]) ever runs. One lexer pass over-approximates the +//! parser's recursion depth; a source of at most `source_scan_threshold` bytes +//! skips it, its depth being bounded by its length. + +use ruff_python_ast::{ + Expr, Mod, Stmt, StringLiteral, + token::TokenKind, + visitor::{Visitor, walk_expr, walk_stmt}, +}; +use ruff_python_parser::{Mode, ParseOptions, lexer::lex, parse_string_annotation, parse_unchecked}; +use ruff_text_size::{Ranged, TextLen, TextRange}; + +use crate::parse::MAX_NESTING_DEPTH; + +/// Whether `source` can be handed to ruff (or ty) without the parser recursing +/// past [`MAX_NESTING_DEPTH`]; a source of at most `source_scan_threshold` +/// bytes always can. +/// +/// Compilation applies the same test and raises `SyntaxError: Source is too +/// deeply nested`, so hosts that also type-check use this to skip the type +/// checker and let the compiler report the located error. +#[must_use] +pub fn source_within_nesting_bound(source: &str, source_scan_threshold: usize) -> bool { + source.len() <= source_scan_threshold || nesting_bound_exceeded(source, Mode::Module, MAX_NESTING_DEPTH).is_none() +} + +/// Estimates ruff's peak parser recursion from one lexer pass, returning the +/// range of the token at which the estimate first exceeds `limit`. +/// +/// The estimate never undercounts a recursion point (see [`Scanner`]), so a +/// source that passes cannot recurse more than `limit` plus a small constant +/// for operator-precedence climbing. String literals are scanned in turn, +/// since the type checker parses a forward-reference annotation's contents. +pub(crate) fn nesting_bound_exceeded(source: &str, mode: Mode, limit: u16) -> Option { + nesting_bound_exceeded_within(source, mode, u32::from(limit), 0) +} + +/// How many string literals deep the scan follows before rejecting outright; +/// a forward reference rarely quotes even one level inside another. +const MAX_STRING_LITERAL_DEPTH: u8 = 8; + +/// [`nesting_bound_exceeded`] for the contents of a string literal +/// `string_depth` literals deep. +fn nesting_bound_exceeded_within(source: &str, mode: Mode, limit: u32, string_depth: u8) -> Option { + // Every frame [`Scanner`] charges costs at least one byte of source, so a + // source no longer than the limit cannot exceed it; that spares nearly + // every string literal a second lexer. + if source.len() <= limit as usize { + return None; + } + if string_depth > MAX_STRING_LITERAL_DEPTH { + return Some(TextRange::up_to(source.text_len())); + } + let mut lexer = lex(source, mode); + let mut scanner = Scanner::new(limit); + loop { + let kind = lexer.next_token(); + let range = lexer.current_range(); + if kind == TokenKind::EndOfFile { + return None; + } + // ruff parses an annotation from the raw source between the quotes, so + // that slice gets the same estimate as the code around it. + if kind == TokenKind::String + && let Some((contents, mode)) = string_literal_contents(&source[range]) + && nesting_bound_exceeded_within(contents, mode, limit, string_depth + 1).is_some() + { + return Some(range); + } + if scanner.observe(kind) { + return Some(range); + } + } +} + +/// The source between a string literal's quotes and the mode ruff parses an +/// annotation in that form with; `None` for bytes literals, which are never +/// annotations, and for anything the lexer left unterminated. +fn string_literal_contents(literal: &str) -> Option<(&str, Mode)> { + let quote_start = literal.find(['\'', '"'])?; + if literal[..quote_start].contains(['b', 'B']) { + return None; + } + let quoted = &literal[quote_start..]; + let quote = "ed[..1]; + let triple = if quote == "'" { "'''" } else { "\"\"\"" }; + let (closer, mode) = if quoted.starts_with(triple) { + (triple, Mode::ParenthesizedExpression) + } else { + (quote, Mode::Expression) + }; + let inner = quoted.get(closer.len()..quoted.len().checked_sub(closer.len())?)?; + quoted.ends_with(closer).then_some((inner, mode)) +} + +/// Token-by-token model of the frames ruff's parser holds open. +/// +/// ruff recurses on every bracketed expression, prefix operator, `**` right +/// operand, lambda body, conditional `else` branch, f-string format spec, +/// indented block and `case` complex-literal pattern. Each is charged when its +/// token arrives and released when a token proves the frame has returned; +/// anything ambiguous stays charged, so the model only ever overcounts. +struct Scanner { + limit: u32, + /// Open bracket levels, bottom entry being the module or expression itself. + levels: Vec, + /// Open indented blocks. + indent: u32, + /// Whether the previous token can end an operand, making a following + /// `-`, `+`, `*` or `not` binary rather than prefix. + prev_ends_operand: bool, + /// Whether a `case` began the current logical line, so `+` and `-` join + /// complex-literal patterns, which recurse on their right operand. + in_pattern: bool, + /// Open levels (excluding the bottom), indentation and every level's counts. + total: u32, +} + +/// Frames open at one bracket level. +struct Level { + kind: LevelKind, + /// Prefix operators and `**` right operands: any lower-precedence binary + /// operator proves they have returned. + tight: u32, + /// Lambda bodies, `else` branches and format specs: only the level's end + /// or a comma, newline or statement colon proves they have returned. + loose: u32, + /// `lambda` keywords whose `:` has not arrived, so commas are still + /// separating parameters rather than ending a body. + pending_lambdas: u32, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum LevelKind { + /// The module or expression itself. + Top, + /// `(`, `[` or `{` outside an f-string. + Bracket, + /// Between `FStringStart` and `FStringEnd` (or the t-string pair). + FString, + /// A `{...}` replacement field; `in_spec` once its format spec began, + /// where a nested `{` opens another replacement field. + Interpolation { in_spec: bool }, +} + +impl Scanner { + fn new(limit: u32) -> Self { + Self { + limit, + levels: vec![Level::new(LevelKind::Top)], + indent: 0, + prev_ends_operand: false, + in_pattern: false, + total: 0, + } + } + + /// Accounts for one token, returning whether the estimate now exceeds the limit. + fn observe(&mut self, kind: TokenKind) -> bool { + let exceeded = match kind { + TokenKind::Lpar | TokenKind::Lsqb => self.push(LevelKind::Bracket), + TokenKind::Lbrace => { + let kind = match self.top().kind { + LevelKind::FString | LevelKind::Interpolation { in_spec: true } => { + LevelKind::Interpolation { in_spec: false } + } + LevelKind::Top | LevelKind::Bracket | LevelKind::Interpolation { in_spec: false } => { + LevelKind::Bracket + } + }; + self.push(kind) + } + TokenKind::FStringStart | TokenKind::TStringStart => self.push(LevelKind::FString), + TokenKind::Rpar | TokenKind::Rsqb | TokenKind::Rbrace | TokenKind::FStringEnd | TokenKind::TStringEnd => { + self.pop(); + false + } + TokenKind::Indent => { + self.indent += 1; + self.add(1) + } + TokenKind::Dedent => { + if self.indent > 0 { + self.indent -= 1; + self.total -= 1; + } + false + } + // `case 1+1+1:` parses each `+` or `-` as a nested complex literal. + TokenKind::Minus | TokenKind::Plus if self.in_pattern => self.add_tight(1), + // Binary after an operand (`a - b`, `a * b`, `a not in b`), prefix otherwise. + TokenKind::Minus | TokenKind::Plus | TokenKind::Star | TokenKind::Not => { + if self.prev_ends_operand { + self.reset_tight(); + false + } else { + self.add_tight(1) + } + } + // `**` as a binary operator recurses for its right operand; as + // unpacking it is merely overcounted. + TokenKind::Tilde | TokenKind::Await | TokenKind::Yield | TokenKind::Async | TokenKind::DoubleStar => { + self.add_tight(1) + } + TokenKind::Lambda => { + self.top().pending_lambdas += 1; + false + } + // Also lexed for a variable named `case`, where the charge merely overcounts. + TokenKind::Case => { + self.in_pattern = true; + false + } + TokenKind::Colon => self.observe_colon(), + // The `orelse` branch recurses once itself and once for its expression. + TokenKind::Else => self.add_loose(2), + // A comma between `lambda` and its `:` separates parameters. + TokenKind::Comma if self.top().pending_lambdas > 0 => false, + TokenKind::Comma => { + self.reset_level(); + false + } + TokenKind::Newline | TokenKind::Semi => { + self.in_pattern = false; + self.reset_level(); + false + } + // Lower precedence than every prefix operator and `**`, so those frames have returned. + TokenKind::Slash + | TokenKind::DoubleSlash + | TokenKind::Percent + | TokenKind::At + | TokenKind::Vbar + | TokenKind::Amper + | TokenKind::CircumFlex + | TokenKind::LeftShift + | TokenKind::RightShift + | TokenKind::Less + | TokenKind::Greater + | TokenKind::EqEqual + | TokenKind::NotEqual + | TokenKind::LessEqual + | TokenKind::GreaterEqual + | TokenKind::In + | TokenKind::Is + | TokenKind::And + | TokenKind::Or + | TokenKind::If + | TokenKind::For => { + self.reset_tight(); + false + } + _ => false, + }; + self.prev_ends_operand = matches!( + kind, + TokenKind::Name + | TokenKind::Int + | TokenKind::Float + | TokenKind::Complex + | TokenKind::String + | TokenKind::FStringEnd + | TokenKind::TStringEnd + | TokenKind::Rpar + | TokenKind::Rsqb + | TokenKind::Rbrace + | TokenKind::True + | TokenKind::False + | TokenKind::None + | TokenKind::Ellipsis + ); + exceeded + } + + /// A lambda's `:` opens its body; any other colon ends the expression + /// before it, and inside a replacement field opens the format spec. + fn observe_colon(&mut self) -> bool { + let top = self.top(); + if top.pending_lambdas > 0 { + top.pending_lambdas -= 1; + // The body recurses once itself and once for its expression. + self.add_loose(2) + } else { + self.reset_level(); + let top = self.top(); + if let LevelKind::Interpolation { in_spec } = &mut top.kind { + *in_spec = true; + self.add_loose(1) + } else { + false + } + } + } + + fn top(&mut self) -> &mut Level { + self.levels.last_mut().expect("the bottom level is never popped") + } + + fn push(&mut self, kind: LevelKind) -> bool { + self.levels.push(Level::new(kind)); + self.add(1) + } + + fn pop(&mut self) { + if self.levels.len() > 1 { + let level = self.levels.pop().expect("length checked above"); + self.total -= 1 + level.tight + level.loose; + } + } + + fn add_tight(&mut self, frames: u32) -> bool { + self.top().tight += frames; + self.add(frames) + } + + fn add_loose(&mut self, frames: u32) -> bool { + self.top().loose += frames; + self.add(frames) + } + + fn reset_tight(&mut self) { + let top = self.top(); + let released = top.tight; + top.tight = 0; + self.total -= released; + } + + fn reset_level(&mut self) { + let top = self.top(); + let released = top.tight + top.loose; + top.tight = 0; + top.loose = 0; + self.total -= released; + } + + fn add(&mut self, frames: u32) -> bool { + self.total += frames; + self.total > self.limit + } +} + +impl Level { + fn new(kind: LevelKind) -> Self { + Self { + kind, + tight: 0, + loose: 0, + pending_lambdas: 0, + } + } +} + +/// Range of the first expression in `source` nested deeper than `limit`, +/// counting through the contents of string literals as the type checker does. +/// +/// ruff builds arbitrarily deep ASTs from flat source (`1+1+...`, `a.x.x...`, +/// `A | B | ...`) without recursing itself, so [`nesting_bound_exceeded`] +/// passes them; ty then recurses once per level. The caller must already have +/// bounded ruff's own recursion with that scan. +pub(crate) fn ast_depth_exceeded(source: &str, limit: u16) -> Option { + // Recovered from any syntax error, as ty type-checks the recovered AST too. + let parsed = parse_unchecked(source, ParseOptions::from(Mode::Module)); + let mut check = AstDepth { + source, + remaining: limit, + string_depth: 0, + exceeded: None, + }; + if let Mod::Module(module) = parsed.syntax() { + check.visit_body(&module.body); + } + check.exceeded +} + +/// Visitor behind [`ast_depth_exceeded`]; stops descending once over budget, +/// so its own recursion is bounded by the limit. +struct AstDepth<'s> { + source: &'s str, + remaining: u16, + /// String literals currently being walked as parsed annotations. + string_depth: u8, + exceeded: Option, +} + +impl<'a> Visitor<'a> for AstDepth<'_> { + fn visit_stmt(&mut self, stmt: &'a Stmt) { + if self.exceeded.is_none() { + walk_stmt(self, stmt); + } + } + + fn visit_expr(&mut self, expr: &'a Expr) { + if self.exceeded.is_some() { + return; + } + if let Some(remaining) = self.remaining.checked_sub(1) { + self.remaining = remaining; + walk_expr(self, expr); + self.remaining += 1; + } else { + self.exceeded = Some(expr.range()); + } + } + + /// ty parses a string annotation's contents in place, continuing the depth + /// of the expression around it. Any string might be one, so every literal + /// long enough to exceed the remaining budget is parsed. + fn visit_string_literal(&mut self, literal: &'a StringLiteral) { + if self.exceeded.is_some() || literal.range().len().to_usize() <= usize::from(self.remaining) { + return; + } + if self.string_depth >= MAX_STRING_LITERAL_DEPTH { + self.exceeded = Some(literal.range()); + return; + } + if let Ok(parsed) = parse_string_annotation(self.source, literal) { + self.string_depth += 1; + self.visit_expr(parsed.expr()); + self.string_depth -= 1; + } + } +} diff --git a/crates/bashkit-monty/src/str_format.rs b/crates/bashkit-monty/src/str_format.rs new file mode 100644 index 000000000..73189b380 --- /dev/null +++ b/crates/bashkit-monty/src/str_format.rs @@ -0,0 +1,445 @@ +//! Runtime replacement-field handling for `str.format()`. + +use std::{borrow::Cow, fmt}; + +use crate::{ + args::{ArgValues, FromArgs, KwargsValues}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + fstring::decimal_digit_value, + heap::{ContainsHeap, DropGuard, DropWithContext}, + string_builder::StringBuilder, + types::{PyTrait, str::allocate_string}, + value::{EitherStr, Value}, +}; + +const MAX_FORMAT_RECURSION: u8 = 2; + +/// Renders a runtime format string with positional and keyword arguments. +pub(crate) fn str_format(template: &str, args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let FormatCallArgs { positional, keywords } = FormatCallArgs::from_args(args, vm)?; + let keywords = match keywords { + KwargsValues::Pairs(keywords) => keywords, + other => other.into_iter().collect(), + }; + let arguments = FormatArguments { positional, keywords }; + defer_drop!(arguments, vm); + + let mut numbering = Numbering::default(); + let rendered = render(template, arguments, &mut numbering, MAX_FORMAT_RECURSION, vm)?; + Ok(allocate_string(rendered, vm.heap)) +} + +/// Arguments accepted by `str.format()`. +#[derive(FromArgs)] +#[from_args(name = "format")] +struct FormatCallArgs { + #[from_args(varargs)] + positional: Vec, + #[from_args(varkwargs)] + keywords: KwargsValues, +} + +/// Owns call arguments until rendering and error cleanup have finished. +struct FormatArguments { + positional: Vec, + keywords: Vec<(Value, Value)>, +} + +impl DropWithContext for FormatArguments { + fn drop_with(self, ctx: &mut C) { + self.positional.drop_with(ctx); + for (key, value) in self.keywords { + key.drop_with(ctx); + value.drop_with(ctx); + } + } +} + +/// Tracks field numbering across nested format specs. +#[derive(Default)] +struct Numbering { + mode: NumberingMode, + next_auto: usize, +} + +/// Enforces Python's rule against mixing automatic and manual numbering. +#[derive(Default)] +enum NumberingMode { + #[default] + Unknown, + Automatic, + Manual, +} + +/// Renders one format-string level within the recursion and resource limits. +fn render( + template: &str, + arguments: &FormatArguments, + numbering: &mut Numbering, + recursion_remaining: u8, + vm: &mut VM<'_>, +) -> RunResult { + let bytes = template.as_bytes(); + let mut output = String::new(); + let mut literal_start = 0; + let mut index = 0; + let mut steps = 0; + + while index < bytes.len() { + vm.heap.tracker.check_time_every(steps)?; + steps += 1; + match bytes[index] { + b'{' => { + output = push_tracked(output, &template[literal_start..index], vm)?; + if bytes.get(index + 1) == Some(&b'{') { + output = push_tracked(output, "{", vm)?; + index += 2; + } else { + if index + 1 == bytes.len() { + return Err(value_error("Single '{' encountered in format string")); + } + let (formatted, next) = + render_field(template, index + 1, arguments, numbering, recursion_remaining, vm)?; + output = push_tracked(output, &formatted, vm)?; + index = next; + } + literal_start = index; + } + b'}' => { + output = push_tracked(output, &template[literal_start..index], vm)?; + if bytes.get(index + 1) == Some(&b'}') { + output = push_tracked(output, "}", vm)?; + index += 2; + literal_start = index; + } else { + return Err(value_error("Single '}' encountered in format string")); + } + } + _ => index += 1, + } + } + + push_tracked(output, &template[literal_start..], vm) +} + +/// Resolves and formats one replacement field in CPython error order. +fn render_field( + template: &str, + start: usize, + arguments: &FormatArguments, + numbering: &mut Numbering, + recursion_remaining: u8, + vm: &mut VM<'_>, +) -> RunResult<(String, usize)> { + let (field_end, delimiter) = find_field_end(template, start, vm)?; + let mut cursor = field_end; + let conversion = if delimiter == b'!' { + let conversion_start = cursor + 1; + let Some(conversion) = template[conversion_start..].chars().next() else { + return Err(value_error("end of string while looking for conversion specifier")); + }; + cursor = conversion_start + conversion.len_utf8(); + match template.as_bytes().get(cursor) { + Some(b':' | b'}') => {} + None => return Err(value_error("unmatched '{' in format spec")), + _ => return Err(value_error("expected ':' after conversion specifier")), + } + Some(conversion) + } else { + None + }; + + let delimiter = *template + .as_bytes() + .get(cursor) + .ok_or_else(|| value_error("expected '}' before end of string"))?; + let spec_range = match delimiter { + b'}' => None, + b':' => { + let spec_start = cursor + 1; + let (spec_end, needs_expansion) = find_spec_end(template, spec_start, vm)?; + Some((spec_start, spec_end, needs_expansion)) + } + _ => return Err(value_error("expected '}' before end of string")), + }; + + let value = resolve_field(&template[start..field_end], arguments, numbering, vm)?; + defer_drop!(value, vm); + let conversion = match conversion { + None | Some('\0') => None, + Some('s') => Some(1), + Some('r') => Some(2), + Some('a') => Some(3), + Some(other) => { + let other = if other.is_ascii_graphic() { + other.to_string() + } else { + format!("\\x{:x}", u32::from(other)) + }; + return Err(value_error(format!("Unknown conversion specifier {other}"))); + } + }; + let converted = conversion + .map(|conversion| vm.convert_value(value, conversion)) + .transpose()?; + + if let Some((spec_start, spec_end, needs_expansion)) = spec_range { + let raw_spec = &template[spec_start..spec_end]; + // Only a spec containing `{` is expanded, and the expansion itself costs a + // recursion level, escaped braces included, matching CPython's `build_string`. + let spec = if needs_expansion { + if recursion_remaining <= 1 { + return Err(value_error("Max string recursion exceeded")); + } + Cow::Owned(render(raw_spec, arguments, numbering, recursion_remaining - 1, vm)?) + } else { + Cow::Borrowed(raw_spec) + }; + let formatted = if let Some(converted) = &converted { + vm.format_runtime_string(converted, spec.as_ref())? + } else { + vm.format_runtime_value(value, 0, Some(spec.as_ref()))? + }; + Ok((formatted, spec_end + 1)) + } else if let Some(converted) = converted { + Ok((converted, cursor + 1)) + } else { + vm.format_runtime_value(value, 0, None) + .map(|formatted| (formatted, cursor + 1)) + } +} + +/// Finds the first field delimiter outside an item lookup. +fn find_field_end(template: &str, start: usize, vm: &VM<'_>) -> RunResult<(usize, u8)> { + let bytes = template.as_bytes(); + let mut index = start; + let mut in_item = false; + + while index < bytes.len() { + vm.heap.tracker.check_time_every(index)?; + match bytes[index] { + b'[' if !in_item => in_item = true, + b']' if in_item => in_item = false, + b'{' if !in_item => return Err(value_error("unexpected '{' in field name")), + delimiter @ (b'!' | b':' | b'}') if !in_item => return Ok((index, delimiter)), + _ => {} + } + index += 1; + } + Err(value_error("expected '}' before end of string")) +} + +/// Finds the closing brace and whether the spec needs expansion in one checked scan. +fn find_spec_end(template: &str, start: usize, vm: &VM<'_>) -> RunResult<(usize, bool)> { + let bytes = template.as_bytes(); + let mut index = start; + let mut nesting = 0usize; + let mut needs_expansion = false; + + while index < bytes.len() { + vm.heap.tracker.check_time_every(index)?; + match bytes[index] { + b'{' => { + nesting += 1; + needs_expansion = true; + } + b'}' if nesting == 0 => return Ok((index, needs_expansion)), + b'}' => nesting -= 1, + _ => {} + } + index += 1; + } + Err(value_error("unmatched '{' in format spec")) +} + +/// Resolves a root argument followed by attribute or item accesses. +fn resolve_field( + field: &str, + arguments: &FormatArguments, + numbering: &mut Numbering, + vm: &mut VM<'_>, +) -> RunResult { + let first_end = field + .as_bytes() + .iter() + .position(|byte| matches!(byte, b'.' | b'[')) + .unwrap_or(field.len()); + let value = resolve_first(&field[..first_end], arguments, numbering, vm)?; + let mut value = DropGuard::new(value, vm); + let mut cursor = first_end; + let mut access_index = 0; + + while cursor < field.len() { + value.ctx().heap.tracker.check_time_every(access_index)?; + access_index += 1; + match field.as_bytes()[cursor] { + b'.' => { + let start = cursor + 1; + let end = field.as_bytes()[start..] + .iter() + .position(|byte| matches!(byte, b'.' | b'[')) + .map_or(field.len(), |offset| start + offset); + if start == end { + return Err(value_error("Empty attribute in format string")); + } + let (current, vm) = value.into_parts(); + let next = resolve_attribute(current, &field[start..end], vm)?; + value = DropGuard::new(next, vm); + cursor = end; + } + b'[' => { + let start = cursor + 1; + let Some(offset) = field[start..].find(']') else { + return Err(value_error("expected '}' before end of string")); + }; + let end = start + offset; + if start == end { + return Err(value_error("Empty attribute in format string")); + } + let (current, vm) = value.into_parts(); + let next = resolve_item(current, &field[start..end], vm)?; + value = DropGuard::new(next, vm); + cursor = end + 1; + if cursor < field.len() && !matches!(field.as_bytes()[cursor], b'.' | b'[') { + return Err(value_error("Only '.' or '[' may follow ']' in format field specifier")); + } + } + _ => { + return Err(value_error("expected '}' before end of string")); + } + } + } + Ok(value.into_inner()) +} + +/// Resolves the root argument and updates the field-numbering mode. +fn resolve_first( + field: &str, + arguments: &FormatArguments, + numbering: &mut Numbering, + vm: &mut VM<'_>, +) -> RunResult { + if field.is_empty() { + return resolve_auto(arguments, numbering, vm); + } + + match decimal_index(field, vm)? { + Some(index) => { + if matches!(numbering.mode, NumberingMode::Automatic) { + return Err(value_error( + "cannot switch from automatic field numbering to manual field specification", + )); + } + numbering.mode = NumberingMode::Manual; + resolve_positional(index, arguments, vm) + } + None => resolve_keyword(field, arguments, vm), + } +} + +/// Resolves the next automatic positional field. +fn resolve_auto(arguments: &FormatArguments, numbering: &mut Numbering, vm: &VM<'_>) -> RunResult { + if matches!(numbering.mode, NumberingMode::Manual) { + return Err(value_error( + "cannot switch from manual field specification to automatic field numbering", + )); + } + numbering.mode = NumberingMode::Automatic; + let index = numbering.next_auto; + numbering.next_auto = numbering + .next_auto + .checked_add(1) + .ok_or_else(|| value_error("Too many decimal digits in format string"))?; + resolve_positional(index, arguments, vm) +} + +/// Clones a positional argument or raises the replacement-index error. +fn resolve_positional(index: usize, arguments: &FormatArguments, vm: &VM<'_>) -> RunResult { + arguments + .positional + .get(index) + .map(|value| value.clone_with_heap(vm.heap)) + .ok_or_else(|| { + SimpleException::new_msg( + ExcType::IndexError, + format!("Replacement index {index} out of range for positional args tuple"), + ) + .into() + }) +} + +/// Clones a keyword argument or raises `KeyError`. +fn resolve_keyword(name: &str, arguments: &FormatArguments, vm: &mut VM<'_>) -> RunResult { + for (index, (key, value)) in arguments.keywords.iter().enumerate() { + vm.heap.tracker.check_time_every(index)?; + if key.to_str(vm)? == name { + return Ok(value.clone_with_heap(vm.heap)); + } + } + + let key = allocate_string(name, vm.heap); + defer_drop!(key, vm); + Err(ExcType::key_error(key, vm)) +} + +/// Resolves an attribute without allowing a suspending lookup. +fn resolve_attribute(value: Value, name: &str, vm: &mut VM<'_>) -> RunResult { + defer_drop!(value, vm); + match value.py_getattr(&EitherStr::from(name.to_owned()), vm)? { + CallResult::Value(value) => Ok(value), + other => { + other.drop_with(vm); + Err(ExcType::not_implemented("str.format attribute access cannot suspend").into()) + } + } +} + +/// Resolves an integer or string item lookup. +fn resolve_item(value: Value, item: &str, vm: &mut VM<'_>) -> RunResult { + defer_drop!(value, vm); + let key = item_key(item, vm)?; + defer_drop!(key, vm); + value.py_getitem(key, vm) +} + +/// Converts decimal item text to an integer key and other text to a string. +fn item_key(item: &str, vm: &VM<'_>) -> RunResult { + if let Some(index) = decimal_index(item, vm)? { + Ok(Value::Int( + i64::try_from(index).expect("index is bounded by isize::MAX"), + )) + } else { + Ok(allocate_string(item, vm.heap)) + } +} + +/// Parses Unicode decimal digits using Python's field-index rules. +fn decimal_index(field: &str, vm: &VM<'_>) -> RunResult> { + let mut index = 0usize; + for (offset, character) in field.chars().enumerate() { + vm.heap.tracker.check_time_every(offset)?; + let Some(digit) = decimal_digit_value(character) else { + return Ok(None); + }; + index = index + .checked_mul(10) + .and_then(|value| value.checked_add(digit as usize)) + .filter(|value| isize::try_from(*value).is_ok()) + .ok_or_else(|| value_error("Too many decimal digits in format string"))?; + } + Ok(Some(index)) +} + +/// Appends a fragment while preserving `StringBuilder` resource accounting. +pub(crate) fn push_tracked(output: String, text: &str, vm: &VM<'_>) -> RunResult { + let mut builder = StringBuilder::from_existing(output, &vm.heap.tracker); + builder.push_str(text)?; + builder.finish_raw() +} + +/// Builds a `ValueError` for a malformed format string. +pub(crate) fn value_error(message: impl fmt::Display) -> RunError { + SimpleException::new_msg(ExcType::ValueError, message).into() +} diff --git a/crates/bashkit-monty/src/string_builder.rs b/crates/bashkit-monty/src/string_builder.rs new file mode 100644 index 000000000..db455cf11 --- /dev/null +++ b/crates/bashkit-monty/src/string_builder.rs @@ -0,0 +1,284 @@ +//! Resource-tracked builder for `String` values. +//! +//! `StringBuilder` is the canonical way to build a Python-visible string whose +//! final size is not already bounded by an existing input. Operations that grow +//! a `String` in a loop — padding, tab expansion, repetition, container repr, +//! etc. — must use `StringBuilder` rather than unchecked `String` growth. One +//! large reservation could otherwise jump across both allocator limits before +//! execution reaches another checkpoint. +//! +//! # Allocator checks +//! +//! Each capacity increase is preflighted against allocator-backed usage. The +//! in-progress buffer is itself visible to the allocator, including during +//! nested string builds. +//! +//! # Growth policy +//! +//! Capacity doubles on each growth (matching `Vec`'s policy), so an `n`-byte +//! build incurs `O(log n)` tracker calls rather than `O(n)`. Use +//! [`with_capacity`](StringBuilder::with_capacity) when an upper bound is +//! known up front (e.g. padding to a width) — a single check covers every +//! subsequent push. Use [`new`](StringBuilder::new) when the size is +//! not bounded up front. +//! +//! # Two APIs: direct push and `fmt::Write` +//! +//! Callers that build strings imperatively use [`push`](StringBuilder::push) +//! and [`push_str`](StringBuilder::push_str), which return [`ResourceError`] +//! directly. Callers that need to plug into `fmt::Write`-based machinery +//! (`write!`, `format_args!`, the existing `py_repr_fmt` recursion) use the +//! builder's [`fmt::Write`] impl, which captures any [`ResourceError`] into +//! an internal slot since `fmt::Error` is payload-free. The stored error is +//! surfaced automatically by [`finish`](StringBuilder::finish), so the +//! tracker error reaches the caller even when the intermediate +//! `fmt::Error` is swallowed by a downstream formatter. + +use std::{fmt, iter, mem}; + +use monty_types::{ResourceError, ResourceTracker}; + +use crate::{exception_private::RunResult, heap::Heap, types::str::allocate_string, value::Value}; + +/// Resource-tracked builder for a `String`. +/// +/// Holds an inner `String`, its tracker, and the capacity approved so far. +/// Growth is preflighted against real allocator usage before reserving. +/// +/// Typical use: +/// +/// ```ignore +/// let mut builder = StringBuilder::with_capacity(cap, &vm.heap.tracker)?; +/// builder.push_str(prefix)?; +/// for _ in 0..pad { builder.push(fill)?; } +/// builder.finish(vm.heap) +/// ``` +pub struct StringBuilder<'t> { + inner: String, + tracker: &'t ResourceTracker, + /// Capacity already approved by the tracker. + approved_capacity: usize, + /// Tracker error captured during a [`fmt::Write`] call. `fmt::Error` is + /// payload-free, so we stash the real error here and surface it via + /// [`finish`](Self::finish) or [`finish_raw`](Self::finish_raw). Direct + /// callers of [`push`](Self::push) / [`push_str`](Self::push_str) never + /// set this — they receive the [`ResourceError`] in the return value. + pending_error: Option, +} + +impl<'t> StringBuilder<'t> { + /// Creates an empty builder with no pre-approved capacity. + /// + /// Use when the final size is not bounded up front. Each 2× growth is + /// checked before the underlying string reserves more capacity. + pub fn new(tracker: &'t ResourceTracker) -> Self { + Self { + inner: String::new(), + tracker, + approved_capacity: 0, + pending_error: None, + } + } + + /// Existing capacity is already tracker-accounted; only later growth needs preflight. + pub fn from_existing(inner: String, tracker: &'t ResourceTracker) -> Self { + let approved_capacity = inner.capacity(); + Self { + inner, + tracker, + approved_capacity, + pending_error: None, + } + } + + /// Creates a builder with `capacity` bytes reserved up front. + /// + /// Use when the final size is known or bounded (e.g. padding to a given + /// width). One up-front check covers pushes within `capacity`. + pub fn with_capacity(capacity: usize, tracker: &'t ResourceTracker) -> Result { + tracker.check_allocation(capacity)?; + check_string_capacity(capacity)?; + Ok(Self { + inner: String::with_capacity(capacity), + tracker, + approved_capacity: capacity, + pending_error: None, + }) + } + + /// Appends a character after checking any required capacity increase. + pub fn push(&mut self, c: char) -> Result<(), ResourceError> { + let needed = self.inner.len().saturating_add(c.len_utf8()); + self.ensure(needed)?; + self.inner.push(c); + Ok(()) + } + + /// Appends a string slice after checking any required capacity increase. + pub fn push_str(&mut self, s: &str) -> Result<(), ResourceError> { + let needed = self.inner.len().saturating_add(s.len()); + self.ensure(needed)?; + self.inner.push_str(s); + Ok(()) + } + + /// Appends `count` copies of `c`, in chunks with the tracker's clock polled + /// between them so a wide padding request stays interruptible. + pub fn push_repeated(&mut self, c: char, count: usize) -> Result<(), ResourceError> { + let mut remaining = count; + let mut chunk = 0; + while remaining > 0 { + self.tracker.check_time_every(chunk)?; + chunk += 1; + let take = remaining.min(FILL_CHUNK); + self.ensure(self.inner.len().saturating_add(take.saturating_mul(c.len_utf8())))?; + self.inner.extend(iter::repeat_n(c, take)); + remaining -= take; + } + Ok(()) + } + + /// Consumes the builder and allocates the resulting string in `heap`. + /// + /// If a prior [`fmt::Write`] call captured a tracker error, that error is + /// returned instead of the partial string. + pub fn finish(mut self, heap: &Heap) -> RunResult { + if let Some(e) = self.pending_error.take() { + return Err(e.into()); + } + Ok(allocate_string(mem::take(&mut self.inner), heap)) + } + + /// Consumes the builder and returns the raw `String`. + /// + /// Like [`finish`](Self::finish), this surfaces a tracker error captured by + /// `fmt::Write` instead of returning the partial string. + pub fn finish_raw(mut self) -> RunResult { + if let Some(e) = self.pending_error.take() { + return Err(e.into()); + } + Ok(mem::take(&mut self.inner)) + } + + fn ensure(&mut self, needed: usize) -> Result<(), ResourceError> { + approve_growth(&mut self.approved_capacity, needed, self.tracker) + } +} + +/// Resource-tracked builder for a `Vec`: the [`StringBuilder`] +/// counterpart for byte output, with the same preflighted 2× growth. +pub struct BytesBuilder<'t> { + inner: Vec, + tracker: &'t ResourceTracker, + /// Capacity already approved by the tracker. + approved_capacity: usize, +} + +impl<'t> BytesBuilder<'t> { + /// Existing capacity is already tracker-accounted; only later growth needs preflight. + pub fn from_existing(inner: Vec, tracker: &'t ResourceTracker) -> Self { + let approved_capacity = inner.capacity(); + Self { + inner, + tracker, + approved_capacity, + } + } + + /// Creates a builder with `capacity` bytes reserved up front, after one tracker check. + pub fn with_capacity(capacity: usize, tracker: &'t ResourceTracker) -> Result { + tracker.check_allocation(capacity)?; + check_string_capacity(capacity)?; + Ok(Self { + inner: Vec::with_capacity(capacity), + tracker, + approved_capacity: capacity, + }) + } + + /// Appends a byte slice after checking any required capacity increase. + pub fn push_slice(&mut self, bytes: &[u8]) -> Result<(), ResourceError> { + let needed = self.inner.len().saturating_add(bytes.len()); + approve_growth(&mut self.approved_capacity, needed, self.tracker)?; + self.inner.extend_from_slice(bytes); + Ok(()) + } + + /// Appends `count` copies of `byte`, in chunks with the tracker's clock + /// polled between them so a wide padding request stays interruptible. + pub fn push_repeated(&mut self, byte: u8, count: usize) -> Result<(), ResourceError> { + let mut remaining = count; + let mut chunk = 0; + while remaining > 0 { + self.tracker.check_time_every(chunk)?; + chunk += 1; + let take = remaining.min(FILL_CHUNK); + let needed = self.inner.len().saturating_add(take); + approve_growth(&mut self.approved_capacity, needed, self.tracker)?; + self.inner.resize(needed, byte); + remaining -= take; + } + Ok(()) + } + + /// Consumes the builder and returns the bytes. + pub fn finish(self) -> Vec { + self.inner + } +} + +/// Approves growth to `needed` bytes against the tracker, doubling the +/// approved capacity like `Vec` so an n-byte build incurs O(log n) checks. +fn approve_growth(approved: &mut usize, needed: usize, tracker: &ResourceTracker) -> Result<(), ResourceError> { + if needed > *approved { + let new_capacity = approved.saturating_mul(2).max(needed); + tracker.check_allocation(new_capacity - *approved)?; + check_string_capacity(new_capacity)?; + *approved = new_capacity; + } + Ok(()) +} + +const MAX_STRING_CAPACITY: usize = isize::MAX as usize; + +/// Fill bytes appended between tracker clock polls by `push_repeated`. +const FILL_CHUNK: usize = 4096; + +/// A capacity above `isize::MAX` panics inside the reservation itself, before +/// the allocator can refuse it, so both reservation paths fence it here. +fn check_string_capacity(capacity: usize) -> Result<(), ResourceError> { + if capacity > MAX_STRING_CAPACITY { + Err(ResourceError::Memory { + limit: MAX_STRING_CAPACITY, + used: capacity, + }) + } else { + Ok(()) + } +} + +/// `fmt::Write` impl so `write!(builder, ...)` and `format_args!` work +/// against any tracker-protected builder. A tracker rejection is converted +/// into the payload-free [`fmt::Error`] and stashed in `pending_error`; +/// short-circuits subsequent writes after the limit has been hit. +impl fmt::Write for StringBuilder<'_> { + fn write_str(&mut self, s: &str) -> fmt::Result { + if self.pending_error.is_some() { + return Err(fmt::Error); + } + self.push_str(s).map_err(|e| { + self.pending_error = Some(e); + fmt::Error + }) + } + + fn write_char(&mut self, c: char) -> fmt::Result { + if self.pending_error.is_some() { + return Err(fmt::Error); + } + self.push(c).map_err(|e| { + self.pending_error = Some(e); + fmt::Error + }) + } +} diff --git a/crates/bashkit-monty/src/stringize.rs b/crates/bashkit-monty/src/stringize.rs new file mode 100644 index 000000000..3dacf7c0b --- /dev/null +++ b/crates/bashkit-monty/src/stringize.rs @@ -0,0 +1,155 @@ +//! Rendering a ruff AST expression back to source text, the way CPython's +//! PEP 563 stringizer does. +//! +//! The inverse of [`parse`](crate::parse). Class annotations are the only caller +//! today (they are stored stringized, not evaluated — see +//! `limitations/typing.md`), but the contract is "match CPython's stringizer", so +//! any future stringization belongs here. Unparsing rather than slicing the +//! source is what makes `x: dict[str,int]` yield `'dict[str, int]'` on both. + +use ruff_python_ast::{ + self as ast, AtomicNodeIndex, Expr as AstExpr, + str::{Quote, TripleQuotes}, + str_prefix::{ByteStringPrefix, StringLiteralPrefix}, + visitor::transformer::{Transformer, walk_expr, walk_f_string}, +}; +use ruff_python_codegen::{Generator, Indentation}; +use ruff_source_file::LineEnding; + +/// Renders `annotation` to the text CPython's PEP 563 stringizer would produce. +/// +/// Takes `&mut` because canonicalising the literals rewrites them in place. +pub(crate) fn stringize_annotation(annotation: &mut AstExpr) -> String { + // Neither generator mode matches CPython alone: `AstUnparse` normalises quotes + // but parenthesises tuple subscripts (`dict[(str, int)]`), `Default` keeps + // subscripts but echoes the source literals. So canonicalise, then `Default`. + CanonicalStringLiterals.visit_expr(annotation); + // `Lf` is pinned because the default is platform-dependent, and Monty must + // stringize identically everywhere. + Generator::new(&Indentation::default(), LineEnding::Lf).expr(annotation) +} + +/// Rewrites string literals into the single canonical form CPython produces, +/// since the generator otherwise echoes them roughly as written. +/// +/// | annotation | without this | with it (= CPython) | +/// | -------------- | -------------- | ------------------- | +/// | `"foo" "bar"` | `'foo' 'bar'` | `'foobar'` | +/// | `f"x" "y"` | `f'x' 'y'` | `f'xy'` | +/// | `r"raw\d"` | `r'raw\d'` | `'raw\\d'` | +/// | `"""triple"""` | `"""triple"""` | `'triple'` | +/// | `b"foo" b"bar"`| `b"foo" b"bar"`| `b'foobar'` | +struct CanonicalStringLiterals; + +impl Transformer for CanonicalStringLiterals { + // Rebuilding is unconditional: the value is the truth and the spelling noise, + // so there is no unaffected case to preserve. + fn visit_expr(&self, expr: &mut AstExpr) { + match expr { + AstExpr::StringLiteral(s) => rebuild_string_literal(s), + AstExpr::BytesLiteral(b) => rebuild_bytes_literal(b), + AstExpr::FString(f) if f.value.is_implicit_concatenated() => merge_f_string_parts(f), + _ => {} + } + walk_expr(self, expr); + } + + // F-strings cannot be rebuilt from a value — the interpolations are live + // expressions — so only the flags are canonicalised. + fn visit_f_string(&self, f_string: &mut ast::FString) { + f_string.flags = f_string + .flags + .with_quote_style(Quote::Single) + .with_triple_quotes(TripleQuotes::No); + walk_f_string(self, f_string); + } +} + +/// The flags CPython effectively renders a `str` literal with: single-quoted, not +/// triple-quoted, raw prefix folded into the value (the generator re-escapes what +/// it covered). Quote style is a request — the generator still switches to double +/// quotes when the value contains a single one, as CPython does. +/// +/// `u` is kept because it is the only prefix CPython's AST retains (as +/// `Constant.kind`); raw-ness is consumed by its parser and cannot come back. +fn canonical_string_flags(flags: ast::StringLiteralFlags) -> ast::StringLiteralFlags { + let prefix = match flags.prefix() { + StringLiteralPrefix::Unicode => StringLiteralPrefix::Unicode, + StringLiteralPrefix::Empty | StringLiteralPrefix::Raw { .. } => StringLiteralPrefix::Empty, + }; + flags + .with_prefix(prefix) + .with_quote_style(Quote::Single) + .with_triple_quotes(TripleQuotes::No) +} + +/// Replaces a `str` literal with the canonical literal for its value, collapsing +/// `"foo" "bar"` into `'foobar'`. +/// +/// CPython needs no equivalent: its parser already folded concatenation and +/// consumed the prefix, so its unparser just writes `repr(value)`. Ruff keeps the +/// spelling — a formatter needs it — so the discard happens here. +fn rebuild_string_literal(expr: &mut ast::ExprStringLiteral) { + let canonical = ast::StringLiteral { + range: expr.range, + node_index: AtomicNodeIndex::default(), + // `to_str` concatenates every part, and is the identity for one. + value: expr.value.to_str().into(), + flags: canonical_string_flags(expr.value.first_literal_flags()), + }; + expr.value = ast::StringLiteralValue::single(canonical); +} + +/// The `bytes` counterpart of [`rebuild_string_literal`], collapsing +/// `b"foo" b"bar"` into `b'foobar'`. +/// +/// Simpler than the `str` case only in the flags: `bytes` has no `u` prefix, so +/// the canonical form keeps no prefix at all. +fn rebuild_bytes_literal(expr: &mut ast::ExprBytesLiteral) { + let canonical = ast::BytesLiteral { + range: expr.range, + node_index: AtomicNodeIndex::default(), + value: expr.value.bytes().collect(), + flags: ast::BytesLiteralFlags::empty() + .with_prefix(ByteStringPrefix::Regular) + .with_quote_style(Quote::Single) + .with_triple_quotes(TripleQuotes::No), + }; + expr.value = ast::BytesLiteralValue::single(canonical); +} + +/// Collapses `f"x" "y"` into the single f-string `f'xy'`. +/// +/// Splices element lists rather than joining a string, because the parts are not +/// all the same kind: a plain part contributes one literal element, an f-string +/// part contributes all of its own. +fn merge_f_string_parts(expr: &mut ast::ExprFString) { + let mut elements: Vec = Vec::new(); + // The first f-string part's flags stand for the whole. + let mut flags = None; + for part in &expr.value { + match part { + ast::FStringPartRef::Literal(literal) => { + elements.push(ast::InterpolatedStringElement::Literal( + ast::InterpolatedStringLiteralElement { + range: literal.range, + node_index: AtomicNodeIndex::default(), + value: literal.value.clone(), + }, + )); + } + ast::FStringPartRef::FString(f_string) => { + flags = flags.or(Some(f_string.flags)); + elements.extend(f_string.elements.iter().cloned()); + } + } + } + // Unreachable: a concatenation with no f-string part would not parse as one. + let Some(flags) = flags else { return }; + expr.value = ast::FStringValue::single(ast::FString { + range: expr.range, + node_index: AtomicNodeIndex::default(), + elements: elements.into(), + flags, + }); +} diff --git a/crates/bashkit-monty/src/types/bytes.rs b/crates/bashkit-monty/src/types/bytes.rs new file mode 100644 index 000000000..85b1b4a09 --- /dev/null +++ b/crates/bashkit-monty/src/types/bytes.rs @@ -0,0 +1,2549 @@ +use std::{cell::Cell, ffi::c_int, fmt::Write, ops, str}; + +/// Python bytes type, wrapping a `Vec`. +/// +/// This type provides Python bytes semantics with operations on ASCII bytes only. +/// Unlike str methods which operate on Unicode codepoints, bytes methods only +/// recognize ASCII characters (0-127) for case transformations and predicates. +/// +/// # Implemented Methods +/// +/// ## Encoding/Decoding +/// - `decode([encoding[, errors]])` - Decode to string (UTF-8, ASCII, UTF-16/32) +/// - `hex([sep[, bytes_per_sep]])` - Return hex string representation +/// - `fromhex(string)` - Create bytes from hex string (classmethod) +/// +/// ## Simple Transformations +/// - `lower()` - Convert ASCII uppercase to lowercase +/// - `upper()` - Convert ASCII lowercase to uppercase +/// - `capitalize()` - First byte uppercase, rest lowercase +/// - `title()` - Titlecase ASCII letters +/// - `swapcase()` - Swap ASCII case +/// +/// ## Predicates +/// - `isalpha()` - All bytes are ASCII letters +/// - `isdigit()` - All bytes are ASCII digits +/// - `isalnum()` - All bytes are ASCII alphanumeric +/// - `isspace()` - All bytes are ASCII whitespace +/// - `islower()` - Has cased bytes, all lowercase +/// - `isupper()` - Has cased bytes, all uppercase +/// - `isascii()` - All bytes are ASCII (0-127) +/// - `istitle()` - Titlecased +/// +/// ## Search Methods +/// - `count(sub[, start[, end]])` - Count non-overlapping occurrences +/// - `find(sub[, start[, end]])` - Find first occurrence (-1 if not found) +/// - `rfind(sub[, start[, end]])` - Find last occurrence (-1 if not found) +/// - `index(sub[, start[, end]])` - Find first occurrence (raises ValueError) +/// - `rindex(sub[, start[, end]])` - Find last occurrence (raises ValueError) +/// - `startswith(prefix[, start[, end]])` - Check if starts with prefix +/// - `endswith(suffix[, start[, end]])` - Check if ends with suffix +/// +/// ## Strip/Trim Methods +/// - `strip([chars])` - Remove leading/trailing bytes +/// - `lstrip([chars])` - Remove leading bytes +/// - `rstrip([chars])` - Remove trailing bytes +/// - `removeprefix(prefix)` - Remove prefix if present +/// - `removesuffix(suffix)` - Remove suffix if present +/// +/// ## Split Methods +/// - `split([sep[, maxsplit]])` - Split on separator +/// - `rsplit([sep[, maxsplit]])` - Split from right +/// - `splitlines([keepends])` - Split on line boundaries +/// - `partition(sep)` - Split into 3 parts at first sep +/// - `rpartition(sep)` - Split into 3 parts at last sep +/// +/// ## Replace/Padding Methods +/// - `replace(old, new[, count])` - Replace occurrences +/// - `center(width[, fillbyte])` - Center with fill byte +/// - `ljust(width[, fillbyte])` - Left justify with fill byte +/// - `rjust(width[, fillbyte])` - Right justify with fill byte +/// - `zfill(width)` - Pad with zeros +/// +/// ## Other Methods +/// - `join(iterable)` - Join bytes sequences +/// +/// # Unimplemented Methods +/// - `expandtabs(tabsize=8)` - Tab expansion +/// - `translate(table[, delete])` - Character translation +/// - `maketrans(frm, to)` - Create translation table (staticmethod) +use memchr::memmem::{Finder, FinderRev}; +use monty_types::ResourceError; +pub use monty_types::{bytes_repr, bytes_repr_fmt}; +use smallvec::smallvec; + +use super::{CmpOrder, LazyHeapSet, PyTrait, Type}; +use crate::{ + args::{ArgValues, FromArgs, StrArg}, + bytecode::{CallResult, VM}, + codecs::Codec, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult, SimpleException}, + hash::{HashValue, hash_python_bytes}, + heap::{ + DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapView, heap_read_ref_as_field, + }, + identity::Identity, + intern::{BytesId, StaticStrings}, + percent_format::{copy_bytes_template, percent_format_bytes}, + resource_checks::{check_repeat_size, check_replace_size}, + types::{ + List, + long_int::repeat_count, + py_trait::PyObjectIdentity, + slice::{optional_sequence_bound, slice_collect_iterator}, + }, + value::{EitherStr, Value, eq_bytes}, +}; + +// ============================================================================= +// ASCII byte helper functions +// ============================================================================= + +/// Returns true if the byte is Python ASCII whitespace. +/// +/// Python considers these bytes as whitespace: space, tab, newline, carriage return, +/// vertical tab (0x0b), and form feed (0x0c). Note: Rust's `is_ascii_whitespace()` +/// does not include vertical tab (0x0b). +#[inline] +fn is_py_whitespace(b: u8) -> bool { + matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c) +} + +/// Gets the byte at a given index, handling negative indices. +/// +/// Returns `None` if the index is out of bounds. +/// Negative indices count from the end: -1 is the last byte. +pub fn get_byte_at_index(bytes: &[u8], index: i64) -> Option { + let len = i64::try_from(bytes.len()).ok()?; + let normalized = if index < 0 { index + len } else { index }; + + if normalized < 0 || normalized >= len { + return None; + } + + let idx = usize::try_from(normalized).ok()?; + Some(bytes[idx]) +} + +/// Python bytes value stored on the heap. +/// +/// Wraps a `Vec` and provides Python-compatible operations. +/// See the module-level documentation for implemented and unimplemented methods. +/// +/// Carries an inline `cached_hash` field (skipped on serde) so a `Bytes` only +/// computes its Python hash once. See [`super::Str`] for the same pattern. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +pub(crate) struct Bytes( + #[serde(with = "serde_bytes")] Vec, + #[serde(skip)] Cell>, +); + +impl PartialEq for Bytes { + /// Compares only the byte content — `cached_hash` is a pure optimisation. + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } +} + +impl Bytes { + /// Creates a new Bytes from a byte vector. + #[must_use] + pub fn new(bytes: Vec) -> Self { + Self(bytes, Cell::new(None)) + } + + /// Returns a reference to the inner byte slice. + #[must_use] + pub fn as_slice(&self) -> &[u8] { + &self.0 + } + + /// Creates bytes from the `bytes()` constructor call. + /// + /// - `bytes()` with no args returns empty bytes + /// - `bytes(int)` returns bytes of that length filled with zeros + /// - `bytes(string, encoding, errors)` encodes via the codec registry — + /// like CPython, a str source *requires* an encoding + /// - `bytes(bytes)` returns a copy of the bytes + pub fn init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let BytesInitArgs { + source, + encoding, + errors, + } = BytesInitArgs::from_args(args, vm)?; + defer_drop!(source, vm); + defer_drop!(encoding, vm); + defer_drop!(errors, vm); + let source_str = match source { + Some(v) if v.is_str(vm.heap) => Some(v), + _ => None, + }; + // CPython's `bytes_new` ordering: an encoding demands a str source, a + // str source demands an encoding, and a lone `errors` is never valid. + if let Some(encoding) = encoding { + let Some(v) = source_str else { + return Err(ExcType::type_error_encoding_without_string()); + }; + let s = v.to_str(vm)?; + let errors = errors.as_ref().map_or("strict", |e| e.as_str(vm)); + let encoding = encoding.as_str(vm); + let codec = Codec::find(encoding).ok_or_else(|| ExcType::lookup_error_unknown_encoding(encoding))?; + let encoded = codec.encode(s, errors, &vm.heap.tracker)?; + let heap_id = vm.heap.allocate(HeapData::Bytes(Self::new(encoded))); + return Ok(Value::Ref(heap_id)); + } + if source_str.is_some() { + return Err(ExcType::type_error_string_without_encoding()); + } + if errors.is_some() { + return Err(ExcType::type_error_errors_without_string()); + } + let new_data = match source { + None => Vec::new(), + Some(Value::Int(n)) => { + if *n < 0 { + return Err(ExcType::value_error_negative_bytes_count()); + } + // Fallible on a 32-bit target (`wasm32-wasip1`), where `bytes(2**40)` + // is a count no `usize` can hold. On 64-bit the conversion always + // succeeds and the size check below rejects it with `MemoryError`. + let size = usize::try_from(*n).map_err(|_| ExcType::overflow_index_sized_int())?; + // Pre-check the requested size against resource limits before + // touching the global allocator. Without this, `bytes(n)` for a + // very large `n` would attempt the native allocation directly + // and abort the host on failure rather than raising MemoryError. + // Mirrors the guard already used by `bytes.ljust`/`zfill`/`*`. + check_repeat_size(size, 1, &vm.heap.tracker)?; + vec![0u8; size] + } + Some(Value::InternBytes(bytes_id)) => { + let b = vm.interns.get_bytes(*bytes_id); + b.to_vec() + } + Some(v @ Value::Ref(id)) => match vm.heap.get(*id) { + HeapData::Bytes(b) => b.as_slice().to_vec(), + _ => return Err(ExcType::type_error_bytes_init(&v.py_type_name(vm))), + }, + Some(v) => return Err(ExcType::type_error_bytes_init(&v.py_type_name(vm))), + }; + let heap_id = vm.heap.allocate(HeapData::Bytes(Self::new(new_data))); + Ok(Value::Ref(heap_id)) + } +} + +/// Argument shape for `bytes(source=..., encoding=..., errors=...)`, all +/// pos-or-keyword. Unlike `str()`, CPython's `bytes_new` reports wrong-typed +/// `encoding`/`errors` with `_PyArg_BadArgument`'s wording (`must be str, not +/// None` for `None`), which is exactly the macro's `bad_arg_named` form. +#[derive(FromArgs)] +#[from_args(name = "bytes", at_most_total, bad_arg_named)] +struct BytesInitArgs { + #[from_args(default)] + source: Option, + #[from_args(default)] + encoding: Option, + #[from_args(default)] + errors: Option, +} + +/// Concatenates two byte strings into a tracked heap value. +pub(crate) fn concat_bytes(lhs: &[u8], rhs: &[u8], heap: &Heap) -> Result { + let result_len = lhs.len().saturating_add(rhs.len()); + check_repeat_size(result_len, 1, &heap.tracker)?; + let mut result = Vec::with_capacity(result_len); + result.extend_from_slice(lhs); + result.extend_from_slice(rhs); + Ok(Value::Ref(heap.allocate(HeapData::Bytes(result.into())))) +} + +/// Repeats bytes after validating the allocation against resource limits. +fn repeat_bytes(value: &[u8], count: &Value, vm: &VM<'_>) -> RunResult> { + let Some(count) = repeat_count(count, vm)? else { + return Ok(None); + }; + check_repeat_size(value.len(), count, &vm.heap.tracker)?; + Ok(Some(Value::Ref( + vm.heap.allocate(HeapData::Bytes(value.repeat(count).into())), + ))) +} + +/// An allocation-free bytes view retaining its interned or heap identity. +/// Heap handles can remain live across `__index__` calls without borrowing the buffer. +pub(crate) enum PyBytes<'h> { + Interned(BytesId), + Heap(HeapObjectRead<'h, Bytes>), +} + +impl<'h> PyBytes<'h> { + /// Extracts bytes without copying their contents. + pub(crate) fn from_value(value: &Value, vm: &VM<'h>) -> Option { + match value { + Value::InternBytes(id) => Some(Self::Interned(*id)), + Value::Ref(id) => vm.heap.read_as(*id).map(Self::Heap), + _ => None, + } + } + + /// Borrows the buffer only for the duration of the heap borrow. + pub(crate) fn as_slice<'a>(&'a self, vm: &'a VM<'h>) -> &'a [u8] { + match self { + Self::Interned(id) => vm.interns.get_bytes(*id), + Self::Heap(value) => value.get(vm.heap).as_slice(), + } + } +} + +impl PyObjectIdentity for PyBytes<'_> { + fn py_identity(&self) -> Identity { + match self { + Self::Interned(id) => Identity::InternBytes(id.index()), + Self::Heap(value) => value.py_identity(), + } + } +} + +impl<'h> PyTrait<'h> for PyBytes<'h> { + fn py_type(&self, _vm: &VM<'h>) -> Type { + Type::Bytes + } + + fn py_eq_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + match self { + Self::Interned(id) => Value::InternBytes(*id).py_eq_impl(other, vm), + Self::Heap(value) => value.py_eq_impl(other, vm), + } + } + + fn py_len(&self, vm: &VM<'h>) -> Option { + Some(self.as_slice(vm).len()) + } + + fn py_bool(&self, vm: &mut VM<'h>) -> RunResult { + Ok(!self.as_slice(vm).is_empty()) + } + + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, _heap_ids: &mut LazyHeapSet) -> RunResult<()> { + Ok(bytes_repr_fmt(self.as_slice(vm), f)?) + } + + fn py_contains_impl(&self, item: &Value, vm: &mut VM<'h>) -> RunResult> { + bytes_contains(self.as_slice(vm), item, vm).map(Some) + } + + fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + repeat_bytes(self.as_slice(vm), other, vm) + } + + fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + self.py_mul_impl(other, vm) + } + + fn py_add_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + bytes_add(self.as_slice(vm), other, vm) + } + + fn py_getitem(&self, key: &Value, vm: &mut VM<'h>) -> RunResult { + match self { + Self::Interned(id) => bytes_getitem(&*vm.heap.protect(vm.interns.get_bytes(*id)), key, vm), + Self::Heap(value) => value.py_getitem(key, vm), + } + } + + fn py_mod_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let template = copy_bytes_template(self.as_slice(vm), &vm.heap.tracker)?; + percent_format_bytes(&template, other, vm).map(Some) + } + + fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { + match self { + Self::Interned(id) => { + let Some(method) = attr.static_string(vm.interns) else { + args.drop_with(vm); + return Err(ExcType::attribute_error(Type::Bytes, attr.as_str(vm.interns))); + }; + let bytes = vm.heap.protect(vm.interns.get_bytes(*id)); + call_bytes_method_impl(&*bytes, method, args, vm).map(CallResult::Value) + } + Self::Heap(value) => value.py_call_attr(vm, attr, args), + } + } +} + +impl From> for Bytes { + fn from(bytes: Vec) -> Self { + Self::new(bytes) + } +} + +impl From<&[u8]> for Bytes { + fn from(bytes: &[u8]) -> Self { + Self::new(bytes.to_vec()) + } +} + +impl From for Vec { + fn from(bytes: Bytes) -> Self { + bytes.0 + } +} + +impl ops::Deref for Bytes { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, Bytes> { + /// One-sided implementation of Python membership (`__contains__`). + fn py_contains_impl(&self, item: &Value, vm: &mut VM<'h>) -> RunResult> { + bytes_contains(self.get(vm.heap).as_slice(), item, vm).map(Some) + } + + fn py_is_iterable(&self, _vm: &VM<'h>) -> bool { + true + } + + fn py_type(&self, _vm: &VM<'h>) -> Type { + Type::Bytes + } + + fn py_iter(&self, vm: &mut VM<'h>) -> RunResult { + Ok(CallResult::Value(BytesIterator::from_heap(self.id(), vm))) + } + + fn py_len(&self, vm: &VM<'h>) -> Option { + Some(self.get(vm.heap).0.len()) + } + + fn py_getitem(&self, key: &Value, vm: &mut VM<'h>) -> RunResult { + let bytes = heap_read_ref_as_field!(self, Bytes, 0); + bytes_getitem(&bytes.as_slice(), key, vm) + } + + fn py_eq_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + // Heap bytes equal interned or heap bytes with the same content. + Ok(eq_bytes(self.get(vm.heap).as_slice(), other, vm)) + } + + fn py_hash(&self, vm: &mut VM<'h>) -> RunResult> { + let b = self.get(vm.heap); + if let Some(cached) = b.1.get() { + return Ok(Some(cached)); + } + // Delegates to the canonical helper used by both heap and intern paths; + // an interned `b"foo"` and a heap `b"foo"` must hash identically for + // dict lookup to work. + let hash = hash_python_bytes(b.as_slice()); + b.1.set(Some(hash)); + Ok(Some(hash)) + } + + fn py_cmp(&self, other: &Self, vm: &mut VM<'h>) -> RunResult { + Ok(CmpOrder::Ordered(self.get(vm.heap).0.cmp(&other.get(vm.heap).0))) + } + + fn py_bool(&self, vm: &mut VM<'h>) -> RunResult { + Ok(!self.get(vm.heap).0.is_empty()) + } + + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, _heap_ids: &mut LazyHeapSet) -> RunResult<()> { + Ok(bytes_repr_fmt(&self.get(vm.heap).0, f)?) + } + + fn py_add_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + bytes_add(self.get(vm.heap).as_slice(), other, vm) + } + + fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + repeat_bytes(self.get(vm.heap).as_slice(), other, vm) + } + + fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + self.py_mul_impl(other, vm) + } + + /// `bytes % args` is printf-style formatting, see `percent_format`. + fn py_mod_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let template = copy_bytes_template(self.get(vm.heap).as_slice(), &vm.heap.tracker)?; + percent_format_bytes(&template, other, vm).map(Some) + } + + fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { + let Some(method) = attr.static_string(vm.interns) else { + args.drop_with(vm); + return Err(ExcType::attribute_error(Type::Bytes, attr.as_str(vm.interns))); + }; + + let field = heap_read_ref_as_field!(self, Bytes, 0); + let bytes = field.as_slice(); + call_bytes_method_impl(&bytes, method, args, vm).map(CallResult::Value) + } +} + +/// Concatenation shared by logical bytes views and concrete heap dispatch. +fn bytes_add(bytes: &[u8], other: &Value, vm: &VM<'_>) -> RunResult> { + match PyBytes::from_value(other, vm) { + Some(other) => Ok(Some(concat_bytes(bytes, other.as_slice(vm), vm.heap)?)), + None => Ok(None), + } +} + +/// Indexes a protected buffer, allowing `__index__` to run before borrowing it. +fn bytes_getitem<'h>(bytes: &impl HeapView<'h, [u8]>, key: &Value, vm: &mut VM<'h>) -> RunResult { + if let Value::Ref(id) = key + && let HeapData::Slice(slice) = vm.heap.get(*id) + { + let result = slice_collect_iterator(vm, slice, bytes.get(vm.heap).iter(), |b| *b)?; + Ok(Value::Ref(vm.heap.allocate(HeapData::Bytes(Bytes::new(result))))) + } else { + let index = key.as_index(vm, Type::Bytes)?; + let byte = get_byte_at_index(bytes.get(vm.heap), index).ok_or_else(ExcType::bytes_index_error)?; + Ok(Value::Int(i64::from(byte))) + } +} + +impl HeapItem for Bytes { + fn py_dec_ref_ids(&mut self, _stack: &mut Vec) { + // No-op: bytes don't hold Value references + } +} + +/// Calls a bytes method on a byte slice. +/// +/// This is the unified implementation for bytes method calls, used by both +/// heap-allocated `Bytes` (via `py_call_attr`) and interned bytes literals +/// (`Value::InternBytes`). +fn call_bytes_method_impl<'h>( + bytes: &impl HeapView<'h, [u8]>, + method: StaticStrings, + args: ArgValues, + vm: &mut VM<'h>, +) -> RunResult { + match method { + // Decode method + StaticStrings::Decode => bytes_decode(bytes, args, vm), + // Simple transformations (no arguments) + StaticStrings::Lower => { + args.check_zero_args("bytes.lower", vm.heap)?; + Ok(bytes_lower(bytes, vm)) + } + StaticStrings::Upper => { + args.check_zero_args("bytes.upper", vm.heap)?; + Ok(bytes_upper(bytes, vm)) + } + StaticStrings::Capitalize => { + args.check_zero_args("bytes.capitalize", vm.heap)?; + Ok(bytes_capitalize(bytes, vm)) + } + StaticStrings::Title => { + args.check_zero_args("bytes.title", vm.heap)?; + Ok(bytes_title(bytes, vm)) + } + StaticStrings::Swapcase => { + args.check_zero_args("bytes.swapcase", vm.heap)?; + Ok(bytes_swapcase(bytes, vm)) + } + // Predicate methods (no arguments, return bool) + StaticStrings::Isalpha => { + args.check_zero_args("bytes.isalpha", vm.heap)?; + Ok(Value::Bool(bytes_isalpha(bytes.get(vm.heap)))) + } + StaticStrings::Isdigit => { + args.check_zero_args("bytes.isdigit", vm.heap)?; + Ok(Value::Bool(bytes_isdigit(bytes.get(vm.heap)))) + } + StaticStrings::Isalnum => { + args.check_zero_args("bytes.isalnum", vm.heap)?; + Ok(Value::Bool(bytes_isalnum(bytes.get(vm.heap)))) + } + StaticStrings::Isspace => { + args.check_zero_args("bytes.isspace", vm.heap)?; + Ok(Value::Bool(bytes_isspace(bytes.get(vm.heap)))) + } + StaticStrings::Islower => { + args.check_zero_args("bytes.islower", vm.heap)?; + Ok(Value::Bool(bytes_islower(bytes.get(vm.heap)))) + } + StaticStrings::Isupper => { + args.check_zero_args("bytes.isupper", vm.heap)?; + Ok(Value::Bool(bytes_isupper(bytes.get(vm.heap)))) + } + StaticStrings::Isascii => { + args.check_zero_args("bytes.isascii", vm.heap)?; + Ok(Value::Bool(bytes.get(vm.heap).iter().all(|&b| b <= 127))) + } + StaticStrings::Istitle => { + args.check_zero_args("bytes.istitle", vm.heap)?; + Ok(Value::Bool(bytes_istitle(bytes.get(vm.heap)))) + } + // Search methods + StaticStrings::Count => bytes_count(bytes, args, vm), + StaticStrings::Find => bytes_find(bytes, args, vm), + StaticStrings::Rfind => bytes_rfind(bytes, args, vm), + StaticStrings::Index => bytes_index(bytes, args, vm), + StaticStrings::Rindex => bytes_rindex(bytes, args, vm), + StaticStrings::Startswith => bytes_startswith(bytes, args, vm), + StaticStrings::Endswith => bytes_endswith(bytes, args, vm), + // Strip/trim methods + StaticStrings::Strip => bytes_strip(bytes, args, vm), + StaticStrings::Lstrip => bytes_lstrip(bytes, args, vm), + StaticStrings::Rstrip => bytes_rstrip(bytes, args, vm), + StaticStrings::Removeprefix => bytes_removeprefix(bytes, args, vm), + StaticStrings::Removesuffix => bytes_removesuffix(bytes, args, vm), + // Split methods + StaticStrings::Split => bytes_split(bytes, args, vm), + StaticStrings::Rsplit => bytes_rsplit(bytes, args, vm), + StaticStrings::Splitlines => bytes_splitlines(bytes, args, vm), + StaticStrings::Partition => bytes_partition(bytes, args, vm), + StaticStrings::Rpartition => bytes_rpartition(bytes, args, vm), + // Replace/padding methods + StaticStrings::Replace => bytes_replace(bytes, args, vm), + StaticStrings::Center => bytes_center(bytes, args, vm), + StaticStrings::Ljust => bytes_ljust(bytes, args, vm), + StaticStrings::Rjust => bytes_rjust(bytes, args, vm), + StaticStrings::Zfill => bytes_zfill(bytes, args, vm), + // Join method + StaticStrings::Join => { + let iterable = args.get_one_arg("bytes.join", vm.heap)?; + bytes_join(bytes, iterable, vm) + } + // Hex method + StaticStrings::Hex => bytes_hex(bytes, args, vm), + // fromhex is a classmethod but also accessible on instances + StaticStrings::Fromhex => bytes_fromhex(args, vm), + _ => { + args.drop_with(vm.heap); + Err(ExcType::attribute_error(Type::Bytes, method.into())) + } + } +} + +/// Implements Python's `bytes.decode([encoding[, errors]])` method. +/// +/// Converts bytes to a string. Encoding-name resolution and the codec +/// implementations (UTF-8, ASCII, UTF-16/32 families) live in +/// [`crate::codecs`]. Like CPython, the error handler name is only looked up +/// (and validated) when a byte actually needs handling — see +/// `limitations/encoding.md` for the handful of decode divergences (the +/// surrogate-producing handlers raise `NotImplementedError`). +fn bytes_decode<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let BytesDecodeArgs { encoding, errors } = BytesDecodeArgs::from_args(args, vm)?; + defer_drop!(errors, vm); + defer_drop!(encoding, vm); + let encoding = encoding.as_ref().map_or("utf-8", |e| e.as_str(vm)); + let errors = errors.as_ref().map_or("strict", |e| e.as_str(vm)); + + let codec = Codec::find(encoding).ok_or_else(|| ExcType::lookup_error_unknown_encoding(encoding))?; + let s = codec.decode(bytes.get(vm.heap), errors)?; + Ok(super::str::allocate_string(s, vm.heap)) +} + +/// Argument shape for `bytes.decode(encoding='utf-8', errors='strict')`. +/// +/// `bad_arg_named` opts in to CPython's `_PyArg_BadArgument` named wording +/// (`decode() argument 'encoding' must be str, not `) so wrong-type +/// errors match the C implementation. Both fields default to absent; +/// CPython rejects explicit `None` here with the bad-arg error, which falls +/// out naturally because `Option::from_value` delegates to +/// `StrArg::from_value` and rejects `Value::None`. +#[derive(FromArgs)] +#[from_args(name = "decode", at_most_total, bad_arg_named)] +struct BytesDecodeArgs { + #[from_args(default)] + encoding: Option, + #[from_args(default)] + errors: Option, +} + +// ============================================================================= +// Substring scanning +// ============================================================================= +// +// Every `bytes` substring operation funnels through the scanners below. A scan +// runs inside one bytecode instruction, so the VM's per-instruction +// `check_time()` cannot preempt it — hence the chunked polling. + +/// Bytes scanned between `check_time()` polls. +const SCAN_CHUNK: usize = 64 * 1024; + +/// Finds the first occurrence of `needle` in `haystack`. +/// +/// Callers must handle the empty needle: it would spin [`count_non_overlapping`]. +/// Repeated scans for the same needle should build one [`Finder`] via +/// [`finder_for`] and call [`find_with`] instead — see their docstrings. +fn find_subsequence(haystack: &[u8], needle: &[u8], heap: &Heap) -> Result, ResourceError> { + match finder_for(needle, haystack) { + Some(finder) => find_with(&finder, haystack, heap), + None => Ok(None), + } +} + +/// Builds a forward finder, or `None` when `needle` cannot fit in `haystack`. +/// +/// [`Finder::new`] runs Two-Way preprocessing over the whole needle *before* +/// [`find_with`] reaches its first `check_time()`, so a host-supplied needle +/// longer than the haystack would burn unpolled time on a search that provably +/// cannot match. Every finder must be built through this or [`rfinder_for`]. +fn finder_for<'n>(needle: &'n [u8], haystack: &[u8]) -> Option> { + (needle.len() <= haystack.len()).then(|| Finder::new(needle)) +} + +/// Builds a reverse finder, or `None` when `needle` cannot fit in `haystack`. +/// +/// The mirror of [`finder_for`], with the same preprocessing rationale. +fn rfinder_for<'n>(needle: &'n [u8], haystack: &[u8]) -> Option> { + (needle.len() <= haystack.len()).then(|| FinderRev::new(needle)) +} + +/// Finds the first occurrence of `finder`'s needle in `haystack`. +/// +/// Chunks overlap by `needle.len() - 1` so boundary-straddling matches are +/// found; the stride never drops below the needle length so that overlap cannot +/// dominate. Above that floor a chunk spans up to `2 * needle.len()`, so a long +/// needle widens the time-limit overshoot — unavoidable, since a window +/// shorter than the needle cannot hold a match. See +/// `limitations/resource_limits.md`. +/// +/// Takes the [`Finder`] by reference because constructing one runs Two-Way +/// preprocessing over the needle; callers scanning in a loop (counting, +/// splitting, replacing) build it once rather than per match. +fn find_with(finder: &Finder<'_>, haystack: &[u8], heap: &Heap) -> Result, ResourceError> { + let needle_len = finder.needle().len(); + debug_assert!(needle_len > 0, "callers must handle the empty needle"); + let stride = SCAN_CHUNK.max(needle_len); + let mut start = 0; + while start < haystack.len() { + heap.tracker.check_time()?; + let end = start + .saturating_add(stride + needle_len.saturating_sub(1)) + .min(haystack.len()); + if let Some(pos) = finder.find(&haystack[start..end]) { + return Ok(Some(start + pos)); + } + start += stride; + } + Ok(None) +} + +/// Finds the last occurrence of `needle` in `haystack`. +/// +/// The mirror of [`find_subsequence`]; [`rfind_with`] is the reusable form. +fn rfind_subsequence(haystack: &[u8], needle: &[u8], heap: &Heap) -> Result, ResourceError> { + match rfinder_for(needle, haystack) { + Some(finder) => rfind_with(&finder, haystack, heap), + None => Ok(None), + } +} + +/// Finds the last occurrence of `finder`'s needle in `haystack`. +/// +/// The mirror of [`find_with`], walking chunks from the end; the same +/// preprocessing-reuse rationale applies. +fn rfind_with(finder: &FinderRev<'_>, haystack: &[u8], heap: &Heap) -> Result, ResourceError> { + let needle_len = finder.needle().len(); + debug_assert!(needle_len > 0, "callers must handle the empty needle"); + let stride = SCAN_CHUNK.max(needle_len); + let mut end = haystack.len(); + while end > 0 { + heap.tracker.check_time()?; + let start = end.saturating_sub(stride + needle_len.saturating_sub(1)); + if let Some(pos) = finder.rfind(&haystack[start..end]) { + return Ok(Some(start + pos)); + } + end = end.saturating_sub(stride); + } + Ok(None) +} + +/// Counts non-overlapping occurrences of `needle` in `haystack`. +fn count_non_overlapping(haystack: &[u8], needle: &[u8], heap: &Heap) -> Result { + let Some(finder) = finder_for(needle, haystack) else { + return Ok(0); + }; + let mut count = 0; + let mut pos = 0; + while let Some(found) = find_with(&finder, &haystack[pos..], heap)? { + count += 1; + pos += found + needle.len(); + } + Ok(count) +} + +/// Implements Python's `bytes.count(sub[, start[, end]])` method. +/// +/// Returns the number of non-overlapping occurrences of the subsequence. +fn bytes_count<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let len = bytes.get(vm.heap).len(); + let (sub, start, end) = parse_bytes_sub_args("bytes.count", len, args, vm)?; + + let slice = &bytes.get(vm.heap)[start..end]; + let count = if sub.is_empty() { + // Empty subsequence: count positions between each byte plus 1 + slice.len() + 1 + } else { + count_non_overlapping(slice, &sub, vm.heap)? + }; + + let count_i64 = i64::try_from(count).expect("count exceeds i64::MAX"); + Ok(Value::Int(count_i64)) +} + +/// Implements Python's `bytes.find(sub[, start[, end]])` method. +/// +/// Returns the lowest index where the subsequence is found, or -1 if not found. +fn bytes_find<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let len = bytes.get(vm.heap).len(); + let (sub, start, end) = parse_bytes_sub_args("bytes.find", len, args, vm)?; + + let slice = &bytes.get(vm.heap)[start..end]; + let result = if sub.is_empty() { + // Empty subsequence: always found at start position + Some(0) + } else { + find_subsequence(slice, &sub, vm.heap)? + }; + + let idx = match result { + Some(i) => i64::try_from(start + i).expect("index exceeds i64::MAX"), + None => -1, + }; + Ok(Value::Int(idx)) +} + +/// Implements Python's `bytes.index(sub[, start[, end]])` method. +/// +/// Like find(), but raises ValueError if the subsequence is not found. +fn bytes_index<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let len = bytes.get(vm.heap).len(); + let (sub, start, end) = parse_bytes_sub_args("bytes.index", len, args, vm)?; + + let slice = &bytes.get(vm.heap)[start..end]; + let result = if sub.is_empty() { + // Empty subsequence: always found at start position + Some(0) + } else { + find_subsequence(slice, &sub, vm.heap)? + }; + + match result { + Some(i) => { + let idx = i64::try_from(start + i).expect("index exceeds i64::MAX"); + Ok(Value::Int(idx)) + } + None => Err(ExcType::value_error_subsequence_not_found()), + } +} + +/// Implements Python's `bytes.startswith(prefix[, start[, end]])` method. +/// +/// Returns True if bytes starts with the specified prefix. +/// Accepts bytes or a tuple of bytes as prefix. If a tuple is given, returns True +/// if any of the prefixes match. +fn bytes_startswith<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let len = bytes.get(vm.heap).len(); + let (prefix_arg, start, end) = parse_bytes_prefix_suffix_args("bytes.startswith", len, args, vm)?; + + let slice = &bytes.get(vm.heap)[start..end]; + let result = match prefix_arg { + PrefixSuffixArg::Single(prefix_bytes) => slice.starts_with(&prefix_bytes), + PrefixSuffixArg::Multiple(prefixes) => prefixes.iter().any(|p| slice.starts_with(p)), + }; + Ok(Value::Bool(result)) +} + +/// Implements Python's `bytes.endswith(suffix[, start[, end]])` method. +/// +/// Returns True if bytes ends with the specified suffix. +/// Accepts bytes or a tuple of bytes as suffix. If a tuple is given, returns True +/// if any of the suffixes match. +fn bytes_endswith<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let len = bytes.get(vm.heap).len(); + let (suffix_arg, start, end) = parse_bytes_prefix_suffix_args("bytes.endswith", len, args, vm)?; + + let slice = &bytes.get(vm.heap)[start..end]; + let result = match suffix_arg { + PrefixSuffixArg::Single(suffix_bytes) => slice.ends_with(&suffix_bytes), + PrefixSuffixArg::Multiple(suffixes) => suffixes.iter().any(|s| slice.ends_with(s)), + }; + Ok(Value::Bool(result)) +} + +/// Argument type for prefix/suffix matching methods. +/// +/// Represents either a single bytes value or a tuple of bytes values +/// for matching in startswith/endswith. +enum PrefixSuffixArg { + /// A single bytes value to match + Single(Vec), + /// Multiple bytes values to match (from a tuple) + Multiple(Vec>), +} + +/// Parses arguments for bytes.startswith/endswith methods. +/// +/// Returns (prefix/suffix_arg, start, end) where start and end are normalized indices. +/// The prefix/suffix_arg can be a single bytes value or a tuple of bytes values. +/// Guarantees `start <= end` to prevent slice panics. +fn parse_bytes_prefix_suffix_args( + method: &str, + len: usize, + args: ArgValues, + vm: &mut VM<'_>, +) -> RunResult<(PrefixSuffixArg, usize, usize)> { + let pos = args.into_pos_only(method, vm.heap)?; + defer_drop!(pos, vm); + + let (prefix, start, end) = match pos.as_slice() { + [prefix_value] => { + let prefix = extract_bytes_for_prefix_suffix(prefix_value, method, vm)?; + (prefix, 0, len) + } + [prefix_value, start_value] => { + let prefix = extract_bytes_for_prefix_suffix(prefix_value, method, vm)?; + let start = optional_sequence_bound(start_value, 0, len, vm)?; + (prefix, start, len) + } + [prefix_value, start_value, end_value] => { + let prefix = extract_bytes_for_prefix_suffix(prefix_value, method, vm)?; + let start = optional_sequence_bound(start_value, 0, len, vm)?; + let end = optional_sequence_bound(end_value, len, len, vm)?; + (prefix, start, end) + } + [] => return Err(ExcType::type_error_at_least(method, 1, 0)), + _ => return Err(ExcType::type_error_at_most(method, 3, pos.len())), + }; + + // Ensure start <= end to prevent slice panics + Ok((prefix, start, end.max(start))) +} + +/// Extracts bytes (or tuple of bytes) for startswith/endswith methods. +/// +/// Returns `PrefixSuffixArg::Single` for a single bytes value, or +/// `PrefixSuffixArg::Multiple` for a tuple of bytes values. +fn extract_bytes_for_prefix_suffix(value: &Value, method: &str, vm: &VM<'_>) -> RunResult { + // Extract the method name (e.g., "startswith" from "bytes.startswith") + let method_name = method.strip_prefix("bytes.").unwrap_or(method); + + match value { + Value::InternBytes(id) => Ok(PrefixSuffixArg::Single(vm.interns.get_bytes(*id).to_vec())), + Value::InternString(_) => Err(ExcType::type_error(format!( + "{method_name} first arg must be bytes or a tuple of bytes, not str" + ))), + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Bytes(b) => Ok(PrefixSuffixArg::Single(b.as_slice().to_vec())), + HeapData::Str(_) => Err(ExcType::type_error(format!( + "{method_name} first arg must be bytes or a tuple of bytes, not str" + ))), + HeapData::Tuple(tuple) => { + // Extract each element as bytes + let items = tuple.as_slice(); + let mut prefixes = Vec::with_capacity(items.len()); + for (i, item) in items.iter().enumerate() { + if let Ok(b) = extract_single_bytes_for_prefix_suffix(item, vm) { + prefixes.push(b); + } else { + let item_type = item.py_type_name(vm); + return Err(ExcType::type_error(format!( + "{method_name} first arg must be bytes or a tuple of bytes, \ + not tuple containing {item_type} at index {i}" + ))); + } + } + Ok(PrefixSuffixArg::Multiple(prefixes)) + } + _ => Err(ExcType::type_error(format!( + "{method_name} first arg must be bytes or a tuple of bytes, not {}", + value.py_type_name(vm) + ))), + }, + _ => Err(ExcType::type_error(format!( + "{method_name} first arg must be bytes or a tuple of bytes, not {}", + value.py_type_name(vm) + ))), + } +} + +/// Extracts a single bytes value for tuple element in startswith/endswith. +fn extract_single_bytes_for_prefix_suffix(value: &Value, vm: &VM<'_>) -> RunResult> { + match value { + Value::InternBytes(id) => Ok(vm.interns.get_bytes(*id).to_vec()), + Value::InternString(_) => Err(ExcType::type_error("expected bytes, not str")), + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Bytes(b) => Ok(b.as_slice().to_vec()), + _ => Err(ExcType::type_error("expected bytes")), + }, + _ => Err(ExcType::type_error("expected bytes")), + } +} + +/// Extracts bytes from a Value (bytes only, NOT str - matches CPython behavior). +/// +/// CPython raises `TypeError: a bytes-like object is required, not 'str'` when +/// a str is passed to bytes methods like find, count, index, startswith, endswith. +fn extract_bytes_only<'a>(value: &Value, vm: &'a VM<'_>) -> RunResult<&'a [u8]> { + match value { + Value::InternBytes(id) => Ok(vm.interns.get_bytes(*id)), + Value::InternString(_) => Err(ExcType::type_error("a bytes-like object is required, not 'str'")), + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Bytes(b) => Ok(b.as_slice()), + HeapData::Str(_) => Err(ExcType::type_error("a bytes-like object is required, not 'str'")), + _ => Err(ExcType::type_error("a bytes-like object is required")), + }, + _ => Err(ExcType::type_error("a bytes-like object is required")), + } +} + +/// Parses arguments for bytes.find/count/index methods. +/// +/// Returns (sub_bytes, start, end) where start and end are normalized indices. +/// Guarantees `start <= end` to prevent slice panics. +fn parse_bytes_sub_args( + method: &str, + len: usize, + args: ArgValues, + vm: &mut VM<'_>, +) -> RunResult<(Vec, usize, usize)> { + let pos = args.into_pos_only(method, vm.heap)?; + defer_drop!(pos, vm); + + // The bounds convert before `sub` is inspected, as in CPython, whose parser + // runs the index converters and leaves the buffer check to the function body. + // A raising `__index__` bound then costs no copy; `pos` keeps `sub` alive. + let (sub_value, start, end) = match pos.as_slice() { + [sub_value] => (sub_value, 0, len), + [sub_value, start_value] => { + let start = optional_sequence_bound(start_value, 0, len, vm)?; + (sub_value, start, len) + } + [sub_value, start_value, end_value] => { + let start = optional_sequence_bound(start_value, 0, len, vm)?; + let end = optional_sequence_bound(end_value, len, len, vm)?; + (sub_value, start, end) + } + [] => return Err(ExcType::type_error_at_least(method, 1, 0)), + _ => return Err(ExcType::type_error_at_most(method, 3, pos.len())), + }; + let sub = extract_bytes_only(sub_value, vm)?.to_owned(); + + // Ensure start <= end to prevent slice panics (Python treats start > end as empty slice) + Ok((sub, start, end.max(start))) +} + +// ============================================================================= +// Simple transformations (no arguments) +// ============================================================================= + +/// Implements Python's `bytes.lower()` method. +/// +/// Returns a copy of the bytes with all ASCII uppercase characters converted to lowercase. +fn bytes_lower<'h>(bytes: &impl HeapView<'h, [u8]>, vm: &mut VM<'h>) -> Value { + let result: Vec = bytes.get(vm.heap).iter().map(|&b| b.to_ascii_lowercase()).collect(); + allocate_bytes(result, vm.heap) +} + +/// Implements Python's `bytes.upper()` method. +/// +/// Returns a copy of the bytes with all ASCII lowercase characters converted to uppercase. +fn bytes_upper<'h>(bytes: &impl HeapView<'h, [u8]>, vm: &mut VM<'h>) -> Value { + let result: Vec = bytes.get(vm.heap).iter().map(|&b| b.to_ascii_uppercase()).collect(); + allocate_bytes(result, vm.heap) +} + +/// Implements Python's `bytes.capitalize()` method. +/// +/// Returns a copy of the bytes with the first byte capitalized (if ASCII) and +/// the rest lowercased. +fn bytes_capitalize<'h>(bytes: &impl HeapView<'h, [u8]>, vm: &mut VM<'h>) -> Value { + let bytes = bytes.get(vm.heap); + let mut result = Vec::with_capacity(bytes.len()); + if let Some((&first, rest)) = bytes.split_first() { + result.push(first.to_ascii_uppercase()); + for &b in rest { + result.push(b.to_ascii_lowercase()); + } + } + allocate_bytes(result, vm.heap) +} + +/// Implements Python's `bytes.title()` method. +/// +/// Returns a titlecased version of the bytes where words start with an uppercase +/// ASCII character and the remaining characters are lowercase. +fn bytes_title<'h>(bytes: &impl HeapView<'h, [u8]>, vm: &mut VM<'h>) -> Value { + let bytes = bytes.get(vm.heap); + let mut result = Vec::with_capacity(bytes.len()); + let mut prev_is_cased = false; + + for &b in bytes { + if prev_is_cased { + result.push(b.to_ascii_lowercase()); + } else { + result.push(b.to_ascii_uppercase()); + } + prev_is_cased = b.is_ascii_alphabetic(); + } + + allocate_bytes(result, vm.heap) +} + +/// Implements Python's `bytes.swapcase()` method. +/// +/// Returns a copy of the bytes with ASCII uppercase characters converted to +/// lowercase and vice versa. +fn bytes_swapcase<'h>(bytes: &impl HeapView<'h, [u8]>, vm: &mut VM<'h>) -> Value { + let result: Vec = bytes + .get(vm.heap) + .iter() + .map(|&b| { + if b.is_ascii_uppercase() { + b.to_ascii_lowercase() + } else if b.is_ascii_lowercase() { + b.to_ascii_uppercase() + } else { + b + } + }) + .collect(); + allocate_bytes(result, vm.heap) +} + +// ============================================================================= +// Predicate methods (no arguments, return bool) +// ============================================================================= + +/// Implements Python's `bytes.isalpha()` method. +/// +/// Returns True if all bytes in the bytes are ASCII letters and there is at least one byte. +fn bytes_isalpha(bytes: &[u8]) -> bool { + !bytes.is_empty() && bytes.iter().all(|&b| b.is_ascii_alphabetic()) +} + +/// Implements Python's `bytes.isdigit()` method. +/// +/// Returns True if all bytes in the bytes are ASCII digits and there is at least one byte. +fn bytes_isdigit(bytes: &[u8]) -> bool { + !bytes.is_empty() && bytes.iter().all(|&b| b.is_ascii_digit()) +} + +/// Implements Python's `bytes.isalnum()` method. +/// +/// Returns True if all bytes in the bytes are ASCII alphanumeric and there is at least one byte. +fn bytes_isalnum(bytes: &[u8]) -> bool { + !bytes.is_empty() && bytes.iter().all(|&b| b.is_ascii_alphanumeric()) +} + +/// Implements Python's `bytes.isspace()` method. +/// +/// Returns True if all bytes in the bytes are ASCII whitespace and there is at least one byte. +fn bytes_isspace(bytes: &[u8]) -> bool { + !bytes.is_empty() && bytes.iter().all(|&b| is_py_whitespace(b)) +} + +/// Implements Python's `bytes.islower()` method. +/// +/// Returns True if all cased bytes are lowercase and there is at least one cased byte. +fn bytes_islower(bytes: &[u8]) -> bool { + let mut has_cased = false; + for &b in bytes { + if b.is_ascii_uppercase() { + return false; + } + if b.is_ascii_lowercase() { + has_cased = true; + } + } + has_cased +} + +/// Implements Python's `bytes.isupper()` method. +/// +/// Returns True if all cased bytes are uppercase and there is at least one cased byte. +fn bytes_isupper(bytes: &[u8]) -> bool { + let mut has_cased = false; + for &b in bytes { + if b.is_ascii_lowercase() { + return false; + } + if b.is_ascii_uppercase() { + has_cased = true; + } + } + has_cased +} + +/// Implements Python's `bytes.istitle()` method. +/// +/// Returns True if the bytes are titlecased: uppercase characters follow +/// uncased characters and lowercase characters follow cased characters. +fn bytes_istitle(bytes: &[u8]) -> bool { + if bytes.is_empty() { + return false; + } + + let mut prev_cased = false; + let mut has_cased = false; + + for &b in bytes { + if b.is_ascii_uppercase() { + if prev_cased { + return false; + } + prev_cased = true; + has_cased = true; + } else if b.is_ascii_lowercase() { + if !prev_cased { + return false; + } + prev_cased = true; + has_cased = true; + } else { + prev_cased = false; + } + } + + has_cased +} + +// ============================================================================= +// Search methods +// ============================================================================= + +/// Implements Python's `bytes.rfind(sub[, start[, end]])` method. +/// +/// Returns the highest index where the subsequence is found, or -1 if not found. +fn bytes_rfind<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let len = bytes.get(vm.heap).len(); + let (sub, start, end) = parse_bytes_sub_args("bytes.rfind", len, args, vm)?; + + let slice = &bytes.get(vm.heap)[start..end]; + let result = if sub.is_empty() { + // Empty subsequence: always found at end position + Some(slice.len()) + } else { + rfind_subsequence(slice, &sub, vm.heap)? + }; + + let idx = match result { + Some(i) => i64::try_from(start + i).expect("index exceeds i64::MAX"), + None => -1, + }; + Ok(Value::Int(idx)) +} + +/// Implements Python's `bytes.rindex(sub[, start[, end]])` method. +/// +/// Like rfind(), but raises ValueError if the subsequence is not found. +fn bytes_rindex<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let len = bytes.get(vm.heap).len(); + let (sub, start, end) = parse_bytes_sub_args("bytes.rindex", len, args, vm)?; + + let slice = &bytes.get(vm.heap)[start..end]; + let result = if sub.is_empty() { + Some(slice.len()) + } else { + rfind_subsequence(slice, &sub, vm.heap)? + }; + + match result { + Some(i) => { + let idx = i64::try_from(start + i).expect("index exceeds i64::MAX"); + Ok(Value::Int(idx)) + } + None => Err(ExcType::value_error_subsequence_not_found()), + } +} + +// ============================================================================= +// Strip/trim methods +// ============================================================================= + +/// Implements Python's `bytes.strip([chars])` method. +/// +/// Returns a copy of the bytes with leading and trailing bytes removed. +/// If chars is not specified, ASCII whitespace bytes are removed. +fn bytes_strip<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let value = args.get_zero_one_arg("bytes.strip", vm.heap)?; + defer_drop!(value, vm); + let result = match value { + None | Some(Value::None) => bytes_strip_whitespace_both(bytes.get(vm.heap)), + Some(v) => bytes_strip_both(bytes.get(vm.heap), extract_bytes_only(v, vm)?), + }; + Ok(allocate_bytes(result.to_vec(), vm.heap)) +} + +/// Implements Python's `bytes.lstrip([chars])` method. +/// +/// Returns a copy of the bytes with leading bytes removed. +fn bytes_lstrip<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let value = args.get_zero_one_arg("bytes.lstrip", vm.heap)?; + defer_drop!(value, vm); + let result = match value { + None | Some(Value::None) => bytes_strip_whitespace_start(bytes.get(vm.heap)), + Some(v) => bytes_strip_start(bytes.get(vm.heap), extract_bytes_only(v, vm)?), + }; + Ok(allocate_bytes(result.to_vec(), vm.heap)) +} + +/// Implements Python's `bytes.rstrip([chars])` method. +/// +/// Returns a copy of the bytes with trailing bytes removed. +fn bytes_rstrip<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let value = args.get_zero_one_arg("bytes.rstrip", vm.heap)?; + defer_drop!(value, vm); + let result = match value { + None | Some(Value::None) => bytes_strip_whitespace_end(bytes.get(vm.heap)), + Some(v) => bytes_strip_end(bytes.get(vm.heap), extract_bytes_only(v, vm)?), + }; + Ok(allocate_bytes(result.to_vec(), vm.heap)) +} + +/// Strips bytes in `chars` from both ends of the byte slice. +fn bytes_strip_both<'a>(bytes: &'a [u8], chars: &[u8]) -> &'a [u8] { + let start = bytes.iter().position(|b| !chars.contains(b)).unwrap_or(bytes.len()); + let end = bytes + .iter() + .rposition(|b| !chars.contains(b)) + .map_or(start, |pos| pos + 1); + &bytes[start..end] +} + +/// Strips bytes in `chars` from the start of the byte slice. +fn bytes_strip_start<'a>(bytes: &'a [u8], chars: &[u8]) -> &'a [u8] { + let start = bytes.iter().position(|b| !chars.contains(b)).unwrap_or(bytes.len()); + &bytes[start..] +} + +/// Strips bytes in `chars` from the end of the byte slice. +fn bytes_strip_end<'a>(bytes: &'a [u8], chars: &[u8]) -> &'a [u8] { + let end = bytes.iter().rposition(|b| !chars.contains(b)).map_or(0, |pos| pos + 1); + &bytes[..end] +} + +/// Strips ASCII whitespace from both ends of the byte slice. +fn bytes_strip_whitespace_both(bytes: &[u8]) -> &[u8] { + let start = bytes.iter().position(|b| !is_py_whitespace(*b)).unwrap_or(bytes.len()); + let end = bytes + .iter() + .rposition(|b| !is_py_whitespace(*b)) + .map_or(start, |pos| pos + 1); + &bytes[start..end] +} + +/// Strips ASCII whitespace from the start of the byte slice. +fn bytes_strip_whitespace_start(bytes: &[u8]) -> &[u8] { + let start = bytes.iter().position(|b| !is_py_whitespace(*b)).unwrap_or(bytes.len()); + &bytes[start..] +} + +/// Strips ASCII whitespace from the end of the byte slice. +fn bytes_strip_whitespace_end(bytes: &[u8]) -> &[u8] { + let end = bytes + .iter() + .rposition(|b| !is_py_whitespace(*b)) + .map_or(0, |pos| pos + 1); + &bytes[..end] +} + +/// Implements Python's `bytes.removeprefix(prefix)` method. +/// +/// If the bytes start with the prefix, return bytes[len(prefix):]. +/// Otherwise, return a copy of the original bytes. +fn bytes_removeprefix<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let prefix_value = args.get_one_arg("bytes.removeprefix", vm.heap)?; + defer_drop!(prefix_value, vm); + let prefix = extract_bytes_only(prefix_value, vm)?; + + let bytes = bytes.get(vm.heap); + let result = if bytes.starts_with(prefix) { + bytes[prefix.len()..].to_vec() + } else { + bytes.to_vec() + }; + Ok(allocate_bytes(result, vm.heap)) +} + +/// Implements Python's `bytes.removesuffix(suffix)` method. +/// +/// If the bytes end with the suffix, return bytes[:-len(suffix)]. +/// Otherwise, return a copy of the original bytes. +fn bytes_removesuffix<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let suffix_value = args.get_one_arg("bytes.removesuffix", vm.heap)?; + defer_drop!(suffix_value, vm); + let suffix = extract_bytes_only(suffix_value, vm)?; + + let bytes = bytes.get(vm.heap); + let result = if bytes.ends_with(suffix) && !suffix.is_empty() { + bytes[..bytes.len() - suffix.len()].to_vec() + } else { + bytes.to_vec() + }; + Ok(allocate_bytes(result, vm.heap)) +} + +// ============================================================================= +// Split methods +// ============================================================================= + +/// Implements Python's `bytes.split([sep[, maxsplit]])` method. +/// +/// Returns a list of the bytes split by the separator. +fn bytes_split<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let BytesSplitArgs { sep, maxsplit } = BytesSplitArgs::from_args(args, vm)?; + let (sep, maxsplit) = coerce_bytes_split_args(sep, maxsplit, vm)?; + + let bytes = bytes.get(vm.heap); + let parts: Vec<&[u8]> = match &sep { + Some(sep) => { + if sep.is_empty() { + return Err(ExcType::value_error_empty_separator()); + } + if maxsplit < 0 { + bytes_split_by_seq(bytes, sep, vm.heap)? + } else { + let max = usize::try_from(maxsplit).unwrap_or(usize::MAX); + bytes_splitn_by_seq(bytes, sep, max + 1, vm.heap)? + } + } + None => { + if maxsplit < 0 { + bytes_split_whitespace(bytes) + } else { + let max = usize::try_from(maxsplit).unwrap_or(usize::MAX); + bytes_splitn_whitespace(bytes, max) + } + } + }; + + let mut list_items = Vec::with_capacity(parts.len()); + for (i, part) in parts.into_iter().enumerate() { + vm.heap.tracker.check_memory_time_every(i)?; + list_items.push(allocate_bytes(part.to_vec(), vm.heap)); + } + + let list = List::new(list_items); + let heap_id = vm.heap.allocate(HeapData::List(list)); + Ok(Value::Ref(heap_id)) +} + +/// Implements Python's `bytes.rsplit([sep[, maxsplit]])` method. +/// +/// Returns a list of the bytes split by the separator, splitting from the right. +fn bytes_rsplit<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let BytesRsplitArgs { sep, maxsplit } = BytesRsplitArgs::from_args(args, vm)?; + let (sep, maxsplit) = coerce_bytes_split_args(sep, maxsplit, vm)?; + + let bytes = bytes.get(vm.heap); + let parts: Vec<&[u8]> = match &sep { + Some(sep) => { + if sep.is_empty() { + return Err(ExcType::value_error_empty_separator()); + } + if maxsplit < 0 { + bytes_split_by_seq(bytes, sep, vm.heap)? + } else { + let max = usize::try_from(maxsplit).unwrap_or(usize::MAX); + bytes_rsplitn_by_seq(bytes, sep, max + 1, vm.heap)? + } + } + None => { + if maxsplit < 0 { + bytes_split_whitespace(bytes) + } else { + let max = usize::try_from(maxsplit).unwrap_or(usize::MAX); + bytes_rsplitn_whitespace(bytes, max) + } + } + }; + + let mut list_items = Vec::with_capacity(parts.len()); + for (i, part) in parts.into_iter().enumerate() { + vm.heap.tracker.check_memory_time_every(i)?; + list_items.push(allocate_bytes(part.to_vec(), vm.heap)); + } + + let list = List::new(list_items); + let heap_id = vm.heap.allocate(HeapData::List(list)); + Ok(Value::Ref(heap_id)) +} + +/// Coerces extracted `sep` / `maxsplit` `Value`s into the runtime shape used +/// by `bytes.split` / `bytes.rsplit`. +/// +/// `sep = None` is the documented "no separator" sentinel (split on +/// runs of whitespace); any other value must be a bytes-like via +/// `extract_bytes_only`. `maxsplit` is read as an `i64`. Both arguments are +/// dropped on every path so refcounts stay balanced. +fn coerce_bytes_split_args(sep: Value, maxsplit: Value, vm: &mut VM<'_>) -> RunResult<(Option>, i64)> { + defer_drop!(sep, vm); + defer_drop!(maxsplit, vm); + // `maxsplit` converts first, as in CPython's clinic, which reads it while + // `sep` is still an unchecked object — a raising `__index__` costs no copy. + let maxsplit_int = maxsplit.as_int(vm)?; + let sep = match sep { + Value::None => None, + _ => Some(extract_bytes_only(sep, vm)?.to_owned()), + }; + Ok((sep, maxsplit_int)) +} + +/// Argument shape for `bytes.split(sep=None, maxsplit=-1)`. +#[derive(FromArgs)] +#[from_args(name = "split")] +struct BytesSplitArgs { + #[from_args(default = Value::None)] + sep: Value, + #[from_args(default = Value::Int(-1))] + maxsplit: Value, +} + +/// Argument shape for `bytes.rsplit(sep=None, maxsplit=-1)`. +#[derive(FromArgs)] +#[from_args(name = "rsplit")] +struct BytesRsplitArgs { + #[from_args(default = Value::None)] + sep: Value, + #[from_args(default = Value::Int(-1))] + maxsplit: Value, +} + +/// Splits bytes by a separator sequence. +fn bytes_split_by_seq<'a>(bytes: &'a [u8], sep: &[u8], heap: &Heap) -> Result, ResourceError> { + let Some(finder) = finder_for(sep, bytes) else { + return Ok(vec![bytes]); + }; + let mut parts = Vec::new(); + let mut start = 0; + + while let Some(pos) = find_with(&finder, &bytes[start..], heap)? { + parts.push(&bytes[start..start + pos]); + start = start + pos + sep.len(); + } + parts.push(&bytes[start..]); + + Ok(parts) +} + +/// Splits bytes by a separator sequence, returning at most n parts. +fn bytes_splitn_by_seq<'a>(bytes: &'a [u8], sep: &[u8], n: usize, heap: &Heap) -> Result, ResourceError> { + // `maxsplit=0` (`n == 1`) permits no splits, so return before `finder_for` + // preprocesses the separator — that runs ahead of any `check_time()`. + if n <= 1 { + return Ok(vec![bytes]); + } + let Some(finder) = finder_for(sep, bytes) else { + return Ok(vec![bytes]); + }; + let mut parts = Vec::new(); + let mut start = 0; + let mut count = 0; + + while count + 1 < n { + if let Some(pos) = find_with(&finder, &bytes[start..], heap)? { + parts.push(&bytes[start..start + pos]); + start = start + pos + sep.len(); + count += 1; + } else { + break; + } + } + parts.push(&bytes[start..]); + + Ok(parts) +} + +/// Splits bytes by a separator sequence from the right, returning at most n parts. +fn bytes_rsplitn_by_seq<'a>( + bytes: &'a [u8], + sep: &[u8], + n: usize, + heap: &Heap, +) -> Result, ResourceError> { + // `maxsplit=0` (`n == 1`) permits no splits, so return before `rfinder_for` + // preprocesses the separator — that runs ahead of any `check_time()`. + if n <= 1 { + return Ok(vec![bytes]); + } + let Some(finder) = rfinder_for(sep, bytes) else { + return Ok(vec![bytes]); + }; + let mut parts = Vec::new(); + let mut end = bytes.len(); + let mut count = 0; + + while count + 1 < n { + if let Some(pos) = rfind_with(&finder, &bytes[..end], heap)? { + parts.push(&bytes[pos + sep.len()..end]); + end = pos; + count += 1; + } else { + break; + } + } + parts.push(&bytes[..end]); + parts.reverse(); + + Ok(parts) +} + +/// Splits bytes by ASCII whitespace, filtering empty parts. +fn bytes_split_whitespace(bytes: &[u8]) -> Vec<&[u8]> { + let mut parts = Vec::new(); + let mut start = None; + + for (i, &b) in bytes.iter().enumerate() { + if is_py_whitespace(b) { + if let Some(s) = start { + parts.push(&bytes[s..i]); + start = None; + } + } else if start.is_none() { + start = Some(i); + } + } + + if let Some(s) = start { + parts.push(&bytes[s..]); + } + + parts +} + +/// Splits bytes by ASCII whitespace, returning at most maxsplit+1 parts. +fn bytes_splitn_whitespace(bytes: &[u8], maxsplit: usize) -> Vec<&[u8]> { + let mut parts = Vec::new(); + let mut start = None; + let mut count = 0; + + let trimmed = bytes_strip_whitespace_start(bytes); + let offset = bytes.len() - trimmed.len(); + + for (i, &b) in trimmed.iter().enumerate() { + if is_py_whitespace(b) { + if let Some(s) = start + && count < maxsplit + { + parts.push(&bytes[offset + s..offset + i]); + count += 1; + start = None; + } + } else if start.is_none() { + start = Some(i); + } + } + + if let Some(s) = start { + parts.push(&bytes[offset + s..]); + } + + parts +} + +/// Splits bytes by ASCII whitespace from the right, returning at most maxsplit+1 parts. +fn bytes_rsplitn_whitespace(bytes: &[u8], maxsplit: usize) -> Vec<&[u8]> { + let mut parts = Vec::new(); + let mut end = None; + let mut count = 0; + + let trimmed = bytes_strip_whitespace_end(bytes); + + for i in (0..trimmed.len()).rev() { + let b = trimmed[i]; + if is_py_whitespace(b) { + if let Some(e) = end + && count < maxsplit + { + parts.push(&trimmed[i + 1..e]); + count += 1; + end = None; + } + } else if end.is_none() { + end = Some(i + 1); + } + } + + if let Some(e) = end { + parts.push(&trimmed[..e]); + } + + parts.reverse(); + parts +} + +/// Implements Python's `bytes.splitlines([keepends])` method. +/// +/// Returns a list of the lines in the bytes, breaking at line boundaries. +fn bytes_splitlines<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let keepends = parse_bytes_splitlines_args(args, vm)?; + + let lines = Vec::new(); + let mut lines_guard = DropGuard::new(lines, vm); + let (lines, vm) = lines_guard.as_parts_mut(); + let mut start = 0; + let bytes = bytes.get(vm.heap); + let len = bytes.len(); + + while start < len { + vm.heap.tracker.check_memory_time_every(lines.len())?; + + let mut end = start; + let mut line_end = start; + + while end < len { + match bytes[end] { + b'\n' => { + line_end = end; + end += 1; + break; + } + b'\r' => { + line_end = end; + end += 1; + if end < len && bytes[end] == b'\n' { + end += 1; + } + break; + } + _ => { + end += 1; + line_end = end; + } + } + } + + let line = if keepends { + &bytes[start..end] + } else { + &bytes[start..line_end] + }; + lines.push(allocate_bytes(line.to_vec(), vm.heap)); + start = end; + } + + let (lines, vm) = lines_guard.into_parts(); + let list = List::new(lines); + let heap_id = vm.heap.allocate(HeapData::List(list)); + Ok(Value::Ref(heap_id)) +} + +/// Parses arguments for bytes.splitlines method. +fn parse_bytes_splitlines_args(args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let BytesSplitlinesArgs { keepends } = BytesSplitlinesArgs::from_args(args, vm)?; + let result = match keepends { + None => false, + Some(v) => { + let result = v.py_bool(vm); + v.drop_with(vm.heap); + result? + } + }; + Ok(result) +} + +/// Argument shape for `bytes.splitlines(keepends=False)`. CPython evaluates +/// `keepends` for truthiness rather than strict-typing, so the field stays as +/// a raw `Value` for `py_bool` to inspect. +#[derive(FromArgs)] +#[from_args(name = "splitlines")] +struct BytesSplitlinesArgs { + #[from_args(default)] + keepends: Option, +} + +/// Implements Python's `bytes.partition(sep)` method. +/// +/// Splits the bytes at the first occurrence of sep, and returns a 3-tuple. +fn bytes_partition<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let sep_value = args.get_one_arg("bytes.partition", vm.heap)?; + defer_drop!(sep_value, vm); + let sep = extract_bytes_only(sep_value, vm)?; + + if sep.is_empty() { + return Err(ExcType::value_error_empty_separator()); + } + + let bytes = bytes.get(vm.heap); + let (before, sep_found, after) = match find_subsequence(bytes, sep, vm.heap)? { + Some(pos) => (bytes[..pos].to_vec(), sep.to_vec(), bytes[pos + sep.len()..].to_vec()), + None => (bytes.to_vec(), Vec::new(), Vec::new()), + }; + + let before_val = allocate_bytes(before, vm.heap); + let sep_val = allocate_bytes(sep_found, vm.heap); + let after_val = allocate_bytes(after, vm.heap); + + Ok(super::allocate_tuple( + smallvec![before_val, sep_val, after_val], + vm.heap, + )) +} + +/// Implements Python's `bytes.rpartition(sep)` method. +/// +/// Splits the bytes at the last occurrence of sep, and returns a 3-tuple. +fn bytes_rpartition<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let sep_value = args.get_one_arg("bytes.rpartition", vm.heap)?; + defer_drop!(sep_value, vm); + let sep = extract_bytes_only(sep_value, vm)?; + + if sep.is_empty() { + return Err(ExcType::value_error_empty_separator()); + } + + let bytes = bytes.get(vm.heap); + let (before, sep_found, after) = match rfind_subsequence(bytes, sep, vm.heap)? { + Some(pos) => (bytes[..pos].to_vec(), sep.to_vec(), bytes[pos + sep.len()..].to_vec()), + None => (Vec::new(), Vec::new(), bytes.to_vec()), + }; + + let before_val = allocate_bytes(before, vm.heap); + let sep_val = allocate_bytes(sep_found, vm.heap); + let after_val = allocate_bytes(after, vm.heap); + + Ok(super::allocate_tuple( + smallvec![before_val, sep_val, after_val], + vm.heap, + )) +} + +// ============================================================================= +// Replace/padding methods +// ============================================================================= + +/// Implements Python's `bytes.replace(old, new[, count])` method. +/// +/// Returns a copy with all occurrences of old replaced by new. +fn bytes_replace<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let (old, new, count) = parse_bytes_replace_args("bytes.replace", args, vm)?; + + let bytes = bytes.get(vm.heap); + + check_replace_size(bytes.len(), old.len(), new.len(), count, &vm.heap.tracker)?; + + let result = if count < 0 { + bytes_replace_all(bytes, &old, &new, vm.heap)? + } else { + let n = usize::try_from(count).unwrap_or(usize::MAX); + bytes_replace_n(bytes, &old, &new, n, vm.heap)? + }; + + Ok(allocate_bytes(result, vm.heap)) +} + +/// Parses arguments for bytes.replace method. +fn parse_bytes_replace_args(_method: &str, args: ArgValues, vm: &mut VM<'_>) -> RunResult<(Vec, Vec, i64)> { + let BytesReplaceArgs { old, new, count } = BytesReplaceArgs::from_args(args, vm)?; + defer_drop!(old, vm); + defer_drop!(new, vm); + defer_drop!(count, vm); + + let old_b = extract_bytes_only(old, vm)?.to_owned(); + let new_b = extract_bytes_only(new, vm)?.to_owned(); + let count_i = count.as_int(vm)?; + Ok((old_b, new_b, count_i)) +} + +/// Argument shape for `bytes.replace(old, new, count=-1)`. +#[derive(FromArgs)] +#[from_args(name = "replace")] +struct BytesReplaceArgs { + old: Value, + new: Value, + #[from_args(default = Value::Int(-1))] + count: Value, +} + +/// Replaces all occurrences of `old` with `new` in bytes. +/// +/// Checks the time limits periodically during potentially long replacement +/// operations on large byte sequences. +fn bytes_replace_all(bytes: &[u8], old: &[u8], new: &[u8], heap: &Heap) -> Result, ResourceError> { + if old.is_empty() { + // Empty pattern: insert new before each byte and at the end + let mut result = Vec::with_capacity(bytes.len() + new.len() * (bytes.len() + 1)); + for (i, &b) in bytes.iter().enumerate() { + heap.tracker.check_memory_time_every(i)?; + result.extend_from_slice(new); + result.push(b); + } + result.extend_from_slice(new); + Ok(result) + } else if let Some(finder) = finder_for(old, bytes) { + let mut result = Vec::new(); + let mut start = 0; + let mut matches = 0usize; + while let Some(pos) = find_with(&finder, &bytes[start..], heap)? { + heap.tracker.check_memory_time_every(matches)?; + matches += 1; + result.extend_from_slice(&bytes[start..start + pos]); + result.extend_from_slice(new); + start = start + pos + old.len(); + } + result.extend_from_slice(&bytes[start..]); + Ok(result) + } else { + replace_nothing(bytes, heap) + } +} + +/// Copies `bytes` unchanged, for a `replace` that cannot match anything. +/// +/// Polls before copying: the callers reaching here skip the scan loop, and +/// with it the `check_time()` it would have run first, so without this a +/// no-match `replace` over a large input would never touch the clock. +fn replace_nothing(bytes: &[u8], heap: &Heap) -> Result, ResourceError> { + heap.tracker.check_time()?; + Ok(bytes.to_vec()) +} + +/// Replaces at most n occurrences of `old` with `new` in bytes. +/// +/// Checks the time limits periodically during potentially long replacement +/// operations on large byte sequences. +fn bytes_replace_n(bytes: &[u8], old: &[u8], new: &[u8], n: usize, heap: &Heap) -> Result, ResourceError> { + // `count=0` permits no replacements, so return before `finder_for` + // preprocesses `old` — that runs ahead of any `check_time()`. + if n == 0 { + return replace_nothing(bytes, heap); + } + if old.is_empty() { + // Empty pattern: insert new before each byte (up to n times) + let mut result = Vec::new(); + let mut count = 0; + for (i, &b) in bytes.iter().enumerate() { + heap.tracker.check_memory_time_every(i)?; + if count < n { + result.extend_from_slice(new); + count += 1; + } + result.push(b); + } + if count < n { + result.extend_from_slice(new); + } + Ok(result) + } else if let Some(finder) = finder_for(old, bytes) { + let mut result = Vec::new(); + let mut start = 0; + let mut count = 0; + while count < n { + heap.tracker.check_memory_time_every(count)?; + if let Some(pos) = find_with(&finder, &bytes[start..], heap)? { + result.extend_from_slice(&bytes[start..start + pos]); + result.extend_from_slice(new); + start = start + pos + old.len(); + count += 1; + } else { + break; + } + } + result.extend_from_slice(&bytes[start..]); + Ok(result) + } else { + replace_nothing(bytes, heap) + } +} + +/// Implements Python's `bytes.center(width[, fillbyte])` method. +/// +/// Returns centered in a bytes of length width. +fn bytes_center<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let (width, fillbyte) = parse_bytes_justify_args("bytes.center", args, vm)?; + + let bytes = bytes.get(vm.heap); + let len = bytes.len(); + + let result = if width <= len { + bytes.to_vec() + } else { + check_repeat_size(width, 1, &vm.heap.tracker)?; + let total_pad = width - len; + // CPython puts the odd fill unit on the left only when `width` is also odd. + let left_pad = total_pad / 2 + (total_pad & width & 1); + let right_pad = total_pad - left_pad; + let mut result = Vec::with_capacity(width); + for _ in 0..left_pad { + result.push(fillbyte); + } + result.extend_from_slice(bytes); + for _ in 0..right_pad { + result.push(fillbyte); + } + result + }; + + Ok(allocate_bytes(result, vm.heap)) +} + +/// Implements Python's `bytes.ljust(width[, fillbyte])` method. +/// +/// Returns left-justified in a bytes of length width. +fn bytes_ljust<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let (width, fillbyte) = parse_bytes_justify_args("bytes.ljust", args, vm)?; + + let bytes = bytes.get(vm.heap); + let len = bytes.len(); + + let result = if width <= len { + bytes.to_vec() + } else { + check_repeat_size(width, 1, &vm.heap.tracker)?; + let pad = width - len; + let mut result = Vec::with_capacity(width); + result.extend_from_slice(bytes); + for _ in 0..pad { + result.push(fillbyte); + } + result + }; + + Ok(allocate_bytes(result, vm.heap)) +} + +/// Implements Python's `bytes.rjust(width[, fillbyte])` method. +/// +/// Returns right-justified in a bytes of length width. +fn bytes_rjust<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let (width, fillbyte) = parse_bytes_justify_args("bytes.rjust", args, vm)?; + + let bytes = bytes.get(vm.heap); + let len = bytes.len(); + + let result = if width <= len { + bytes.to_vec() + } else { + check_repeat_size(width, 1, &vm.heap.tracker)?; + let pad = width - len; + let mut result = Vec::with_capacity(width); + for _ in 0..pad { + result.push(fillbyte); + } + result.extend_from_slice(bytes); + result + }; + + Ok(allocate_bytes(result, vm.heap)) +} + +/// Parses arguments for bytes justify methods (center, ljust, rjust). +fn parse_bytes_justify_args(method: &str, args: ArgValues, vm: &mut VM<'_>) -> RunResult<(usize, u8)> { + let pos = args.into_pos_only(method, vm.heap)?; + defer_drop!(pos, vm); + + // Free functions rather than closures: `extract_width` needs `&mut VM` for a + // user `__index__`, which cannot coexist with a second closure capturing the + // same `vm` immutably. + match pos.as_slice() { + [width_value] => Ok((extract_justify_width(width_value, vm)?, b' ')), + [width_value, fillbyte_value] => { + // Width first, so its error wins for `center('x', 'y')` as in CPython. + let width = extract_justify_width(width_value, vm)?; + Ok((width, extract_justify_fill(method, fillbyte_value, vm)?)) + } + [] => Err(ExcType::type_error_at_least(method, 1, 0)), + _ => Err(ExcType::type_error_at_most(method, 2, pos.len())), + } +} + +/// Reads a justify method's `width`, clamping negatives to zero as CPython does. +fn extract_justify_width(value: &Value, vm: &mut VM<'_>) -> RunResult { + let width = value.as_int(vm)?; + Ok(if width < 0 { + 0 + } else { + usize::try_from(width).unwrap_or(usize::MAX) + }) +} + +/// Reads a justify method's `fillbyte`, which must be exactly one byte. +fn extract_justify_fill(method: &str, value: &Value, vm: &VM<'_>) -> RunResult { + let fill_bytes = extract_bytes_only(value, vm)?; + if fill_bytes.len() == 1 { + Ok(fill_bytes[0]) + } else { + Err(ExcType::type_error(format!( + "{method}() argument 2 must be a byte string of length 1, not bytes of length {}", + fill_bytes.len() + ))) + } +} + +/// Implements Python's `bytes.zfill(width)` method. +/// +/// Returns a copy of the bytes left filled with ASCII '0' digits. +fn bytes_zfill<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let width_value = args.get_one_arg("bytes.zfill", vm.heap)?; + defer_drop!(width_value, vm); + let width_i64 = width_value.as_int(vm)?; + + let width = if width_i64 < 0 { + 0 + } else { + usize::try_from(width_i64).unwrap_or(usize::MAX) + }; + + let bytes = bytes.get(vm.heap); + let len = bytes.len(); + + let result = if width <= len { + bytes.to_vec() + } else { + check_repeat_size(width, 1, &vm.heap.tracker)?; + let pad = width - len; + let mut result = Vec::with_capacity(width); + + // Handle sign prefix + if !bytes.is_empty() && (bytes[0] == b'+' || bytes[0] == b'-') { + result.push(bytes[0]); + result.resize(pad + 1, b'0'); + result.extend_from_slice(&bytes[1..]); + } else { + result.resize(pad, b'0'); + result.extend_from_slice(bytes); + } + result + }; + + Ok(allocate_bytes(result, vm.heap)) +} + +// ============================================================================= +// Join method +// ============================================================================= + +/// Implements Python's `bytes.join(iterable)` method. +/// +/// Joins elements of the iterable with the separator bytes. +fn bytes_join<'h>(separator: &impl HeapView<'h, [u8]>, iterable: Value, vm: &mut VM<'h>) -> RunResult { + // Checked up front: a user `__iter__` can raise anything, and rewriting that + // as "can only join an iterable" would hide it, resource errors included. + if !iterable.py_is_iterable(vm) { + iterable.drop_with(vm); + return Err(ExcType::type_error_join_not_iterable()); + } + let iter = iterable.into_py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iter, vm); + let mut iter = iter.read(vm); + + let mut result = Vec::new(); + let mut index = 0usize; + + while let Some(item) = iter.py_next(vm)? { + defer_drop!(item, vm); + + if index > 0 { + result.extend_from_slice(separator.get(vm.heap)); + } + + // Check item is bytes and extract its content + match item { + Value::InternBytes(id) => { + result.extend_from_slice(vm.interns.get_bytes(*id)); + } + Value::Ref(heap_id) => { + if let HeapData::Bytes(b) = vm.heap.get(*heap_id) { + result.extend_from_slice(b.as_slice()); + } else { + let t = item.py_type_name(vm); + return Err(ExcType::type_error(format!( + "sequence item {index}: expected a bytes-like object, {t} found" + ))); + } + } + _ => { + let t = item.py_type_name(vm); + return Err(ExcType::type_error(format!( + "sequence item {index}: expected a bytes-like object, {t} found" + ))); + } + } + index += 1; + } + + Ok(allocate_bytes(result, vm.heap)) +} + +// ============================================================================= +// Hex method +// ============================================================================= + +/// Implements Python's `bytes.hex([sep[, bytes_per_sep]])` method. +/// +/// Returns a string containing the hexadecimal representation of the bytes. +fn bytes_hex<'h>(bytes: &impl HeapView<'h, [u8]>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let (sep, bytes_per_sep) = parse_bytes_hex_args(args, vm)?; + + let bytes = bytes.get(vm.heap); + let hex_chars: Vec = bytes + .iter() + .flat_map(|b| { + let hi = (b >> 4) & 0xf; + let lo = b & 0xf; + let hi_char = if hi < 10 { + (b'0' + hi) as char + } else { + (b'a' + hi - 10) as char + }; + let lo_char = if lo < 10 { + (b'0' + lo) as char + } else { + (b'a' + lo - 10) as char + }; + [hi_char, lo_char] + }) + .collect(); + + let result = if let Some(sep) = sep { + if bytes_per_sep == 0 || bytes.is_empty() { + hex_chars.iter().collect() + } else { + // Insert separator every `bytes_per_sep` bytes (2*bytes_per_sep hex chars). + // `saturating_mul` guards against overflow when `bytes_per_sep == i64::MIN`, + // whose `unsigned_abs()` is `2^63` and would wrap `* 2` to zero, triggering + // a panic in `chunks(0)` below. + let chars_per_group = usize::try_from(bytes_per_sep.unsigned_abs()) + .unwrap_or(usize::MAX) + .saturating_mul(2); + let mut result = String::new(); + + if bytes_per_sep > 0 { + // Positive: count from right, so partial group is at the START + let total_len = hex_chars.len(); + let first_chunk_len = total_len % chars_per_group; + let first_chunk_len = if first_chunk_len == 0 { + chars_per_group + } else { + first_chunk_len + }; + + result.extend(&hex_chars[..first_chunk_len]); + for chunk in hex_chars[first_chunk_len..].chunks(chars_per_group) { + result.push(sep); + result.extend(chunk); + } + } else { + // Negative: count from left, so partial group is at the END + for (i, chunk) in hex_chars.chunks(chars_per_group).enumerate() { + if i > 0 { + result.push(sep); + } + result.extend(chunk); + } + } + result + } + } else { + hex_chars.iter().collect() + }; + + Ok(super::str::allocate_string(result, vm.heap)) +} + +/// Parses arguments for bytes.hex method. +fn parse_bytes_hex_args(args: ArgValues, vm: &mut VM<'_>) -> RunResult<(Option, i64)> { + let BytesHexArgs { sep, bytes_per_sep } = BytesHexArgs::from_args(args, vm)?; + defer_drop!(sep, vm); + defer_drop!(bytes_per_sep, vm); + + let Some(sep_value) = (match &sep { + Value::None => None, + v => Some(v), + }) else { + // CPython treats absent `sep` as "no separator", regardless of `bytes_per_sep`. + return Ok((None, 1)); + }; + + let sep_bytes = match sep_value { + Value::InternString(id) => vm.interns.get_str(*id).as_bytes(), + Value::InternBytes(id) => vm.interns.get_bytes(*id), + Value::Ref(heap_id) => match vm.heap.get(*heap_id) { + HeapData::Str(s) => s.as_bytes(), + HeapData::Bytes(b) => b.as_slice(), + _ => return Err(ExcType::type_error("sep must be str or bytes")), + }, + _ => return Err(ExcType::type_error("sep must be str or bytes")), + }; + + let sep_char = match sep_bytes { + [b] if b.is_ascii() => *b as char, + _ => return Err(SimpleException::new_msg(ExcType::ValueError, "sep must be a single ASCII character").into()), + }; + + let bytes_per_sep = match bytes_per_sep { + Value::None => 1, + bps_value => { + // CPython parses `bytes_per_sep` with the `i` format (C int), so values outside + // c_int range raise OverflowError before any computation happens. + let raw = bps_value.as_int(vm)?; + c_int::try_from(raw).map_err(|_| ExcType::overflow_c_int())?.into() + } + }; + + Ok((Some(sep_char), bytes_per_sep)) +} + +/// `bytes.hex([sep[, bytes_per_sep]])` — CPython accepts `sep` and +/// `bytes_per_sep` as positional-or-keyword, but Monty has not threaded +/// kwarg dispatch through to the type-checking body yet. +/// `kwargs_not_supported_yet` rejects any kwarg with +/// `NotImplementedError: bytes.hex() does not yet support keyword +/// arguments` (replacing the previous `TypeError: bytes.hex() takes no +/// keyword arguments` from `into_pos_only`) while the macro takes over +/// arity validation, upgrading the too-many-args wording from +/// `bytes.hex expected at most 2 arguments, got N` to CPython's +/// `bytes.hex() takes at most 2 arguments (N given)`. Fields become real +/// kwargs and the flag goes away when the kwarg dispatch is plumbed +/// through. +#[derive(FromArgs)] +#[from_args(name = "bytes.hex", style = c_named, at_most_total, kwargs_not_supported_yet)] +struct BytesHexArgs { + #[from_args(default = Value::None)] + sep: Value, + #[from_args(default = Value::None)] + bytes_per_sep: Value, +} + +// ============================================================================= +// fromhex classmethod +// ============================================================================= + +/// Implements Python's `bytes.fromhex(string)` classmethod. +/// +/// Creates bytes from a hexadecimal string. Whitespace is allowed between byte pairs, +/// but not between the two digits of a byte. +pub fn bytes_fromhex(args: ArgValues, vm: &mut VM<'_>) -> RunResult { + let hex_value = args.get_one_arg("bytes.fromhex", vm.heap)?; + defer_drop!(hex_value, vm); + + let hex_str = match hex_value { + Value::InternString(id) => vm.interns.get_str(*id), + Value::Ref(heap_id) => { + if let HeapData::Str(s) = vm.heap.get(*heap_id) { + s.as_str() + } else { + return Err(ExcType::type_error("fromhex() argument must be str, not bytes")); + } + } + _ => { + let t = hex_value.py_type_name(vm); + return Err(ExcType::type_error(format!("fromhex() argument must be str, not {t}"))); + } + }; + + // CPython allows whitespace BETWEEN byte pairs, but NOT within a pair. + // - "de ad" is valid (whitespace between pairs) + // - "d e" or "0 1" are NOT valid (whitespace within a pair) + // - " 01 " is valid (whitespace before/after) + // + // Error messages: + // - Invalid char (including whitespace in wrong place): "non-hexadecimal number found ... at position X" + // - Odd number of valid hex digits: "must contain an even number of hexadecimal digits" + + let mut result = Vec::new(); + let mut chars = hex_str.chars().enumerate().peekable(); + + loop { + // Skip whitespace BETWEEN byte pairs (before the high nibble) + while chars.peek().is_some_and(|(_, c)| c.is_whitespace()) { + chars.next(); + } + + // Get high nibble + let Some((hi_pos, hi_char)) = chars.next() else { + break; // End of string - we're done + }; + + let Some(hi_val) = hex_char_to_value(hi_char) else { + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("non-hexadecimal number found in fromhex() arg at position {hi_pos}"), + ) + .into()); + }; + + // Get low nibble - must be IMMEDIATELY after high nibble (no whitespace) + let Some((lo_pos, lo_char)) = chars.next() else { + // End of string after high nibble = odd number of hex digits + return Err(SimpleException::new_msg( + ExcType::ValueError, + "fromhex() arg must contain an even number of hexadecimal digits", + ) + .into()); + }; + + let Some(lo_val) = hex_char_to_value(lo_char) else { + // Invalid character (including whitespace) in low nibble position + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("non-hexadecimal number found in fromhex() arg at position {lo_pos}"), + ) + .into()); + }; + + result.push((hi_val << 4) | lo_val); + } + + Ok(allocate_bytes(result, vm.heap)) +} + +/// Converts a hex character to its numeric value. +fn hex_char_to_value(c: char) -> Option { + match c { + '0'..='9' => Some(c as u8 - b'0'), + 'a'..='f' => Some(c as u8 - b'a' + 10), + 'A'..='F' => Some(c as u8 - b'A' + 10), + _ => None, + } +} + +// ============================================================================= +// Helper function for bytes allocation +// ============================================================================= + +/// Allocates bytes on the heap. +pub(crate) fn allocate_bytes(bytes: Vec, heap: &Heap) -> Value { + let heap_id = heap.allocate(HeapData::Bytes(Bytes::new(bytes))); + Value::Ref(heap_id) +} + +/// Source representation retained by a bytes iterator. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +enum BytesIteratorSource { + Intern(BytesId), + Heap(HeapId), +} + +/// Iterator yielding integer elements from bytes storage. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct BytesIterator { + source: BytesIteratorSource, + index: usize, +} + +impl BytesIterator { + /// Allocates an iterator over interned bytes. + pub(crate) fn from_intern(id: BytesId, vm: &mut VM<'_>) -> Value { + Self::allocate(BytesIteratorSource::Intern(id), vm) + } + + /// Allocates an iterator retaining heap bytes. + fn from_heap(id: HeapId, vm: &mut VM<'_>) -> Value { + Self::allocate(BytesIteratorSource::Heap(id), vm) + } + + /// Returns a retained heap source, if the bytes are not interned. + pub(crate) fn source_id(&self) -> Option { + match self.source { + BytesIteratorSource::Intern(_) => None, + BytesIteratorSource::Heap(id) => Some(id), + } + } + + /// Returns the number of bytes not yet yielded. + pub(crate) fn size_hint(&self, vm: &VM<'_>) -> usize { + self.as_slice(vm).len().saturating_sub(self.index) + } + + /// Borrows the source bytes. + fn as_slice<'a>(&self, vm: &'a VM<'_>) -> &'a [u8] { + match self.source { + BytesIteratorSource::Intern(id) => vm.interns.get_bytes(id), + BytesIteratorSource::Heap(id) => match vm.heap.get(id) { + HeapData::Bytes(bytes) => bytes.as_slice(), + _ => unreachable!("bytes iterator must retain bytes"), + }, + } + } + + /// Allocates an iterator and retains a heap source when present. + fn allocate(source: BytesIteratorSource, vm: &mut VM<'_>) -> Value { + let source_id = match source { + BytesIteratorSource::Heap(id) => Some(id), + BytesIteratorSource::Intern(_) => None, + }; + let id = vm.heap.allocate(HeapData::BytesIterator(Self { source, index: 0 })); + if let Some(source_id) = source_id { + vm.heap.inc_ref(source_id); + } + Value::Ref(id) + } +} + +impl HeapItem for BytesIterator { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + if let Some(id) = self.source_id() { + stack.push(id); + } + } +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, BytesIterator> { + fn py_is_iterable(&self, _: &VM<'h>) -> bool { + true + } + + fn py_type(&self, _: &VM<'h>) -> Type { + Type::BytesIterator + } + + fn py_len(&self, _: &VM<'h>) -> Option { + None + } + + fn py_eq_impl(&self, _: &Value, _: &mut VM<'h>) -> RunResult> { + Ok(None) + } + + fn py_iter(&self, vm: &mut VM<'h>) -> RunResult { + Ok(CallResult::Value(self.clone_value(vm.heap))) + } + + fn py_next(&mut self, vm: &mut VM<'h>) -> RunResult> { + let byte = { + let iter = self.get(vm.heap); + iter.as_slice(vm).get(iter.index).copied() + }; + if let Some(byte) = byte { + self.get_mut(vm.heap).index += 1; + Ok(Some(Value::Int(i64::from(byte)))) + } else { + Ok(None) + } + } +} + +/// Membership for `item in `, shared by heap and interned containers. +/// +/// CPython accepts a bytes-like probe (substring) or an integer (byte value); +/// an integer outside `range(0, 256)` is a `ValueError`, anything else a `TypeError`. +pub(crate) fn bytes_contains(container: &[u8], item: &Value, vm: &VM<'_>) -> RunResult { + // `None` marks an integer probe that cannot be a byte, keeping the range + // error in one place. A `LongInt` never fits in a `u8` by construction — it + // exists precisely because the value overflowed `i64`. + let byte = match item { + Value::Int(i) => Some(*i), + Value::Bool(b) => Some(i64::from(*b)), + Value::InternLongInt(_) => None, + Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::LongInt(_)) => None, + // A bytes-like probe is a substring test. + Value::InternBytes(_) | Value::Ref(_) => { + let needle = extract_bytes_only(item, vm)?; + // An empty needle is in everything, and `find_subsequence` rejects it. + return Ok(needle.is_empty() || find_subsequence(container, needle, vm.heap)?.is_some()); + } + other => { + return Err(ExcType::type_error(format!( + "a bytes-like object is required, not '{}'", + other.py_type_name(vm) + ))); + } + }; + match byte.and_then(|b| u8::try_from(b).ok()) { + Some(b) => Ok(container.contains(&b)), + None => Err(ExcType::value_error("byte must be in range(0, 256)")), + } +} diff --git a/crates/bashkit-monty/src/types/callable_iterator.rs b/crates/bashkit-monty/src/types/callable_iterator.rs new file mode 100644 index 000000000..9ca3c9237 --- /dev/null +++ b/crates/bashkit-monty/src/types/callable_iterator.rs @@ -0,0 +1,156 @@ +//! The `callable_iterator` produced by the two-argument `iter(callable, sentinel)`. +//! +//! Unlike every other iterator, this one re-enters Python on each step, which +//! drives the two unusual things about it: the heap borrow must be released +//! before the call (see [`HeapRead::py_next`]), and its two owned refs live in +//! the iterator itself rather than in a container it points at. + +use std::mem; + +use serde::{Deserialize, Serialize}; + +use crate::{ + args::ArgValues, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::RunResult, + heap::{DropGuard, HeapId, HeapItem, HeapObjectRead}, + types::{PyTrait, Type}, + value::Value, +}; + +/// Calls `callable()` for each item until a result compares `==` to `sentinel`. +/// +/// `callable` and `sentinel` are OWNED refs held directly here — not in a +/// referenced container — so `py_dec_ref_ids` and `for_each_child_id` must both +/// enumerate them or the GC will under-trace and free a live object. +#[derive(Debug, Serialize, Deserialize)] +pub(crate) struct CallableIterator { + /// Invoked with no arguments to produce each item. + callable: Value, + /// Iteration stops once a result compares `==` to this. + sentinel: Value, + /// Latches on exhaustion so a spent iterator never calls `callable` again. + done: bool, +} + +impl CallableIterator { + /// Takes ownership of `callable` and `sentinel` from the caller. + pub(crate) fn new(callable: Value, sentinel: Value) -> Self { + Self { + callable, + sentinel, + done: false, + } + } + + /// Invokes `on_child` for each heap id this iterator owns (GC trace hook). + pub(crate) fn for_each_child_id(&self, mut on_child: impl FnMut(HeapId)) { + if let Value::Ref(id) = &self.callable { + on_child(*id); + } + if let Value::Ref(id) = &self.sentinel { + on_child(*id); + } + } +} + +impl HeapItem for CallableIterator { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + self.callable.py_dec_ref_ids(stack); + self.sentinel.py_dec_ref_ids(stack); + } +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, CallableIterator> { + fn py_is_iterator(&self, _: &VM<'h>) -> bool { + true + } + + fn py_is_iterable(&self, _: &VM<'h>) -> bool { + true + } + + fn py_type(&self, _: &VM<'h>) -> Type { + Type::CallableIterator + } + + fn py_len(&self, _: &VM<'h>) -> Option { + None + } + + fn py_eq_impl(&self, _: &Value, _: &mut VM<'h>) -> RunResult> { + Ok(None) + } + + fn py_iter(&self, vm: &mut VM<'h>) -> RunResult { + Ok(CallResult::Value(self.clone_value(vm.heap))) + } + + /// Calls `callable()` and yields the result unless it `==` `sentinel`. + /// + /// The heap borrow is resolved to owned clones and released BEFORE the call: + /// `callable` re-enters Python and may reach this same iterator through a + /// nested `next()`, which would alias the `UnsafeCell` if a borrow were held + /// across it (`iter__reentrant.py` covers exactly that). + fn py_next(&mut self, vm: &mut VM<'h>) -> RunResult> { + let resolved = { + let this = self.get(vm.heap); + if this.done { + None + } else { + Some(( + this.callable.clone_with_heap(vm.heap), + this.sentinel.clone_with_heap(vm.heap), + )) + } + }; + let Some((callable, sentinel)) = resolved else { + return Ok(None); + }; + + let next = callable_next(callable, sentinel, vm)?; + if next.is_none() { + // Exhausted. CPython's `calliter_iternext` `Py_CLEAR`s both refs + // here, so a spent-but-still-referenced iterator does not pin the + // callable's captured state; take them out under the borrow and drop + // once it has ended. + let (callable, sentinel) = { + let this = self.get_mut(vm.heap); + this.done = true; + ( + mem::replace(&mut this.callable, Value::None), + mem::replace(&mut this.sentinel, Value::None), + ) + }; + callable.drop_with(vm); + sentinel.drop_with(vm); + } + Ok(next) + } +} + +/// Calls `callable()` once, returning `None` when the result `==` `sentinel` or +/// the call raises `StopIteration`. +/// +/// Takes both values by ownership: the caller has already cloned them out of the +/// iterator so that no heap borrow is live across the re-entrant call. +fn callable_next(callable: Value, sentinel: Value, vm: &mut VM<'_>) -> RunResult> { + defer_drop!(callable, vm); + defer_drop!(sentinel, vm); + let result = match vm.evaluate_function(callable, ArgValues::Empty) { + Ok(result) => result, + // CPython's `calliter_iternext` swallows `StopIteration` from the + // callable and reports exhaustion, exactly as for a `__next__`. + Err(e) if e.is_stop_iteration() => return Ok(None), + Err(e) => return Err(e), + }; + let mut result = DropGuard::new(result, vm); + let (result_ref, vm) = result.as_parts_mut(); + if result_ref.py_eq(sentinel, vm)? { + // result == sentinel: iterator exhausted; `result` dropped by the guard. + Ok(None) + } else { + Ok(Some(result.into_inner())) + } +} diff --git a/crates/bashkit-monty/src/types/class.rs b/crates/bashkit-monty/src/types/class.rs new file mode 100644 index 000000000..d688025ae --- /dev/null +++ b/crates/bashkit-monty/src/types/class.rs @@ -0,0 +1,235 @@ +use std::fmt::Write; + +use monty_types::MontyUuid; + +use super::{Dict, LazyHeapSet, PyTrait, Type, attribute_name_value}; +use crate::{ + args::ArgValues, + boundary_uuid::create_uuid, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + hash::{HashValue, identity_hash}, + heap::{ + BorrowedHeapReadMut, DropGuard, DropWithContext, HeapId, HeapItem, HeapObjectRead, HeapReadMut, HeapReader, + heap_read_ref_as_field_mut, + }, + intern::{Interns, StringId}, + types::{Union, str::allocate_string}, + value::{EitherStr, Value}, +}; + +/// A user-defined class object created by a `class Foo: ...` statement. +/// +/// Holds the class name and a `namespace` [`Dict`] mapping member names to values: +/// methods (stored as `DefFunction`/`Closure` values) and class variables. The +/// class's own [`HeapId`] is its type identity — `type(x) is Foo` and `isinstance` +/// work via reference identity, so there is no separate type-id counter. +/// +/// Calling a class (`Foo(...)`) constructs an [`Instance`](super::Instance); see +/// `instantiate_class` in the VM's call module. Inheritance is not yet supported, +/// but a future `bases: Vec` field would slot in here without disturbing +/// the rest of the design. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub(crate) struct Class { + /// Class name (e.g. `Foo`), used for `repr` and `__name__`. Interned for + /// compiled `class` statements; heap-owned for classes created at runtime + /// via the 3-arg `type(name, bases, dict)` form, whose name cannot be + /// interned because the intern table is frozen after prepare. + name: EitherStr, + /// Members: method name / class-variable name -> value. + namespace: Dict, + /// Boundary identity, generated lazily the first time the class (or one of + /// its instances) crosses to the host; dumped with the heap so it stays + /// stable across restores. + uuid: Option, +} + +impl Class { + /// Creates a new class object from its name and member namespace. + #[must_use] + pub fn new(name: EitherStr, namespace: Dict) -> Self { + Self { + name, + namespace, + uuid: None, + } + } + + /// Boundary identity of the class, generated and stored on first use so + /// repeated crossings (and dump/restore) observe the same id. Only + /// `Heap::boundary_uuid` may call this: it also indexes the new id. + pub(crate) fn boundary_uuid(&mut self) -> MontyUuid { + *self.uuid.get_or_insert_with(create_uuid) + } + + /// The boundary identity, if the class (or an instance) has crossed to the host. + #[must_use] + pub fn uuid(&self) -> Option { + self.uuid + } + + /// Returns the class name (interned or heap-owned). + #[must_use] + pub fn name(&self) -> &EitherStr { + &self.name + } + + /// Returns a reference to the class member namespace. + #[must_use] + pub fn namespace(&self) -> &Dict { + &self.namespace + } +} + +impl<'h> HeapReadMut<'h, Class> { + /// Borrows the inline namespace for reader-gated attribute mutation. + fn namespace_mut(&self) -> BorrowedHeapReadMut<'_, 'h, Dict> { + heap_read_ref_as_field_mut!(self, Class, namespace) + } + + /// Sets a class attribute (`Foo.x = 1`), returning the previous value (if any) + /// for the caller to drop. Takes ownership of both `name` and `value`. + /// + /// Existing instances observe the change immediately: instance attribute reads + /// fall through to this namespace. + pub fn set_attr(&self, name: Value, value: Value, vm: &mut VM<'h>) -> RunResult> { + self.namespace_mut().set(name, value, vm) + } + + /// [`set_attr`](Self::set_attr) for a dump upgrade, which has no VM and + /// cannot fail: see `HeapRead::::set_interned_str`. + pub(crate) fn set_interned_attr( + &self, + name: StringId, + value: Value, + heap: &mut HeapReader<'h>, + interns: &Interns, + ) -> Option { + self.namespace_mut().set_interned_str(name, value, heap, interns) + } + + /// Removes a class attribute, returning it for the caller to drop. + /// + /// Only `@dataclass` needs this, to clear the `field()` object a class body + /// bound for a factory-only field — CPython's decorator `delattr`s it. + pub fn pop_attr(&self, name: &Value, vm: &mut VM<'h>) -> RunResult> { + Ok(self.namespace_mut().pop(name, vm)?.map(|(key, value)| { + key.drop_with(vm); + value + })) + } +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, Class> { + /// Constructing an instance, which runs `__init__` as an ordinary frame. + fn py_call(&mut self, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + vm.instantiate_class(self.id(), args) + } + + fn py_type(&self, _vm: &VM<'h>) -> Type { + // The type of a class object is `type` (matching `type(Foo) is type`). + Type::Type + } + + fn py_len(&self, _vm: &VM<'h>) -> Option { + None + } + + fn py_or_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + Union::heap_or(self, other, vm) + } + + fn py_ror_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + Union::heap_ror(self, other, vm) + } + + /// `Foo[int]`: a class's `__class_getitem__` is never looked up, so the + /// wording is CPython's for a type without one. + fn py_getitem(&self, _key: &Value, vm: &mut VM<'h>) -> RunResult { + Err(ExcType::type_error_type_not_subscriptable( + self.get(vm.heap).name.as_str(vm.interns), + )) + } + + fn py_set_attr(&mut self, name: &EitherStr, value: Value, vm: &mut VM<'h>) -> RunResult<()> { + let mut value_guard = DropGuard::new(value, vm); + let name = attribute_name_value(name, value_guard.ctx()); + let (value, vm) = value_guard.into_parts(); + let old_value = self.set_attr(name, value, vm)?; + old_value.drop_with(vm); + Ok(()) + } + + fn py_eq_impl(&self, _other: &Value, _vm: &mut VM<'h>) -> RunResult> { + // Classes return `NotImplemented`; rich equality's final identity + // fallback makes a class equal only to itself. + Ok(None) + } + + fn py_hash(&self, _vm: &mut VM<'h>) -> RunResult> { + // Class objects hash by identity (like CPython type objects). + Ok(Some(identity_hash(self.id()))) + } + + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, _heap_ids: &mut LazyHeapSet) -> RunResult<()> { + Ok(write!(f, "", self.get(vm.heap).name.as_str(vm.interns))?) + } + + fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { + let attr_str = attr.as_str(vm.interns); + // `Foo.__name__` returns the class name — before the namespace lookup + // because in CPython `type.__name__` is a metaclass data descriptor that + // shadows a same-named class-dict member (`class Foo: __name__ = 'bar'` + // still reads `'Foo'`; only instances see the member). + if attr_str == "__name__" { + let name = self.get(vm.heap).name.as_str(vm.interns).to_owned(); + return Ok(Some(CallResult::Value(allocate_string(name, vm.heap)))); + } + // Otherwise look up a member (method or class variable) in the namespace. + match self.get(vm.heap).namespace.get_by_str(attr_str, vm.heap, vm.interns) { + Some(value) => Ok(Some(CallResult::Value(value.clone_with_heap(vm.heap)))), + None => Err(ExcType::attribute_error_type( + self.get(vm.heap).name.as_str(vm.interns), + attr_str, + )), + } + } + + fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { + let attr_str = attr.as_str(vm.interns); + // `__name__` is a synthesized string, not a namespace member (see + // `py_getattr`), so calling it goes through the normal callable + // dispatch and raises CPython's `TypeError: 'str' object is not + // callable` rather than a spurious `AttributeError`. + if attr_str == "__name__" { + let name = self.get(vm.heap).name.as_str(vm.interns).to_owned(); + let name_val = allocate_string(name, vm.heap); + defer_drop!(name_val, vm); + return vm.call_function(name_val, args); + } + // `Foo.method(args)` calls the raw (unbound) member with the given args — + // no `self` is inserted, the caller passes the instance explicitly. + let member = self + .get(vm.heap) + .namespace + .get_by_str(attr_str, vm.heap, vm.interns) + .map(|v| v.clone_with_heap(vm.heap)); + if let Some(member) = member { + defer_drop!(member, vm); + vm.call_function(member, args) + } else { + args.drop_with(vm); + Err(ExcType::attribute_error_type( + self.get(vm.heap).name.as_str(vm.interns), + attr_str, + )) + } + } +} + +impl HeapItem for Class { + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + self.namespace.py_dec_ref_ids(stack); + } +} diff --git a/crates/bashkit-monty/src/types/complex.rs b/crates/bashkit-monty/src/types/complex.rs new file mode 100644 index 000000000..e0122c13b --- /dev/null +++ b/crates/bashkit-monty/src/types/complex.rs @@ -0,0 +1,767 @@ +//! Python `complex` implementation. +//! +//! A complex number is two `f64`s, too wide for an immediate `Value`, so it lives on the +//! heap as a leaf `HeapData::Complex` entry (no references, never GC-tracked). Arithmetic +//! follows CPython's `complexobject.c`: the C99 Annex G recovery of infinities in products +//! and quotients, the small-integer power fast path, and the 3.14 mixed-mode rules, under +//! which a real operand only touches the part it combines with (`1j * inf` is `nan+infj` +//! but `(1+1j) * inf` is `inf+infj`). + +use std::fmt::Write; + +use monty_types::FormatComplex; + +use crate::{ + args::{ArgValues, FromArgs, FromValue, FromValueFail}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + hash::{HashValue, hash_f64}, + heap::{Heap, HeapData, HeapId, HeapItem, HeapObjectRead}, + intern::StaticStrings, + py_value::PyValue, + types::{ + LazyHeapSet, PyTrait, Type, + str::{StringRepr, allocate_string}, + r#type::strip_underscores, + }, + value::{EitherStr, Value, eq_f64}, +}; + +/// A Python `complex`: real and imaginary IEEE doubles. +/// +/// Plain data with no heap references; every operation returns a fresh value +/// because the type is immutable. +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +pub struct Complex { + /// The real part. + #[serde(rename = "R")] + pub real: f64, + /// The imaginary part. + #[serde(rename = "I")] + pub imag: f64, +} + +/// The multiplicative identity, `1+0j`. +const ONE: Complex = Complex::new(1.0, 0.0); + +/// Exponents with an integral real part up to this magnitude use repeated +/// squaring (CPython's `c_powi`), which is exact for small powers. +const POWI_MAX_EXPONENT: f64 = 100.0; + +impl Complex { + /// Builds a complex from its parts. + #[must_use] + pub const fn new(real: f64, imag: f64) -> Self { + Self { real, imag } + } + + /// Allocates this complex on the heap, handing back the owning value. + pub(crate) fn into_value(self, heap: &Heap) -> Value { + Value::Ref(heap.allocate(HeapData::Complex(self))) + } + + /// `-z`. + fn neg(self) -> Self { + Self::new(-self.real, -self.imag) + } + + /// `z.conjugate()`. + fn conjugate(self) -> Self { + Self::new(self.real, -self.imag) + } + + /// Whether both parts are zero, ignoring the sign of zero. + fn is_zero(self) -> bool { + self.real == 0.0 && self.imag == 0.0 + } + + /// Python `==` between two complexes: part-wise IEEE equality, so `nan` + /// is unequal to itself and `-0.0` equals `0.0`. + fn eq(self, other: Self) -> bool { + self.real == other.real && self.imag == other.imag + } + + /// `abs(z)`, CPython's `_Py_c_abs`: `inf` if either part is infinite (even + /// alongside `nan`), `nan` if either is `nan`, else `hypot`, which raises + /// `OverflowError` when finite parts overflow. + pub(crate) fn abs(self) -> RunResult { + if self.real.is_infinite() || self.imag.is_infinite() { + Ok(f64::INFINITY) + } else if self.real.is_nan() || self.imag.is_nan() { + Ok(f64::NAN) + } else { + let result = self.real.hypot(self.imag); + if result.is_infinite() { + Err(ExcType::overflow_error("absolute value too large")) + } else { + Ok(result) + } + } + } + + /// `z * w`, CPython's `_Py_c_prod`, recovering an infinite result that the + /// naive formula turns into `nan+nanj` (C11 Annex G.5.1). + fn mul(self, other: Self) -> Self { + let (mut a, mut b, mut c, mut d) = (self.real, self.imag, other.real, other.imag); + let (ac, bd, ad, bc) = (a * c, b * d, a * d, b * c); + let result = Self::new(ac - bd, ad + bc); + if !(result.real.is_nan() && result.imag.is_nan()) { + return result; + } + let mut recalc = false; + if a.is_infinite() || b.is_infinite() { + // Box the infinity and zero the nans in the other factor. + a = boxed_infinity(a); + b = boxed_infinity(b); + c = nan_to_zero(c); + d = nan_to_zero(d); + recalc = true; + } + if c.is_infinite() || d.is_infinite() { + c = boxed_infinity(c); + d = boxed_infinity(d); + a = nan_to_zero(a); + b = nan_to_zero(b); + recalc = true; + } + if !recalc && (ac.is_infinite() || bd.is_infinite() || ad.is_infinite() || bc.is_infinite()) { + // An intermediate product overflowed: drop the nans and rescale. + a = nan_to_zero(a); + b = nan_to_zero(b); + c = nan_to_zero(c); + d = nan_to_zero(d); + recalc = true; + } + if recalc { + Self::new(f64::INFINITY * (a * c - b * d), f64::INFINITY * (a * d + b * c)) + } else { + result + } + } + + /// `z / w`, CPython's `_Py_c_quot`: `None` for a zero divisor (C's `EDOM`), + /// otherwise Smith's scaled division with the Annex G.5.2 recovery of + /// infinities and zeros. + fn div(self, den: Self) -> Option { + let num = self; + let abs_breal = den.real.abs(); + let abs_bimag = den.imag.abs(); + let mut result = if abs_breal >= abs_bimag { + if abs_breal == 0.0 { + return None; + } + let ratio = den.imag / den.real; + let denom = den.real + den.imag * ratio; + Self::new( + (num.real + num.imag * ratio) / denom, + (num.imag - num.real * ratio) / denom, + ) + } else if abs_bimag >= abs_breal { + let ratio = den.real / den.imag; + let denom = den.real * ratio + den.imag; + Self::new( + (num.real * ratio + num.imag) / denom, + (num.imag * ratio - num.real) / denom, + ) + } else { + // At least one part of the divisor is nan. + Self::new(f64::NAN, f64::NAN) + }; + if result.real.is_nan() && result.imag.is_nan() { + if (num.real.is_infinite() || num.imag.is_infinite()) && den.real.is_finite() && den.imag.is_finite() { + let x = boxed_infinity(num.real); + let y = boxed_infinity(num.imag); + result = Self::new( + f64::INFINITY * (x * den.real + y * den.imag), + f64::INFINITY * (y * den.real - x * den.imag), + ); + } else if (abs_breal.is_infinite() || abs_bimag.is_infinite()) + && num.real.is_finite() + && num.imag.is_finite() + { + let x = boxed_infinity(den.real); + let y = boxed_infinity(den.imag); + result = Self::new(0.0 * (num.real * x + num.imag * y), 0.0 * (num.imag * x - num.real * y)); + } + } + Some(result) + } + + /// `r / z` for a real dividend, CPython 3.14's `_Py_rc_quot`: the scaled + /// division of [`div`](Self::div) with the dividend's zero imaginary part + /// never entering the arithmetic, which changes the sign of zero results. + fn div_into(real: f64, den: Self) -> Option { + let abs_breal = den.real.abs(); + let abs_bimag = den.imag.abs(); + let mut result = if abs_breal >= abs_bimag { + if abs_breal == 0.0 { + return None; + } + let ratio = den.imag / den.real; + let denom = den.real + den.imag * ratio; + Self::new(real / denom, (-real * ratio) / denom) + } else if abs_bimag >= abs_breal { + let ratio = den.real / den.imag; + let denom = den.real * ratio + den.imag; + Self::new((real * ratio) / denom, -real / denom) + } else { + // At least one part of the divisor is nan. + Self::new(f64::NAN, f64::NAN) + }; + // Unlike the complex quotient, only an infinite divisor is recovered; + // an infinite real dividend stays `nan+nanj`. + if result.real.is_nan() + && result.imag.is_nan() + && (abs_breal.is_infinite() || abs_bimag.is_infinite()) + && real.is_finite() + { + let x = boxed_infinity(den.real); + let y = boxed_infinity(den.imag); + result = Self::new(0.0 * (real * x), 0.0 * (-real * y)); + } + Some(result) + } + + /// `z ** w`, CPython's `complex_pow`: a small integral exponent uses exact + /// repeated squaring, anything else the polar form. A zero base with a + /// negative or non-real exponent raises `ZeroDivisionError`; an infinite + /// component in the result (C's `ERANGE`) raises `OverflowError`. + pub(crate) fn pow(self, exp: Self) -> RunResult { + let result = if exp.imag == 0.0 && exp.real.fract() == 0.0 && exp.real.abs() <= POWI_MAX_EXPONENT { + // The bound keeps the cast exact. + #[expect(clippy::cast_possible_truncation)] + let n = exp.real as i64; + self.powi(n) + } else { + self.pow_general(exp) + } + .ok_or_else(ExcType::zero_division_complex_power)?; + if result.real.is_infinite() || result.imag.is_infinite() { + Err(ExcType::overflow_error("complex exponentiation")) + } else { + Ok(result) + } + } + + /// `c_powi`: `c_powu` for a non-negative exponent, its reciprocal otherwise + /// (`None` when that reciprocal divides by zero). + fn powi(self, n: i64) -> Option { + if n >= 0 { + Some(self.powu(n.unsigned_abs())) + } else { + ONE.div(self.powu(n.unsigned_abs())) + } + } + + /// `c_powu`: binary exponentiation by repeated squaring. + fn powu(self, n: u64) -> Self { + let mut r = ONE; + let mut p = self; + let mut mask = 1u64; + while mask > 0 && n >= mask { + if n & mask != 0 { + r = r.mul(p); + } + mask <<= 1; + p = p.mul(p); + } + r + } + + /// `_Py_c_pow`: the polar-form power, `None` for a zero base with a + /// negative or complex exponent. + fn pow_general(self, exp: Self) -> Option { + if exp.is_zero() { + Some(ONE) + } else if self.is_zero() { + if exp.imag != 0.0 || exp.real < 0.0 { + None + } else { + Some(Self::new(0.0, 0.0)) + } + } else { + let vabs = self.real.hypot(self.imag); + let mut len = vabs.powf(exp.real); + let at = self.imag.atan2(self.real); + let mut phase = at * exp.real; + if exp.imag != 0.0 { + len *= (-at * exp.imag).exp(); + phase += exp.imag * vabs.ln(); + } + Some(Self::new(len * phase.cos(), len * phase.sin())) + } + } +} + +/// Replaces an infinity by a unit of the same sign and anything else by a +/// signed zero — the "boxing" step of the Annex G recovery formulas. +fn boxed_infinity(value: f64) -> f64 { + let unit: f64 = if value.is_infinite() { 1.0 } else { 0.0 }; + unit.copysign(value) +} + +/// Replaces `nan` by a signed zero so it drops out of a recovery product. +fn nan_to_zero(value: f64) -> f64 { + if value.is_nan() { 0.0f64.copysign(value) } else { value } +} + +/// The other operand of a complex arithmetic operation. +/// +/// CPython 3.14's mixed-mode rules treat a real operand differently from +/// `complex(x, 0)`, so the two are kept apart rather than widened up front. +#[derive(Clone, Copy)] +enum Operand { + Real(f64), + Complex(Complex), +} + +/// Classifies an operand, widening ints (an oversized big int raises +/// `OverflowError`); `None` for a non-number so the operation reports +/// `NotImplemented` and the reflected form gets its turn. +fn operand(value: &Value, vm: &VM<'_>) -> RunResult> { + Ok(match value.py_value(vm) { + PyValue::Float(value) => Some(Operand::Real(value)), + PyValue::Int(integer) => Some(Operand::Real(integer.to_f64_checked(vm)?)), + PyValue::Bool(value) => Some(Operand::Real(f64::from(value))), + PyValue::Complex(value) => Some(Operand::Complex(*value.get(vm.heap))), + _ => None, + }) +} + +/// Widens an operand to a complex for the operations with no mixed-mode form (`**`). +fn widen(operand: Operand) -> Complex { + match operand { + Operand::Real(r) => Complex::new(r, 0.0), + Operand::Complex(c) => c, + } +} + +/// Implements the `complex()` constructor. +/// +/// A lone positional argument may be a string to parse, a number, or a +/// complex (returned as is); otherwise `real` and `imag` are each a number or +/// a complex, combined as `real + imag*1j`. +pub(crate) fn init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + if let ArgValues::One(value) = args { + return init_single(value, vm); + } + let ComplexArgs { real, imag } = ComplexArgs::from_args(args, vm)?; + let real = real.unwrap_or(Part::Real(0.0)); + let mut result = Complex::new(real.real(), 0.0); + match imag { + // `complex(z)` with a complex `real` and no `imag` keeps `z.imag`. + None => { + if let Part::Complex(r) = real { + result.imag = r.imag; + } + } + // Otherwise the parts of a complex `real` and `imag` combine as `real + imag*1j`. + Some(imag) => { + result.imag = imag.real(); + if let Part::Complex(i) = imag { + result.real -= i.imag; + } + if let Part::Complex(r) = real { + result.imag += r.imag; + } + } + } + Ok(result.into_value(vm.heap)) +} + +/// `complex(x)`: the one form that also accepts a string. +fn init_single(value: Value, vm: &mut VM<'_>) -> RunResult { + if let Value::Ref(id) = &value + && matches!(vm.heap.get(*id), HeapData::Complex(_)) + { + return Ok(value); + } + defer_drop!(value, vm); + let parsed = match value.as_either_str(vm.heap) { + Some(text) => Some(parse(text.as_str(vm.interns))?), + // `Decimal.__complex__`; Decimals take no part in complex arithmetic. + None if let PyValue::Decimal(d) = value.py_value(vm) => Some(Complex::new(d.get(vm.heap).to_f64()?, 0.0)), + None => operand(value, vm)?.map(widen), + }; + match parsed { + Some(c) => Ok(c.into_value(vm.heap)), + None => Err(ExcType::type_error(format!( + "complex() argument must be a string or a number, not {}", + value.py_type_name(vm) + ))), + } +} + +/// Argument shape for `complex(real=0, imag=0)`; a string is only accepted +/// through the single-positional form handled by [`init`]. +#[derive(FromArgs)] +#[from_args(name = "complex", at_most_total, bad_arg_named)] +struct ComplexArgs { + #[from_args(default)] + real: Option, + #[from_args(default)] + imag: Option, +} + +/// One `complex(...)` constructor argument: a real number or a complex. +#[derive(Clone, Copy)] +enum Part { + Real(f64), + Complex(Complex), +} + +impl Part { + /// The real component of the part. + fn real(self) -> f64 { + match self { + Self::Real(r) => r, + Self::Complex(c) => c.real, + } + } +} + +impl FromValue for Part { + const EXPECTED_TYPE_NAME: Option<&'static str> = Some("a real number"); + + fn from_value(value: Value, vm: &mut VM<'_>) -> Result { + let result = if let PyValue::Decimal(d) = value.py_value(vm) { + // `Decimal.__float__`, as for `complex(Decimal)`. + d.get(vm.heap).to_f64().map(Self::Real).map_err(FromValueFail::Raise) + } else { + match operand(&value, vm) { + Ok(Some(Operand::Real(r))) => Ok(Self::Real(r)), + Ok(Some(Operand::Complex(c))) => Ok(Self::Complex(c)), + Ok(None) => Err(FromValueFail::WrongType), + Err(err) => Err(FromValueFail::Raise(err)), + } + }; + value.drop_with(vm); + result + } +} + +/// `complex.from_number(x)`: a number or complex, never a string. +pub(crate) fn class_from_number(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let value = args.get_one_arg("complex.from_number", vm.heap)?; + if let Value::Ref(id) = &value + && matches!(vm.heap.get(*id), HeapData::Complex(_)) + { + return Ok(value); + } + defer_drop!(value, vm); + match operand(value, vm)? { + Some(op) => Ok(widen(op).into_value(vm.heap)), + None => Err(ExcType::type_error(format!( + "must be real number, not {}", + value.py_type_name(vm) + ))), + } +} + +/// Parses the string form CPython's `complex()` accepts: ``, +/// `j`, `j`, plus the legacy `j`, +/// `j` and `j`, optionally parenthesised and whitespace-padded. +/// +/// Underscores are validated as digit separators over the whole text first, +/// which is why a misplaced one gets a different message from other errors. +fn parse(text: &str) -> RunResult { + let malformed = || ExcType::value_error("complex() arg is a malformed string"); + let stripped; + let text = if text.contains('_') { + stripped = strip_underscores(text).ok_or_else(|| { + ExcType::value_error(format!("could not convert string to complex: {}", StringRepr(text))) + })?; + stripped.as_str() + } else { + text + }; + let mut s = text.trim_start(); + let bracketed = s.starts_with('('); + if bracketed { + s = s[1..].trim_start(); + } + let (mut real, mut imag) = (0.0, 0.0); + if let Some((z, len)) = float_prefix(s) { + s = &s[len..]; + if s.starts_with(['+', '-']) { + real = z; + if let Some((y, len)) = float_prefix(s) { + imag = y; + s = &s[len..]; + } else { + imag = if s.starts_with('+') { 1.0 } else { -1.0 }; + s = &s[1..]; + } + s = s.strip_prefix(['j', 'J']).ok_or_else(malformed)?; + } else if let Some(rest) = s.strip_prefix(['j', 'J']) { + imag = z; + s = rest; + } else { + real = z; + } + } else { + // Not starting with a float: `j` or `j`. + imag = 1.0; + if let Some(rest) = s.strip_prefix(['+', '-']) { + imag = if s.starts_with('+') { 1.0 } else { -1.0 }; + s = rest; + } + s = s.strip_prefix(['j', 'J']).ok_or_else(malformed)?; + } + s = s.trim_start(); + if bracketed { + s = s.strip_prefix(')').ok_or_else(malformed)?.trim_start(); + } + if s.is_empty() { + Ok(Complex::new(real, imag)) + } else { + Err(malformed()) + } +} + +/// The longest float literal at the start of `s`, as CPython's +/// `PyOS_string_to_double` consumes it: an optional sign, then `inf`, +/// `infinity`, `nan` (any case) or decimal digits with an optional fraction +/// and exponent. Returns the value and the byte length consumed. +fn float_prefix(s: &str) -> Option<(f64, usize)> { + let bytes = s.as_bytes(); + let mut i = usize::from(bytes.first().is_some_and(|b| matches!(b, b'+' | b'-'))); + let rest = &s[i..]; + let word_len = ["infinity", "inf", "nan"].iter().find_map(|word| { + rest.get(..word.len()) + .filter(|p| p.eq_ignore_ascii_case(word)) + .map(|_| word.len()) + }); + if let Some(len) = word_len { + i += len; + } else { + let digits = |i: usize| bytes[i..].iter().take_while(|b| b.is_ascii_digit()).count(); + let int_digits = digits(i); + i += int_digits; + let mut frac_digits = 0; + if bytes.get(i) == Some(&b'.') { + frac_digits = digits(i + 1); + i += 1 + frac_digits; + } + if int_digits + frac_digits == 0 { + return None; + } + if matches!(bytes.get(i), Some(b'e' | b'E')) { + let mut j = i + 1; + if matches!(bytes.get(j), Some(b'+' | b'-')) { + j += 1; + } + let exp_digits = digits(j); + // An exponent marker with no digits is not part of the number. + if exp_digits > 0 { + i = j + exp_digits; + } + } + } + s[..i].parse().ok().map(|value| (value, i)) +} + +impl HeapItem for Complex { + fn py_dec_ref_ids(&mut self, _stack: &mut Vec) {} +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, Complex> { + fn py_type(&self, _vm: &VM<'h>) -> Type { + Type::Complex + } + + fn py_len(&self, _vm: &VM<'h>) -> Option { + None + } + + /// Equal to another complex part-wise, and to a real number when the + /// imaginary part is zero and the real part matches it exactly. + fn py_eq_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let c = *self.get(vm.heap); + Ok(match other { + Value::Ref(id) if let HeapData::Complex(o) = vm.heap.get(*id) => Some(c.eq(*o)), + _ => eq_f64(c.real, other, vm).map(|real_eq| real_eq && c.imag == 0.0), + }) + } + + /// Combines the part hashes as CPython does, so a complex with a zero + /// imaginary part hashes like its real part (and so like an equal int). + fn py_hash(&self, vm: &mut VM<'h>) -> RunResult> { + let c = *self.get(vm.heap); + let combined = hash_f64(c.real) + .raw() + .wrapping_add(hash_f64(c.imag).raw().wrapping_mul(1_000_003)); + Ok(Some(HashValue::new(combined))) + } + + fn py_bool(&self, vm: &mut VM<'h>) -> RunResult { + Ok(!self.get(vm.heap).is_zero()) + } + + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, _heap_ids: &mut LazyHeapSet) -> RunResult<()> { + let c = self.get(vm.heap); + Ok(write!( + f, + "{}", + FormatComplex { + real: c.real, + imag: c.imag + } + )?) + } + + fn py_str(&self, vm: &mut VM<'h>) -> RunResult { + let c = self.get(vm.heap); + let text = FormatComplex { + real: c.real, + imag: c.imag, + } + .to_string(); + Ok(allocate_string(text, vm.heap)) + } + + fn py_abs_impl(&self, vm: &mut VM<'h>) -> RunResult> { + Ok(Some(Value::Float(self.get(vm.heap).abs()?))) + } + + fn py_neg_impl(&self, vm: &mut VM<'h>) -> RunResult> { + Ok(Some(self.get(vm.heap).neg().into_value(vm.heap))) + } + + fn py_pos_impl(&self, vm: &mut VM<'h>) -> RunResult> { + Ok(Some(self.clone_value(vm.heap))) + } + + fn py_add_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let c = *self.get(vm.heap); + let result = match operand(other, vm)? { + Some(Operand::Real(r)) => Complex::new(c.real + r, c.imag), + Some(Operand::Complex(o)) => Complex::new(c.real + o.real, c.imag + o.imag), + None => return Ok(None), + }; + Ok(Some(result.into_value(vm.heap))) + } + + fn py_radd_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + // Addition is symmetric part-wise, so the reflected form is the direct one. + self.py_add_impl(other, vm) + } + + fn py_sub_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let c = *self.get(vm.heap); + let result = match operand(other, vm)? { + Some(Operand::Real(r)) => Complex::new(c.real - r, c.imag), + Some(Operand::Complex(o)) => Complex::new(c.real - o.real, c.imag - o.imag), + None => return Ok(None), + }; + Ok(Some(result.into_value(vm.heap))) + } + + fn py_rsub_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let c = *self.get(vm.heap); + let result = match operand(other, vm)? { + Some(Operand::Real(r)) => Complex::new(r - c.real, -c.imag), + Some(Operand::Complex(o)) => Complex::new(o.real - c.real, o.imag - c.imag), + None => return Ok(None), + }; + Ok(Some(result.into_value(vm.heap))) + } + + fn py_mul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let c = *self.get(vm.heap); + let result = match operand(other, vm)? { + Some(Operand::Real(r)) => Complex::new(c.real * r, c.imag * r), + Some(Operand::Complex(o)) => c.mul(o), + None => return Ok(None), + }; + Ok(Some(result.into_value(vm.heap))) + } + + fn py_rmul_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + // Scaling by a real is symmetric part-wise, so the reflected form is the direct one. + self.py_mul_impl(other, vm) + } + + fn py_truediv_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let c = *self.get(vm.heap); + let result = match operand(other, vm)? { + Some(Operand::Real(r)) => { + if r == 0.0 { + None + } else { + Some(Complex::new(c.real / r, c.imag / r)) + } + } + Some(Operand::Complex(o)) => c.div(o), + None => return Ok(None), + }; + result + .map(|r| r.into_value(vm.heap)) + .ok_or_else(|| ExcType::zero_division().into()) + .map(Some) + } + + fn py_rtruediv_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let c = *self.get(vm.heap); + let quotient = match operand(other, vm)? { + Some(Operand::Real(r)) => Complex::div_into(r, c), + Some(Operand::Complex(o)) => o.div(c), + None => return Ok(None), + }; + quotient + .map(|r| r.into_value(vm.heap)) + .ok_or_else(|| ExcType::zero_division().into()) + .map(Some) + } + + fn py_pow_impl(&self, other: &Value, modulus: Option<&Value>, vm: &mut VM<'h>) -> RunResult> { + let c = *self.get(vm.heap); + let Some(exp) = operand(other, vm)? else { + return Ok(None); + }; + if modulus.is_some() { + return Err(ExcType::value_error_complex_modulo()); + } + Ok(Some(c.pow(widen(exp))?.into_value(vm.heap))) + } + + fn py_rpow_impl(&self, other: &Value, modulus: Option<&Value>, vm: &mut VM<'h>) -> RunResult> { + let c = *self.get(vm.heap); + let Some(base) = operand(other, vm)? else { + return Ok(None); + }; + if modulus.is_some() { + return Err(ExcType::value_error_complex_modulo()); + } + Ok(Some(widen(base).pow(c)?.into_value(vm.heap))) + } + + fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { + if attr.static_string(vm.interns) == Some(StaticStrings::Conjugate) { + let c = *self.get(vm.heap); + args.check_zero_args("complex.conjugate", vm.heap)?; + return Ok(CallResult::Value(c.conjugate().into_value(vm.heap))); + } + Err(ExcType::attribute_error_method(Type::Complex, attr, args, vm)) + } + + fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { + let c = *self.get(vm.heap); + Ok(match attr.static_string(vm.interns) { + Some(StaticStrings::Real) => Some(CallResult::Value(Value::Float(c.real))), + Some(StaticStrings::Imag) => Some(CallResult::Value(Value::Float(c.imag))), + _ => None, + }) + } + + /// `real` and `imag` exist but are read-only, which CPython words differently + /// from a missing attribute. + fn py_set_attr(&mut self, name: &EitherStr, value: Value, vm: &mut VM<'h>) -> RunResult<()> { + value.drop_with(vm); + Err(match name.static_string(vm.interns) { + Some(StaticStrings::Real | StaticStrings::Imag) => ExcType::attribute_error_readonly(), + _ => ExcType::attribute_error_no_setattr(&self.py_type_name(vm), name.as_str(vm.interns)), + }) + } +} diff --git a/crates/bashkit-monty/src/types/csv/dialect.rs b/crates/bashkit-monty/src/types/csv/dialect.rs new file mode 100644 index 000000000..aaba0b4e0 --- /dev/null +++ b/crates/bashkit-monty/src/types/csv/dialect.rs @@ -0,0 +1,415 @@ +//! `_csv.Dialect`: the resolved formatting parameters a reader or writer runs with. +//! +//! Resolution follows CPython's `dialect_new`: an explicit format parameter wins, then the +//! attribute of the `dialect` argument (a registered name, a `_csv.Dialect` or any object with +//! the attributes), then the `excel` default; conversion and validation errors keep CPython's +//! wording and order. + +use serde::{Deserialize, Serialize}; + +use crate::{ + bytecode::{CallResult, VM}, + exception_private::{ExcType, ExcTypeExt, RunResult}, + heap::{ContainsHeap, DropGuard, DropWithContext, HeapData}, + intern::StaticStrings, + types::{CsvObject, PyTrait, Type, str::allocate_string}, + value::{EitherStr, Value}, +}; + +/// The `csv.QUOTE_*` constants; the discriminants are CPython's values, which the module +/// exports and `dialect.quoting` reports. Serialized by name, so the numbering is not persisted. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[repr(i64)] +pub(crate) enum Quoting { + Minimal = 0, + All = 1, + Nonnumeric = 2, + None = 3, + Strings = 4, + Notnull = 5, +} + +impl Quoting { + /// Every constant, indexed by its value. + const ALL: [Self; 6] = [ + Self::Minimal, + Self::All, + Self::Nonnumeric, + Self::None, + Self::Strings, + Self::Notnull, + ]; + + /// The constant's value. + pub(crate) const fn as_int(self) -> i64 { + self as i64 + } + + /// The constant for a `quoting=` value; `None` for anything CPython rejects. + fn from_int(value: i32) -> Option { + usize::try_from(value) + .ok() + .and_then(|index| Self::ALL.get(index).copied()) + } +} + +/// A resolved dialect. Readers and writers hold their own copy, so `reader.dialect` is a fresh +/// `_csv.Dialect` object on each access rather than the one passed in. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct Dialect { + pub(crate) delimiter: char, + pub(crate) quotechar: Option, + pub(crate) escapechar: Option, + pub(crate) doublequote: bool, + pub(crate) skipinitialspace: bool, + pub(crate) lineterminator: String, + pub(crate) quoting: Quoting, + pub(crate) strict: bool, +} + +/// The format parameters a call supplied explicitly; `None` means "not given", which is +/// distinct from an explicit Python `None` (`quotechar=None` turns quoting off). +#[derive(Debug, Default)] +pub(crate) struct FmtParams { + pub(crate) delimiter: Option, + pub(crate) doublequote: Option, + pub(crate) escapechar: Option, + pub(crate) lineterminator: Option, + pub(crate) quotechar: Option, + pub(crate) quoting: Option, + pub(crate) skipinitialspace: Option, + pub(crate) strict: Option, +} + +impl DropWithContext for FmtParams { + fn drop_with(self, ctx: &mut C) { + self.delimiter.drop_with(ctx); + self.doublequote.drop_with(ctx); + self.escapechar.drop_with(ctx); + self.lineterminator.drop_with(ctx); + self.quotechar.drop_with(ctx); + self.quoting.drop_with(ctx); + self.skipinitialspace.drop_with(ctx); + self.strict.drop_with(ctx); + } +} + +/// The registered dialect names, in `csv.list_dialects()` order. +pub(crate) const DIALECT_NAMES: [&str; 3] = ["excel", "excel-tab", "unix"]; + +impl Dialect { + /// `csv.excel`: the default dialect. + pub(crate) fn excel() -> Self { + Self { + delimiter: ',', + quotechar: Some('"'), + escapechar: None, + doublequote: true, + skipinitialspace: false, + lineterminator: "\r\n".to_owned(), + quoting: Quoting::Minimal, + strict: false, + } + } + + /// `csv.excel_tab`: `excel` with a tab delimiter. + pub(crate) fn excel_tab() -> Self { + Self { + delimiter: '\t', + ..Self::excel() + } + } + + /// `csv.unix_dialect`: `\n` line endings and every field quoted. + pub(crate) fn unix() -> Self { + Self { + lineterminator: "\n".to_owned(), + quoting: Quoting::All, + ..Self::excel() + } + } + + /// The registered dialect called `name`, if any. + pub(crate) fn by_name(name: &str) -> Option { + match name { + "excel" => Some(Self::excel()), + "excel-tab" => Some(Self::excel_tab()), + "unix" => Some(Self::unix()), + _ => None, + } + } + + /// Resolves the dialect a reader, writer or `_csv.Dialect(...)` call runs with. + /// + /// `base` is the `dialect` argument: a registered name, a `_csv.Dialect`, or any other object + /// whose attributes supply the parameters `params` leaves unset. Consumes `params` on every path. + pub(crate) fn resolve(base: Option<&Value>, params: FmtParams, vm: &mut VM<'_>) -> RunResult { + let mut params_guard = DropGuard::new(params, vm); + let (params, vm) = params_guard.as_parts_mut(); + let base = match base { + None => Base::Defaults, + Some(value) if value.is_str(vm.heap) => { + Base::Dialect(Self::by_name(value.to_str(vm)?).ok_or_else(ExcType::csv_unknown_dialect)?) + } + Some(Value::Ref(id)) + if let HeapData::Csv(csv) = vm.heap.get(*id) + && let CsvObject::Dialect(dialect) = &**csv => + { + Base::Dialect(dialect.clone()) + } + Some(value) => Base::Object(value), + }; + + // CPython fetches every parameter the call left unset from `base` first, in this + // order, and converts them only afterwards. They stay in the guarded `params` until + // converted, so an earlier parameter's error still releases them. + params.delimiter = base.take(params.delimiter.take(), StaticStrings::Delimiter, vm)?; + params.doublequote = base.take(params.doublequote.take(), StaticStrings::Doublequote, vm)?; + params.escapechar = base.take(params.escapechar.take(), StaticStrings::Escapechar, vm)?; + params.lineterminator = base.take(params.lineterminator.take(), StaticStrings::Lineterminator, vm)?; + params.quotechar = base.take(params.quotechar.take(), StaticStrings::Quotechar, vm)?; + params.quoting = base.take(params.quoting.take(), StaticStrings::Quoting, vm)?; + params.skipinitialspace = base.take(params.skipinitialspace.take(), StaticStrings::Skipinitialspace, vm)?; + params.strict = base.take(params.strict.take(), StaticStrings::Strict, vm)?; + + // Explicit `quotechar=None` with no `quoting` selects QUOTE_NONE, decided on the + // raw values before conversion as CPython does. + let quoting_unset = params.quoting.is_none(); + let quotechar_is_none = matches!(params.quotechar, Some(Value::None)); + + let delimiter = set_char("delimiter", params.delimiter.take(), ',', vm)?; + let doublequote = set_bool(params.doublequote.take(), true, vm)?; + let escapechar = set_char_or_none("escapechar", params.escapechar.take(), None, vm)?; + let lineterminator = set_str("lineterminator", params.lineterminator.take(), "\r\n", vm)?; + let quotechar = set_char_or_none("quotechar", params.quotechar.take(), Some('"'), vm)?; + let mut quoting = set_quoting(params.quoting.take(), vm)?; + let skipinitialspace = set_bool(params.skipinitialspace.take(), false, vm)?; + let strict = set_bool(params.strict.take(), false, vm)?; + + if quotechar_is_none && quoting_unset { + quoting = Quoting::None; + } + if quoting != Quoting::None && quotechar.is_none() { + return Err(ExcType::type_error("quotechar must be set if quoting enabled")); + } + let dialect = Self { + delimiter, + quotechar, + escapechar, + doublequote, + skipinitialspace, + lineterminator, + quoting, + strict, + }; + dialect.check_char("delimiter", Some(delimiter), true)?; + dialect.check_char("escapechar", escapechar, !skipinitialspace)?; + dialect.check_char("quotechar", quotechar, !skipinitialspace)?; + check_chars("delimiter", "escapechar", Some(delimiter), escapechar)?; + check_chars("delimiter", "quotechar", Some(delimiter), quotechar)?; + check_chars("escapechar", "quotechar", escapechar, quotechar)?; + Ok(dialect) + } + + /// `dialect_check_char`: a control character, or a character that also ends lines, + /// cannot serve as a delimiter, quote or escape. + fn check_char(&self, name: &str, c: Option, allow_space: bool) -> RunResult<()> { + let Some(c) = c else { + return Ok(()); + }; + if c == '\r' || c == '\n' || (c == ' ' && !allow_space) { + Err(ExcType::value_error(format!("bad {name} value"))) + } else if self.lineterminator.contains(c) { + Err(ExcType::value_error(format!("bad {name} or lineterminator value"))) + } else { + Ok(()) + } + } + + /// Whether `attr` names one of the eight `_csv.Dialect` attributes. + pub(crate) fn is_attr(attr: StaticStrings) -> bool { + matches!( + attr, + StaticStrings::Delimiter + | StaticStrings::Quotechar + | StaticStrings::Escapechar + | StaticStrings::Doublequote + | StaticStrings::Skipinitialspace + | StaticStrings::Lineterminator + | StaticStrings::Quoting + | StaticStrings::Strict + ) + } + + /// The value of a `_csv.Dialect` attribute, or `None` for a name that is not one. + pub(crate) fn attr(&self, attr: StaticStrings, vm: &VM<'_>) -> Option { + Some(match attr { + StaticStrings::Delimiter => char_value(self.delimiter, vm), + StaticStrings::Quotechar => self.quotechar.map_or(Value::None, |c| char_value(c, vm)), + StaticStrings::Escapechar => self.escapechar.map_or(Value::None, |c| char_value(c, vm)), + StaticStrings::Doublequote => Value::Bool(self.doublequote), + StaticStrings::Skipinitialspace => Value::Bool(self.skipinitialspace), + StaticStrings::Lineterminator => allocate_string(self.lineterminator.clone(), vm.heap), + StaticStrings::Quoting => Value::Int(self.quoting.as_int()), + StaticStrings::Strict => Value::Bool(self.strict), + _ => return None, + }) + } +} + +/// A single-character `str` value. +fn char_value(c: char, vm: &VM<'_>) -> Value { + allocate_string(c.to_string(), vm.heap) +} + +/// Where unset parameters come from: the defaults, a resolved dialect, or an +/// arbitrary object's attributes (a user class with `delimiter = ';'`). +enum Base<'a> { + Defaults, + Dialect(Dialect), + Object(&'a Value), +} + +impl Base<'_> { + /// The parameter to convert: `explicit` when given, else this base's value, else `None` + /// for the default. The result is owned; the caller releases it. + fn take(&self, explicit: Option, attr: StaticStrings, vm: &mut VM<'_>) -> RunResult> { + if explicit.is_some() { + return Ok(explicit); + } + match self { + Self::Defaults => Ok(None), + Self::Dialect(dialect) => Ok(dialect.attr(attr, vm)), + Self::Object(object) => { + let name = EitherStr::Interned(vm.interns.intern_static(attr)); + match object.py_getattr(&name, vm) { + Ok(CallResult::Value(value)) => Ok(Some(value)), + // A missing attribute means "use the default", as CPython's `PyErr_Clear` does. + Err(err) if err.is_catchable(ExcType::AttributeError) => Ok(None), + Err(err) => Err(err), + Ok(other) => { + other.drop_with(vm); + Err(ExcType::not_implemented(format!( + "csv: dialect attribute '{}' cannot be computed by a property", + attr_name(attr) + )) + .into()) + } + } + } + } + } +} + +/// The Python spelling of a parameter name, for error messages. +fn attr_name(attr: StaticStrings) -> &'static str { + attr.into() +} + +/// `_set_char`: a one-character `str`. +fn set_char(name: &str, value: Option, default: char, vm: &mut VM<'_>) -> RunResult { + let Some(value) = value else { + return Ok(default); + }; + let result = single_char(name, &value, "a unicode character", vm); + value.drop_with(vm); + result +} + +/// `_set_char_or_none`: a one-character `str`, or `None` to unset. +fn set_char_or_none( + name: &str, + value: Option, + default: Option, + vm: &mut VM<'_>, +) -> RunResult> { + let Some(value) = value else { + return Ok(default); + }; + let result = if matches!(value, Value::None) { + Ok(None) + } else { + single_char(name, &value, "a unicode character or None", vm).map(Some) + }; + value.drop_with(vm); + result +} + +/// The character of a one-character `str`, with CPython's two wordings for a wrong +/// type and a wrong length. +fn single_char(name: &str, value: &Value, expected: &str, vm: &VM<'_>) -> RunResult { + if value.is_str(vm.heap) { + let text = value.to_str(vm)?; + let mut chars = text.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) => Ok(c), + _ => Err(ExcType::type_error(format!( + "\"{name}\" must be {expected}, not a string of length {}", + text.chars().count() + ))), + } + } else { + Err(ExcType::type_error(format!( + "\"{name}\" must be {expected}, not {}", + value.py_type_name(vm) + ))) + } +} + +/// `_set_bool`: any value, through `bool()`. +fn set_bool(value: Option, default: bool, vm: &mut VM<'_>) -> RunResult { + let Some(value) = value else { + return Ok(default); + }; + let result = value.py_bool(vm); + value.drop_with(vm); + result +} + +/// `_set_str`: any `str`. +fn set_str(name: &str, value: Option, default: &str, vm: &mut VM<'_>) -> RunResult { + let Some(value) = value else { + return Ok(default.to_owned()); + }; + let result = if value.is_str(vm.heap) { + value.to_str(vm).map(str::to_owned) + } else { + Err(ExcType::type_error(format!( + "\"{name}\" must be a string, not {}", + value.py_type_name(vm) + ))) + }; + value.drop_with(vm); + result +} + +/// `_set_int` plus `dialect_check_quoting`: an exact `int` naming a `QUOTE_*` constant. +/// The conversion goes through a C `int`, so a value beyond it is an `OverflowError`. +fn set_quoting(value: Option, vm: &mut VM<'_>) -> RunResult { + let Some(value) = value else { + return Ok(Quoting::Minimal); + }; + let result = match value { + Value::Int(n) => match i32::try_from(n) { + Ok(n) => Quoting::from_int(n).ok_or_else(|| ExcType::type_error("bad \"quoting\" value")), + Err(_) => Err(ExcType::overflow_c_int()), + }, + Value::Bool(_) => Err(ExcType::type_error("\"quoting\" must be an integer, not bool")), + _ if value.py_type(vm) == Type::Int => Err(ExcType::overflow_c_int()), + _ => Err(ExcType::type_error(format!( + "\"quoting\" must be an integer, not {}", + value.py_type_name(vm) + ))), + }; + value.drop_with(vm); + result +} + +/// `dialect_check_chars`: two set characters must differ. +fn check_chars(name1: &str, name2: &str, c1: Option, c2: Option) -> RunResult<()> { + if c1.is_some() && c1 == c2 { + Err(ExcType::value_error(format!("bad {name1} or {name2} value"))) + } else { + Ok(()) + } +} diff --git a/crates/bashkit-monty/src/types/csv/dict.rs b/crates/bashkit-monty/src/types/csv/dict.rs new file mode 100644 index 000000000..56ff18c52 --- /dev/null +++ b/crates/bashkit-monty/src/types/csv/dict.rs @@ -0,0 +1,667 @@ +//! `csv.DictReader` and `csv.DictWriter`: the pure-Python wrappers of CPython's `csv.py`, +//! mapping rows to and from dicts keyed by `fieldnames`. + +use std::{mem, sync::Arc}; + +use serde::{Deserialize, Serialize}; + +use crate::{ + args::ArgValues, + bytecode::{CallResult, VM}, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{ + ContainsHeap, DropGuard, DropWithContext, HeapData, HeapId, HeapObjectRead, HeapRead, HeapReadMut, + HeapReadOutput, + }, + string_builder::StringBuilder, + types::{ + CsvObject, Dict, List, PyTrait, Set, + csv::{ + Dialect, + writer::{terminator_chars, writerow_now}, + }, + iter::collect_iterable, + }, + value::{VALUE_SIZE, Value}, +}; + +/// A `csv.DictReader`: a `_csv.reader` plus the header handling around it. +#[derive(Debug, Serialize, Deserialize)] +pub(crate) struct DictReader { + /// The underlying `_csv.reader`. Owned. + pub(crate) reader: Value, + /// `None` until the header row is read (or `fieldnames` is assigned). Owned. + pub(crate) fieldnames: Option, + /// Key for the surplus fields of a long row. Owned. + pub(crate) restkey: Value, + /// Value for the missing fields of a short row. Owned. + pub(crate) restval: Value, + /// The `dialect` argument as passed, which is what `.dialect` reports. Owned. + pub(crate) dialect: Value, + pub(crate) line_num: u64, + /// Keys in the last row's dict: the capacity the next one starts at. Below the header + /// width when a name repeats, since the repeat overwrites its slot; zero before any row. + #[serde(skip)] + dict_hint: usize, +} + +impl DictReader { + pub(crate) fn new( + reader: Value, + fieldnames: Option, + restkey: Value, + restval: Value, + dialect: Value, + ) -> Self { + Self { + reader, + fieldnames, + restkey, + restval, + dialect, + line_num: 0, + dict_hint: 0, + } + } + + /// Invokes `on_child` for each heap id this reader owns (GC trace hook). + pub(crate) fn for_each_child_id(&self, mut on_child: impl FnMut(HeapId)) { + for value in [ + Some(&self.reader), + self.fieldnames.as_ref(), + Some(&self.restkey), + Some(&self.restval), + Some(&self.dialect), + ] + .into_iter() + .flatten() + { + if let Value::Ref(id) = value { + on_child(*id); + } + } + } + + /// Releases every owned reference (mirrors `for_each_child_id`). + pub(crate) fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + self.reader.py_dec_ref_ids(stack); + if let Some(fieldnames) = &mut self.fieldnames { + fieldnames.py_dec_ref_ids(stack); + } + self.restkey.py_dec_ref_ids(stack); + self.restval.py_dec_ref_ids(stack); + self.dialect.py_dec_ref_ids(stack); + } +} + +/// A `csv.DictWriter`: a `_csv.writer` plus the field order a row dict is flattened in. +#[derive(Debug, Serialize, Deserialize)] +pub(crate) struct DictWriter { + /// The underlying `_csv.writer`. Owned. + pub(crate) writer: Value, + /// Any iterable of keys, as passed. Owned. + pub(crate) fieldnames: Value, + /// Value written for a key the row dict lacks. Owned. + pub(crate) restval: Value, + /// The `extrasaction` argument, lower-cased at construction; a key outside `fieldnames` + /// raises when it is `'raise'` at the time of the write. Owned. + pub(crate) extrasaction: Value, +} + +impl DictWriter { + pub(crate) fn new(writer: Value, fieldnames: Value, restval: Value, extrasaction: Value) -> Self { + Self { + writer, + fieldnames, + restval, + extrasaction, + } + } + + /// Invokes `on_child` for each heap id this writer owns (GC trace hook). + pub(crate) fn for_each_child_id(&self, mut on_child: impl FnMut(HeapId)) { + for value in [&self.writer, &self.fieldnames, &self.restval, &self.extrasaction] { + if let Value::Ref(id) = value { + on_child(*id); + } + } + } + + /// Releases every owned reference (mirrors `for_each_child_id`). + pub(crate) fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + self.writer.py_dec_ref_ids(stack); + self.fieldnames.py_dec_ref_ids(stack); + self.restval.py_dec_ref_ids(stack); + self.extrasaction.py_dec_ref_ids(stack); + } +} + +/// `DictReader.fieldnames`: reads the header row on first access, then reports the names +/// (`None` for an empty source). The caller owns the returned reference. +pub(super) fn reader_fieldnames<'h>(obj: &HeapReadMut<'h, CsvObject>, vm: &mut VM<'h>) -> RunResult { + let (reader, unset) = { + let CsvObject::DictReader(dict_reader) = obj.get(vm.heap) else { + unreachable!("dispatched on CsvObject::DictReader") + }; + ( + dict_reader.reader.clone_with_heap(vm.heap), + dict_reader.fieldnames.is_none(), + ) + }; + defer_drop!(reader, vm); + if unset && let Some(header) = next_row(reader, vm)? { + let header = Value::Ref(vm.heap.allocate(HeapData::List(List::new(header)))); + if let CsvObject::DictReader(dict_reader) = obj.get_mut(vm.heap) { + dict_reader.fieldnames = Some(header); + } + } + let line_num = reader_line_num(reader, vm); + if let CsvObject::DictReader(dict_reader) = obj.get_mut(vm.heap) { + dict_reader.line_num = line_num; + } + let CsvObject::DictReader(dict_reader) = obj.get(vm.heap) else { + unreachable!("dispatched on CsvObject::DictReader") + }; + Ok(dict_reader + .fieldnames + .as_ref() + .map_or(Value::None, |names| names.clone_with_heap(vm.heap))) +} + +/// `DictReader.__next__`: the next non-empty row as a dict, with `restkey` / `restval` +/// covering a length mismatch against `fieldnames`. +pub(super) fn reader_next<'h>(obj: &HeapReadMut<'h, CsvObject>, vm: &mut VM<'h>) -> RunResult> { + let first = matches!(obj.get(vm.heap), CsvObject::DictReader(dict_reader) if dict_reader.line_num == 0); + if first { + // Used only for its side effect of reading the header, as in CPython. + reader_fieldnames(obj, vm)?.drop_with(vm); + } + let (reader, fieldnames, restkey, restval, dict_hint) = { + let CsvObject::DictReader(dict_reader) = obj.get(vm.heap) else { + unreachable!("dispatched on CsvObject::DictReader") + }; + ( + dict_reader.reader.clone_with_heap(vm.heap), + dict_reader + .fieldnames + .as_ref() + .map_or(Value::None, |names| names.clone_with_heap(vm.heap)), + dict_reader.restkey.clone_with_heap(vm.heap), + dict_reader.restval.clone_with_heap(vm.heap), + dict_reader.dict_hint, + ) + }; + defer_drop!(reader, vm); + defer_drop!(fieldnames, vm); + defer_drop!(restkey, vm); + defer_drop!(restval, vm); + + let Some(items) = next_row(reader, vm)? else { + return Ok(None); + }; + let mut items_guard = DropGuard::new(items, vm); + let (items, vm) = items_guard.as_parts_mut(); + let line_num = reader_line_num(reader, vm); + if let CsvObject::DictReader(dict_reader) = obj.get_mut(vm.heap) { + dict_reader.line_num = line_num; + } + // Blank lines yield empty rows, which CPython skips here. A native loop over the + // source, so it polls the clock: an endless run of blank lines must still time out. + let mut skipped = 0usize; + while items.is_empty() { + vm.heap.tracker.check_time_every(skipped)?; + skipped += 1; + let Some(next) = next_row(reader, vm)? else { + return Ok(None); + }; + mem::replace(items, next).drop_with(vm); + } + // CPython reads `self.fieldnames` to build the dict, and the property refreshes `line_num`. + let line_num = reader_line_num(reader, vm); + if let CsvObject::DictReader(dict_reader) = obj.get_mut(vm.heap) { + dict_reader.line_num = line_num; + } + + let names = fieldnames_items(fieldnames, vm)?; + let mut names_guard = DropGuard::new(names, vm); + let (names, vm) = names_guard.as_parts_mut(); + + let (name_count, item_count) = (names.len(), items.len()); + // The last row's key count predicts this one's; the first row assumes distinct names. + let capacity = if dict_hint == 0 { name_count } else { dict_hint }; + // The table is sized up front from a width the caller controls, so charge it as a + // dict copy does before it exists. + vm.heap + .tracker + .check_allocation(capacity.saturating_mul(2 * VALUE_SIZE))?; + let mut dict_guard = DropGuard::new(Dict::with_capacity(capacity), vm); + let (dict, vm) = dict_guard.as_parts_mut(); + // `dict(zip(fieldnames, row))`: the surplus of the longer side stays behind. + let paired = name_count.min(item_count); + for (name, item) in names.drain(..paired).zip(items.drain(..paired)) { + if let Some(old) = dict.set(name, item, vm)? { + old.drop_with(vm); + } + } + if name_count < item_count { + let extra = List::new(mem::take(items)); + let extra = Value::Ref(vm.heap.allocate(HeapData::List(extra))); + if let Some(old) = dict.set(restkey.clone_with_heap(vm.heap), extra, vm)? { + old.drop_with(vm); + } + } else { + for name in names.drain(..) { + if let Some(old) = dict.set(name, restval.clone_with_heap(vm.heap), vm)? { + old.drop_with(vm); + } + } + } + let (dict, vm) = dict_guard.into_parts(); + let key_count = dict.len(); + if let CsvObject::DictReader(dict_reader) = obj.get_mut(vm.heap) { + dict_reader.dict_hint = key_count; + } + Ok(Some(Value::Ref(vm.heap.allocate(HeapData::Dict(dict))))) +} + +/// `DictWriter.writerow(rowdict)`: flattens the dict in `fieldnames` order and writes it. +pub(super) fn writer_writerow<'h>( + obj: &HeapRead<'h, CsvObject>, + args: ArgValues, + vm: &mut VM<'h>, +) -> RunResult { + let rowdict = args.get_one_arg("DictWriter.writerow", vm.heap)?; + defer_drop!(rowdict, vm); + let spec: Option = None; + defer_drop_mut!(spec, vm); + let items = dict_to_list(obj, spec, rowdict, vm)?; + defer_drop!(items, vm); + write_items(obj, items, vm) +} + +/// `DictWriter.writeheader()`: `self.writerow(dict(zip(self.fieldnames, self.fieldnames)))`, +/// returning what `write()` did. The dict is what rejects an unhashable name, and a repeated +/// name collapses in it, so the row goes through it as in CPython. +pub(super) fn writer_writeheader<'h>( + obj: &HeapRead<'h, CsvObject>, + args: ArgValues, + vm: &mut VM<'h>, +) -> RunResult { + args.check_zero_args("DictWriter.writeheader", vm.heap)?; + let fieldnames = dict_writer_part(obj, vm, |writer| writer.fieldnames.clone_with_heap(vm.heap)); + defer_drop!(fieldnames, vm); + let names = fieldnames_items(fieldnames, vm)?; + defer_drop!(names, vm); + let mut header_guard = DropGuard::new(Dict::with_capacity(names.len()), vm); + let (header, vm) = header_guard.as_parts_mut(); + for name in names { + if let Some(old) = header.set(name.clone_with_heap(vm.heap), name.clone_with_heap(vm.heap), vm)? { + old.drop_with(vm); + } + } + let (header, vm) = header_guard.into_parts(); + let header = Value::Ref(vm.heap.allocate(HeapData::Dict(header))); + defer_drop!(header, vm); + let spec: Option = None; + defer_drop_mut!(spec, vm); + let items = dict_to_list(obj, spec, header, vm)?; + defer_drop!(items, vm); + write_items(obj, items, vm) +} + +/// `DictWriter.writerows(rowdicts)`: flattens and writes each dict. +/// +/// A file target gets every row in one host write, so the dicts are all flattened first; +/// any other target is written synchronously as each dict arrives. +pub(super) fn writer_writerows<'h>( + obj: &HeapRead<'h, CsvObject>, + args: ArgValues, + vm: &mut VM<'h>, +) -> RunResult { + let rowdicts = args.get_one_arg("DictWriter.writerows", vm.heap)?; + defer_drop!(rowdicts, vm); + let writer = dict_writer_part(obj, vm, |writer| writer.writer.clone_with_heap(vm.heap)); + defer_drop!(writer, vm); + let Some((targets_file, write, dialect)) = writer_parts(writer, vm) else { + return Err(RunError::internal("DictWriter: writer is not a _csv.writer")); + }; + defer_drop!(write, vm); + // Filled by the first row and refreshed whenever an attribute changes between rows. + let spec: Option = None; + defer_drop_mut!(spec, vm); + if targets_file { + let rows = collect_iterable(rowdicts, vm)?; + defer_drop!(rows, vm); + let mut lists_guard = DropGuard::new(Vec::with_capacity(rows.len()), vm); + let (flattened, vm) = lists_guard.as_parts_mut(); + for rowdict in rows { + let items = dict_to_list(obj, spec, rowdict, vm)?; + flattened.push(Value::Ref(vm.heap.allocate(HeapData::List(List::new(items))))); + } + let (lists, vm) = lists_guard.into_parts(); + let rows = Value::Ref(vm.heap.allocate(HeapData::List(List::new(lists)))); + defer_drop!(rows, vm); + with_writer(writer, vm, |writer_obj, vm| { + let rows = rows.clone_with_heap(vm.heap); + super::writer::writerows(writer_obj, ArgValues::One(rows), vm) + }) + } else { + let iterator = rowdicts.py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iterator, vm); + let terminator_chars = terminator_chars(&dialect.lineterminator); + let mut line = String::new(); + // One view across the loop: its step count is what polls the time limit. + let mut rows = iterator.read(vm); + while let Some(rowdict) = rows.py_next(vm)? { + defer_drop!(rowdict, vm); + let items = dict_to_list(obj, spec, rowdict, vm)?; + defer_drop!(items, vm); + writerow_now(write, &dialect, &terminator_chars, items, &mut line, vm)?; + } + Ok(CallResult::Value(Value::None)) + } +} + +/// What flattening a row needs: `fieldnames` as a list, the set CPython subtracts them +/// through under `extrasaction='raise'` (`None` under `'ignore'`), and `restval`. +/// +/// CPython reads the attributes for every row, so a `writerows` call keeps one of these +/// and rebuilds it when [`RowSpec::is_current`] sees an attribute change between rows. +struct RowSpec { + /// The attribute objects the spec was read from, kept to detect reassignment. + fieldnames: Value, + restval: Value, + extrasaction: Value, + names: Vec, + known: Option, +} + +impl DropWithContext for RowSpec { + fn drop_with(self, ctx: &mut C) { + self.fieldnames.drop_with(ctx); + self.restval.drop_with(ctx); + self.extrasaction.drop_with(ctx); + self.names.drop_with(ctx); + self.known.drop_with(ctx); + } +} + +impl RowSpec { + /// Reads the spec off the writer for `rowdict`. Under `'raise'` CPython reaches + /// `rowdict.keys()` before it hashes the names, so a row that is not a dict fails here + /// first; under `'ignore'` it iterates `fieldnames` before `rowdict.get()`. + fn read<'h>(obj: &HeapRead<'h, CsvObject>, rowdict: &Value, vm: &mut VM<'h>) -> RunResult { + let (fieldnames, restval, extrasaction) = dict_writer_part(obj, vm, |writer| { + ( + writer.fieldnames.clone_with_heap(vm.heap), + writer.restval.clone_with_heap(vm.heap), + writer.extrasaction.clone_with_heap(vm.heap), + ) + }); + defer_drop!(fieldnames, vm); + defer_drop!(restval, vm); + defer_drop!(extrasaction, vm); + let raise_on_extra = extrasaction.is_str(vm.heap) && extrasaction.to_str(vm)? == "raise"; + if raise_on_extra && row_dict(rowdict, vm).is_none() { + return Err(dict_method_missing(rowdict, raise_on_extra, vm)); + } + let mut names_guard = DropGuard::new(fieldnames_items(fieldnames, vm)?, vm); + let (names, vm) = names_guard.as_parts_mut(); + let known = if raise_on_extra { + Some(known_names(names, vm)?) + } else { + None + }; + let (names, vm) = names_guard.into_parts(); + Ok(Self { + fieldnames: fieldnames.clone_with_heap(vm.heap), + restval: restval.clone_with_heap(vm.heap), + extrasaction: extrasaction.clone_with_heap(vm.heap), + names, + known, + }) + } + + /// Whether the attributes still describe this spec: the same three objects, and for a + /// `fieldnames` list the same items, since the list can be mutated in place between + /// rows. A mutable iterable of any other kind (a set, a dict view) is reread per row. + fn is_current(&self, fieldnames: &Value, restval: &Value, extrasaction: &Value, vm: &VM<'_>) -> bool { + self.fieldnames.is(fieldnames) + && self.restval.is(restval) + && self.extrasaction.is(extrasaction) + && match fieldnames { + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::List(list) => { + let items = list.as_slice(); + items.len() == self.names.len() && items.iter().zip(&self.names).all(|(a, b)| a.is(b)) + } + HeapData::Tuple(_) + | HeapData::Str(_) + | HeapData::Bytes(_) + | HeapData::Range(_) + | HeapData::FrozenSet(_) => true, + _ => false, + }, + _ => true, + } + } +} + +/// `set(fieldnames)`, which the `extrasaction='raise'` check subtracts the row's keys +/// through as CPython does, so the names must be hashable. +fn known_names(names: &[Value], vm: &mut VM<'_>) -> RunResult { + let mut known_guard = DropGuard::new(Set::new(), vm); + let (known, vm) = known_guard.as_parts_mut(); + for name in names { + known.add(name.clone_with_heap(vm.heap), vm)?; + } + let (known, vm) = known_guard.into_parts(); + Ok(Value::Ref(vm.heap.allocate(HeapData::Set(known)))) +} + +/// `DictWriter._dict_to_list`: `rowdict.get(key, restval)` for each field name, after the +/// `extrasaction='raise'` check for keys outside `fieldnames`. +/// +/// `spec` is the caller's cache across rows, filled or refreshed here when the +/// attributes it was read from changed; the attributes are untouched until a row arrives. +fn dict_to_list<'h>( + obj: &HeapRead<'h, CsvObject>, + spec: &mut Option, + rowdict: &Value, + vm: &mut VM<'h>, +) -> RunResult> { + let current = dict_writer_part(obj, vm, |writer| { + spec.as_ref() + .is_some_and(|spec| spec.is_current(&writer.fieldnames, &writer.restval, &writer.extrasaction, vm)) + }); + if !current { + if let Some(stale) = spec.take() { + stale.drop_with(vm); + } + *spec = Some(RowSpec::read(obj, rowdict, vm)?); + } + let Some(spec) = spec else { unreachable!("filled above") }; + let raise_on_extra = spec.known.is_some(); + let Some(dict) = row_dict(rowdict, vm) else { + return Err(dict_method_missing(rowdict, raise_on_extra, vm)); + }; + if let Some(known) = &spec.known { + check_extra_keys(&dict, known, vm)?; + } + // One list per row: `writerows` on a file keeps every row's list until the single + // write, so each is preflighted against the usage so far. + vm.heap.tracker.check_allocation(spec.names.len() * VALUE_SIZE)?; + let mut items_guard = DropGuard::new(Vec::with_capacity(spec.names.len()), vm); + let (items, vm) = items_guard.as_parts_mut(); + for name in &spec.names { + let value = match dict.dict_get(name, vm)? { + Some(value) => value, + None => spec.restval.clone_with_heap(vm.heap), + }; + items.push(value); + } + Ok(items_guard.into_inner()) +} + +/// The row as a dict, or `None` when it is anything else (see [`dict_method_missing`]). +fn row_dict<'h>(rowdict: &Value, vm: &VM<'h>) -> Option> { + match rowdict { + Value::Ref(id) => match vm.heap.read(*id) { + HeapReadOutput::Dict(dict) => Some(dict), + _ => None, + }, + _ => None, + } +} + +/// The `AttributeError` CPython raises for a row that is not a mapping: `.keys()` is +/// what the `raise` check touches first, `.get()` otherwise. +fn dict_method_missing(rowdict: &Value, raise_on_extra: bool, vm: &VM<'_>) -> RunError { + let method = if raise_on_extra { "keys" } else { "get" }; + ExcType::attribute_error(rowdict.py_type_name(vm), method) +} + +/// `rowdict.keys() - self.fieldnames`: the `ValueError` for keys outside `known`, the set +/// [`known_names`] built. +fn check_extra_keys<'h>(dict: &HeapRead<'h, Dict>, known: &Value, vm: &mut VM<'h>) -> RunResult<()> { + let Value::Ref(known_id) = known else { + unreachable!("known_names allocates a set") + }; + let HeapReadOutput::Set(known) = vm.heap.read(*known_id) else { + unreachable!("known_names allocates a set") + }; + let keys = dict_keys(dict, vm)?; + defer_drop!(keys, vm); + // The reprs of the offending keys outlive the keys' own tracked reprs, so the message + // grows through the tracker; a wide row allocates per key, so the loop also polls. + let mut wrong = String::new(); + // A key's repr may be empty, so the message's emptiness cannot stand in for this. + let mut any_wrong = false; + for (i, key) in keys.iter().enumerate() { + vm.heap.tracker.check_memory_time_every(i)?; + if !known.contains(key, vm)? { + let repr = key.py_repr(vm)?; + defer_drop!(repr, vm); + let mut builder = StringBuilder::from_existing(mem::take(&mut wrong), &vm.heap.tracker); + if any_wrong { + builder.push_str(", ")?; + } + builder.push_str(repr.to_str(vm)?)?; + wrong = builder.finish_raw()?; + any_wrong = true; + } + } + if any_wrong { + Err(ExcType::value_error(format!( + "dict contains fields not in fieldnames: {wrong}" + ))) + } else { + Ok(()) + } +} + +/// Owned clones of a dict's keys, in insertion order: a bulk copy, preflighted as one. +fn dict_keys<'h>(dict: &HeapRead<'h, Dict>, vm: &VM<'h>) -> RunResult> { + let dict = dict.get(vm.heap); + vm.heap + .tracker + .check_allocation(dict.len().saturating_mul(VALUE_SIZE))?; + Ok(dict.iter().map(|(key, _)| key.clone_with_heap(vm.heap)).collect()) +} + +/// Formats `items` and writes them through the wrapped `_csv.writer`. +fn write_items<'h>(obj: &HeapRead<'h, CsvObject>, items: &[Value], vm: &mut VM<'h>) -> RunResult { + let writer = dict_writer_part(obj, vm, |writer| writer.writer.clone_with_heap(vm.heap)); + defer_drop!(writer, vm); + with_writer(writer, vm, |writer_obj, vm| { + super::writer::write_fields(writer_obj, items, vm) + }) +} + +/// Runs `call` on the wrapped `_csv.writer`, an internal error if `writer` is not one (the +/// constructor always stores one). +fn with_writer<'h, T>( + writer: &Value, + vm: &mut VM<'h>, + call: impl FnOnce(&HeapRead<'h, CsvObject>, &mut VM<'h>) -> RunResult, +) -> RunResult { + let Value::Ref(writer_id) = writer else { + return Err(RunError::internal("DictWriter: writer is not a _csv.writer")); + }; + let HeapReadOutput::Csv(mut writer_obj) = vm.heap.read(*writer_id) else { + return Err(RunError::internal("DictWriter: writer is not a _csv.writer")); + }; + call(&mut writer_obj, vm) +} + +/// Whether the wrapped `_csv.writer` targets a file, with its bound `write` and dialect; +/// `None` if `writer` is not one. +fn writer_parts(writer: &Value, vm: &VM<'_>) -> Option<(bool, Value, Arc)> { + match writer { + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Csv(csv) => match &**csv { + CsvObject::Writer(writer) => Some(( + writer.targets_file(vm), + writer.write_method(vm.heap), + Arc::clone(&writer.dialect), + )), + _ => None, + }, + _ => None, + }, + _ => None, + } +} + +/// Reads one field of the `DictWriter` under a short borrow. +fn dict_writer_part<'h, T>(obj: &HeapRead<'h, CsvObject>, vm: &VM<'h>, part: impl FnOnce(&DictWriter) -> T) -> T { + let CsvObject::DictWriter(writer) = obj.get(vm.heap) else { + unreachable!("dispatched on CsvObject::DictWriter") + }; + part(writer) +} + +/// The next record's fields from the wrapped `_csv.reader`, taken as a vector rather than +/// through `next()` so no list is built and discarded per row. +fn next_row(reader: &Value, vm: &mut VM<'_>) -> RunResult>> { + let Value::Ref(reader_id) = reader else { + return Err(RunError::internal("DictReader: reader is not a _csv.reader")); + }; + let HeapReadOutput::Csv(reader_obj) = vm.heap.read(*reader_id) else { + return Err(RunError::internal("DictReader: reader is not a _csv.reader")); + }; + super::reader::next_fields(&reader_obj, vm) +} + +/// `fieldnames` as owned values: a `list` (what a header read produces) is copied directly, +/// preflighted as a bulk copy; any other iterable is iterated as `zip` or `list()` would. +fn fieldnames_items(fieldnames: &Value, vm: &mut VM<'_>) -> RunResult> { + match fieldnames { + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::List(list) => { + let items = list.as_slice(); + vm.heap + .tracker + .check_allocation(items.len().saturating_mul(VALUE_SIZE))?; + Ok(items.iter().map(|item| item.clone_with_heap(vm.heap)).collect()) + } + _ => collect_iterable(fieldnames, vm), + }, + _ => collect_iterable(fieldnames, vm), + } +} + +/// The wrapped reader's `line_num`. +fn reader_line_num(reader: &Value, vm: &VM<'_>) -> u64 { + match reader { + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Csv(csv) => match &**csv { + CsvObject::Reader(reader) => reader.line_num, + _ => 0, + }, + _ => 0, + }, + _ => 0, + } +} diff --git a/crates/bashkit-monty/src/types/csv/mod.rs b/crates/bashkit-monty/src/types/csv/mod.rs new file mode 100644 index 000000000..7dfb0e360 --- /dev/null +++ b/crates/bashkit-monty/src/types/csv/mod.rs @@ -0,0 +1,256 @@ +//! Heap objects of the `csv` module: readers, writers, `DictReader`, `DictWriter` and dialects. +//! +//! One `HeapData::Csv(CsvObject)` variant covers the family, as `Itertools` does for its +//! adaptors; the Python-visible `type()` names live in [`Type`]. A reader pulls lines from its +//! source through `py_next` and so cannot load a file itself: `modules/csv.rs` yields that load +//! at construction, before any consumer runs. + +pub mod dialect; +pub mod dict; +pub mod reader; +pub mod writer; + +use std::{fmt::Write, mem}; + +pub(crate) use dialect::{DIALECT_NAMES, Dialect, FmtParams, Quoting}; +pub(crate) use dict::{DictReader, DictWriter}; +pub(crate) use reader::{FIELD_SIZE_LIMIT, Reader}; +use serde::{Deserialize, Serialize}; +pub(crate) use writer::{Writer, write_method}; + +use crate::{ + args::ArgValues, + bytecode::{CallResult, VM}, + exception_private::{ExcType, ExcTypeExt, RunResult}, + hash::{HashValue, identity_hash}, + heap::{DropWithContext, HeapData, HeapId, HeapItem, HeapObjectRead, HeapReadOutput}, + intern::StaticStrings, + types::{LazyHeapSet, PyTrait, Type}, + value::{EitherStr, Value}, +}; + +/// One `csv` object, whichever constructor produced it. +#[derive(Debug, Serialize, Deserialize)] +pub(crate) enum CsvObject { + Reader(Reader), + Writer(Writer), + DictReader(DictReader), + DictWriter(DictWriter), + Dialect(Dialect), +} + +/// Which object a [`CsvObject`] is, without borrowing it: dispatch reads this tag under a +/// short borrow and lets it end before re-entering the VM. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + Reader, + Writer, + DictReader, + DictWriter, + Dialect, +} + +impl CsvObject { + fn kind(&self) -> Kind { + match self { + Self::Reader(_) => Kind::Reader, + Self::Writer(_) => Kind::Writer, + Self::DictReader(_) => Kind::DictReader, + Self::DictWriter(_) => Kind::DictWriter, + Self::Dialect(_) => Kind::Dialect, + } + } + + /// The Python type this object reports. + pub(crate) fn py_type(&self) -> Type { + match self { + Self::Reader(_) => Type::CsvReader, + Self::Writer(_) => Type::CsvWriter, + Self::DictReader(_) => Type::CsvDictReader, + Self::DictWriter(_) => Type::CsvDictWriter, + Self::Dialect(_) => Type::CsvDialect, + } + } + + /// Invokes `on_child` for each heap id this object owns (GC trace hook). + pub(crate) fn for_each_child_id(&self, on_child: impl FnMut(HeapId)) { + match self { + Self::Reader(reader) => reader.for_each_child_id(on_child), + Self::Writer(writer) => writer.for_each_child_id(on_child), + Self::DictReader(reader) => reader.for_each_child_id(on_child), + Self::DictWriter(writer) => writer.for_each_child_id(on_child), + Self::Dialect(_) => {} + } + } + + /// Allocates this object on the heap. + pub(crate) fn allocate(self, vm: &VM<'_>) -> Value { + Value::Ref(vm.heap.allocate(HeapData::Csv(Box::new(self)))) + } +} + +impl HeapItem for CsvObject { + /// Mirrors [`CsvObject::for_each_child_id`] — the two must stay in sync. + fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + match self { + Self::Reader(reader) => reader.py_dec_ref_ids(stack), + Self::Writer(writer) => writer.py_dec_ref_ids(stack), + Self::DictReader(reader) => reader.py_dec_ref_ids(stack), + Self::DictWriter(writer) => writer.py_dec_ref_ids(stack), + Self::Dialect(_) => {} + } + } +} + +impl<'h> PyTrait<'h> for HeapObjectRead<'h, CsvObject> { + fn py_type(&self, vm: &VM<'h>) -> Type { + self.get(vm.heap).py_type() + } + + fn py_len(&self, _: &VM<'h>) -> Option { + None + } + + fn py_eq_impl(&self, _: &Value, _: &mut VM<'h>) -> RunResult> { + Ok(None) + } + + /// Identity hashing, as for any class without `__eq__`. + fn py_hash(&self, _: &mut VM<'h>) -> RunResult> { + Ok(Some(identity_hash(self.id()))) + } + + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, _: &mut LazyHeapSet) -> RunResult<()> { + self.py_default_repr_fmt(f, vm) + } + + fn py_is_iterator(&self, vm: &VM<'h>) -> bool { + matches!(self.get(vm.heap).kind(), Kind::Reader | Kind::DictReader) + } + + fn py_is_iterable(&self, vm: &VM<'h>) -> bool { + self.py_is_iterator(vm) + } + + /// `iter(reader) is reader`; the other objects are not iterable. + fn py_iter(&self, vm: &mut VM<'h>) -> RunResult { + if self.py_is_iterator(vm) { + Ok(CallResult::Value(self.clone_value(vm.heap))) + } else { + Err(ExcType::type_error_not_iterable(&self.py_type_name(vm))) + } + } + + fn py_next(&mut self, vm: &mut VM<'h>) -> RunResult> { + match self.get(vm.heap).kind() { + Kind::Reader => reader::next(self, vm), + Kind::DictReader => dict::reader_next(self, vm), + Kind::Writer | Kind::DictWriter | Kind::Dialect => { + Err(ExcType::type_error_not_iterator(&self.py_type_name(vm))) + } + } + } + + fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { + let Some(name) = attr.static_string(vm.interns) else { + return Err(ExcType::attribute_error(self.py_type_name(vm), attr.as_str(vm.interns))); + }; + let value = match (self.get(vm.heap), name) { + (CsvObject::Reader(reader), StaticStrings::Dialect) => { + CsvObject::Dialect(Dialect::clone(&reader.dialect)).allocate(vm) + } + (CsvObject::Reader(reader), StaticStrings::LineNum) => line_num_value(reader.line_num)?, + (CsvObject::Writer(writer), StaticStrings::Dialect) => { + CsvObject::Dialect(Dialect::clone(&writer.dialect)).allocate(vm) + } + (CsvObject::DictReader(_), StaticStrings::Fieldnames) => { + // Reading the header mutates the object, which needs its own handle. + let HeapReadOutput::Csv(this) = vm.heap.read(self.id()) else { + unreachable!("self is a csv object") + }; + return dict::reader_fieldnames(&this, vm).map(|value| Some(CallResult::Value(value))); + } + (CsvObject::DictReader(reader), StaticStrings::LineNum) => line_num_value(reader.line_num)?, + (CsvObject::DictReader(reader), StaticStrings::Reader) => reader.reader.clone_with_heap(vm.heap), + (CsvObject::DictReader(reader), StaticStrings::Restkey) => reader.restkey.clone_with_heap(vm.heap), + (CsvObject::DictReader(reader), StaticStrings::Restval) => reader.restval.clone_with_heap(vm.heap), + (CsvObject::DictReader(reader), StaticStrings::Dialect) => reader.dialect.clone_with_heap(vm.heap), + (CsvObject::DictWriter(writer), StaticStrings::Fieldnames) => writer.fieldnames.clone_with_heap(vm.heap), + (CsvObject::DictWriter(writer), StaticStrings::Restval) => writer.restval.clone_with_heap(vm.heap), + (CsvObject::DictWriter(writer), StaticStrings::Extrasaction) => { + writer.extrasaction.clone_with_heap(vm.heap) + } + (CsvObject::DictWriter(writer), StaticStrings::Writer) => writer.writer.clone_with_heap(vm.heap), + (CsvObject::Dialect(dialect), name) => match dialect.attr(name, vm) { + Some(value) => value, + None => return Err(ExcType::attribute_error(Type::CsvDialect, attr.as_str(vm.interns))), + }, + _ => return Err(ExcType::attribute_error(self.py_type_name(vm), attr.as_str(vm.interns))), + }; + Ok(Some(CallResult::Value(value))) + } + + /// The `DictReader` and `DictWriter` attributes that are plain Python attributes in + /// CPython are assignable, except the wrapped `reader` / `writer` and `line_num`; + /// everything on the `_csv` objects is read-only, with CPython's two wordings for a + /// member and a getset descriptor. + fn py_set_attr(&mut self, name: &EitherStr, value: Value, vm: &mut VM<'h>) -> RunResult<()> { + let slot = match (self.get_mut(vm.heap), name.static_string(vm.interns)) { + (CsvObject::Reader(_), Some(StaticStrings::Dialect | StaticStrings::LineNum)) + | (CsvObject::Writer(_), Some(StaticStrings::Dialect)) => { + value.drop_with(vm); + return Err(ExcType::attribute_error_readonly()); + } + (CsvObject::DictReader(reader), Some(StaticStrings::Fieldnames)) => { + // `None` unsets the names, so the next row read is the header again. + let names = match value { + Value::None => None, + names => Some(names), + }; + mem::replace(&mut reader.fieldnames, names).drop_with(vm); + return Ok(()); + } + (CsvObject::DictReader(reader), Some(StaticStrings::Restkey)) => &mut reader.restkey, + (CsvObject::DictReader(reader), Some(StaticStrings::Restval)) => &mut reader.restval, + (CsvObject::DictReader(reader), Some(StaticStrings::Dialect)) => &mut reader.dialect, + (CsvObject::DictWriter(writer), Some(StaticStrings::Fieldnames)) => &mut writer.fieldnames, + (CsvObject::DictWriter(writer), Some(StaticStrings::Restval)) => &mut writer.restval, + (CsvObject::DictWriter(writer), Some(StaticStrings::Extrasaction)) => &mut writer.extrasaction, + (CsvObject::Dialect(_), Some(attr)) if Dialect::is_attr(attr) => { + value.drop_with(vm); + return Err(ExcType::attribute_error_not_writable( + name.as_str(vm.interns), + &Type::CsvDialect.to_string(), + )); + } + _ => { + value.drop_with(vm); + let type_name = self.py_type_name(vm); + return Err(ExcType::attribute_error_no_setattr(&type_name, name.as_str(vm.interns))); + } + }; + mem::replace(slot, value).drop_with(vm); + Ok(()) + } + + fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { + match (self.get(vm.heap).kind(), attr.static_string(vm.interns)) { + (Kind::Writer, Some(StaticStrings::Writerow)) => writer::writerow(self, args, vm), + (Kind::Writer, Some(StaticStrings::Writerows)) => writer::writerows(self, args, vm), + (Kind::DictWriter, Some(StaticStrings::Writerow)) => dict::writer_writerow(self, args, vm), + (Kind::DictWriter, Some(StaticStrings::Writerows)) => dict::writer_writerows(self, args, vm), + (Kind::DictWriter, Some(StaticStrings::Writeheader)) => dict::writer_writeheader(self, args, vm), + _ => { + let type_name = self.py_type_name(vm); + Err(ExcType::attribute_error_method(type_name, attr, args, vm)) + } + } + } +} + +/// `line_num` as a Python `int`. +fn line_num_value(line_num: u64) -> RunResult { + i64::try_from(line_num) + .map(Value::Int) + .map_err(|_| ExcType::overflow_c_ssize_t()) +} diff --git a/crates/bashkit-monty/src/types/csv/reader.rs b/crates/bashkit-monty/src/types/csv/reader.rs new file mode 100644 index 000000000..6cdf7f7dd --- /dev/null +++ b/crates/bashkit-monty/src/types/csv/reader.rs @@ -0,0 +1,388 @@ +//! `_csv.reader`: parses records from an iterator of lines. +//! +//! The parser is a port of CPython's `parse_process_char` state machine, so quoting, +//! escaping, `skipinitialspace`, `strict` and the `QUOTE_*` conversions behave identically. +//! A record may span several source lines (a quoted field containing newlines), so one +//! `__next__` pulls lines until the machine returns to `StartRecord`. + +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; + +use crate::{ + bytecode::VM, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult}, + heap::{DropGuard, Heap, HeapData, HeapId, HeapReadMut}, + types::{ + CsvObject, List, + csv::dialect::{Dialect, Quoting}, + str::allocate_string, + r#type::parse_f64_from_str, + }, + value::{VALUE_SIZE, Value}, +}; + +/// CPython's default `csv.field_size_limit()`; Monty does not let it change. +pub(crate) const FIELD_SIZE_LIMIT: usize = 131_072; + +/// A `_csv.reader`: the source iterator, the dialect, and the lines consumed so far. +#[derive(Debug, Serialize, Deserialize)] +pub(crate) struct Reader { + /// The iterator lines come from (`iter(csvfile)` at construction). Owned. + source: Value, + /// Shared with each record read, so a row costs no copy of the dialect's strings. + pub(crate) dialect: Arc, + /// Source lines consumed, including those a multi-line record spans. + pub(crate) line_num: u64, + /// Fields in the last record: the capacity the next record's vector starts at, since + /// records of one source are nearly always the same width. + #[serde(skip)] + field_hint: usize, +} + +impl Reader { + pub(crate) fn new(source: Value, dialect: Dialect) -> Self { + Self { + source, + dialect: Arc::new(dialect), + line_num: 0, + field_hint: 0, + } + } + + /// Invokes `on_child` for each heap id this reader owns (GC trace hook). + pub(crate) fn for_each_child_id(&self, mut on_child: impl FnMut(HeapId)) { + if let Value::Ref(id) = &self.source { + on_child(*id); + } + } + + /// Releases the source reference (mirrors `for_each_child_id`). + pub(crate) fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + self.source.py_dec_ref_ids(stack); + } +} + +/// One record as a `list` of fields, or `None` once the source is exhausted. +pub(super) fn next<'h>(obj: &HeapReadMut<'h, CsvObject>, vm: &mut VM<'h>) -> RunResult> { + let fields = next_fields(obj, vm)?; + Ok(fields.map(|fields| Value::Ref(vm.heap.allocate(HeapData::List(List::new(fields)))))) +} + +/// The fields of the next record, or `None` once the source is exhausted. `DictReader` +/// takes the fields this way, so its rows never pass through a list. +pub(super) fn next_fields<'h>(obj: &HeapReadMut<'h, CsvObject>, vm: &mut VM<'h>) -> RunResult>> { + let (source, dialect, field_hint) = { + let CsvObject::Reader(reader) = obj.get(vm.heap) else { + unreachable!("dispatched on CsvObject::Reader") + }; + ( + reader.source.clone_with_heap(vm.heap), + Arc::clone(&reader.dialect), + reader.field_hint, + ) + }; + defer_drop!(source, vm); + vm.heap.tracker.check_allocation(field_hint * VALUE_SIZE)?; + let mut fields_guard = DropGuard::new(Vec::with_capacity(field_hint), vm); + let (fields, vm) = fields_guard.as_parts_mut(); + let mut parser = Parser::new(&dialect); + + // Native loops over source lines and their characters: poll the tracker so time + // limits still bite on one enormous line. + let mut polls = 0usize; + loop { + vm.heap.tracker.check_time_every(polls)?; + polls += 1; + let line = { + let mut guard = vm.recursion_guard()?; + let vm = &mut *guard; + source.read(vm).py_next(vm)? + }; + let Some(line) = line else { + // End of input mid-record: strict mode rejects it, otherwise the partial field closes the record. + if parser.field_len != 0 || parser.state == State::InQuotedField { + if dialect.strict { + return Err(ExcType::csv_error("unexpected end of data")); + } + parser.save_field(fields, vm.heap)?; + break; + } + return Ok(None); + }; + defer_drop!(line, vm); + if !line.is_str(vm.heap) { + return Err(ExcType::csv_error(format!( + "iterator should return strings, not {} (the file should be opened in text mode)", + line.py_type_name(vm) + ))); + } + if let CsvObject::Reader(reader) = obj.get_mut(vm.heap) { + reader.line_num += 1; + } + // The parser only allocates, so the line is read in place rather than copied. + let heap: &Heap = vm.heap; + let mut rest = line.to_str_heap(heap, vm.interns)?; + while !rest.is_empty() { + heap.tracker.check_time_every(polls)?; + polls += 1; + // Inside a field, everything up to the next character the dialect treats + // specially goes in as one run; any other state moves one character. + let run = parser.run_len(rest); + if run > 0 { + parser.add_run(&rest[..run])?; + rest = &rest[run..]; + } else { + let c = rest.chars().next().expect("rest is not empty"); + rest = &rest[c.len_utf8()..]; + parser.process_char(Some(c), fields, heap)?; + } + } + parser.process_char(None, fields, heap)?; + if parser.state == State::StartRecord { + break; + } + } + let (fields, vm) = fields_guard.into_parts(); + if let CsvObject::Reader(reader) = obj.get_mut(vm.heap) { + reader.field_hint = fields.len(); + } + Ok(Some(fields)) +} + +/// The parser states of CPython's `_csv.c`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + StartRecord, + StartField, + EscapedChar, + InField, + InQuotedField, + EscapeInQuotedField, + QuoteInQuotedField, + EatCrNl, + AfterEscapedCrNl, +} + +/// Per-record parse state. Completed fields go to the caller's guarded `Vec`, so the +/// parser itself holds no heap references. +struct Parser<'d> { + dialect: &'d Dialect, + state: State, + /// The field being built; kept between fields so its capacity is reused. + field: String, + /// Characters in `field`, checked against [`FIELD_SIZE_LIMIT`]. + field_len: usize, + /// Whether the current field started without a quote: drives the `QUOTE_NONNUMERIC`, + /// `QUOTE_STRINGS` and `QUOTE_NOTNULL` conversions. + unquoted_field: bool, +} + +impl<'d> Parser<'d> { + fn new(dialect: &'d Dialect) -> Self { + Self { + dialect, + state: State::StartRecord, + field: String::new(), + field_len: 0, + unquoted_field: false, + } + } + + /// Feeds one character, or `None` for the end of a source line. + fn process_char(&mut self, c: Option, fields: &mut Vec, heap: &Heap) -> RunResult<()> { + let d = self.dialect; + // The state a line break leads to: the record is complete at end of line, + // otherwise the rest of the terminator is swallowed. + let after_break = |c: Option| { + if c.is_none() { + State::StartRecord + } else { + State::EatCrNl + } + }; + + match self.state { + State::StartRecord => match c { + // An empty line is an empty record. + None => {} + Some('\n' | '\r') => self.state = State::EatCrNl, + Some(_) => { + self.state = State::StartField; + return self.process_char(c, fields, heap); + } + }, + State::StartField => { + self.unquoted_field = true; + match c { + None | Some('\n' | '\r') => { + self.save_field(fields, heap)?; + self.state = after_break(c); + } + Some(ch) if self.is_quote(ch) => { + self.unquoted_field = false; + self.state = State::InQuotedField; + } + Some(ch) if Some(ch) == d.escapechar => self.state = State::EscapedChar, + // Leading spaces are skipped. + Some(' ') if d.skipinitialspace => {} + Some(ch) if ch == d.delimiter => self.save_field(fields, heap)?, + Some(ch) => { + self.add_char(ch)?; + self.state = State::InField; + } + } + } + State::EscapedChar => { + if let Some(ch @ ('\n' | '\r')) = c { + self.add_char(ch)?; + self.state = State::AfterEscapedCrNl; + } else { + self.add_char(c.unwrap_or('\n'))?; + self.state = State::InField; + } + } + State::AfterEscapedCrNl => { + if c.is_some() { + self.state = State::InField; + return self.process_char(c, fields, heap); + } + } + State::InField => match c { + None | Some('\n' | '\r') => { + self.save_field(fields, heap)?; + self.state = after_break(c); + } + Some(ch) if Some(ch) == d.escapechar => self.state = State::EscapedChar, + Some(ch) if ch == d.delimiter => { + self.save_field(fields, heap)?; + self.state = State::StartField; + } + Some(ch) => self.add_char(ch)?, + }, + State::InQuotedField => match c { + // The record continues on the next source line. + None => {} + Some(ch) if Some(ch) == d.escapechar => self.state = State::EscapeInQuotedField, + Some(ch) if self.is_quote(ch) => { + self.state = if d.doublequote { + State::QuoteInQuotedField + } else { + State::InField + }; + } + Some(ch) => self.add_char(ch)?, + }, + State::EscapeInQuotedField => { + self.add_char(c.unwrap_or('\n'))?; + self.state = State::InQuotedField; + } + State::QuoteInQuotedField => match c { + Some(ch) if self.is_quote(ch) => { + self.add_char(ch)?; + self.state = State::InQuotedField; + } + Some(ch) if ch == d.delimiter => { + self.save_field(fields, heap)?; + self.state = State::StartField; + } + None | Some('\n' | '\r') => { + self.save_field(fields, heap)?; + self.state = after_break(c); + } + Some(_) if d.strict => { + return Err(ExcType::csv_error(format!( + "'{}' expected after '{}'", + d.delimiter, + d.quotechar.expect("quoting is enabled") + ))); + } + Some(ch) => { + self.add_char(ch)?; + self.state = State::InField; + } + }, + State::EatCrNl => match c { + // The rest of a `\r\n` terminator. + Some('\n' | '\r') => {} + None => self.state = State::StartRecord, + Some(_) => { + return Err(ExcType::csv_error( + "new-line character seen in unquoted field - do you need to open the file with newline=''?", + )); + } + }, + } + Ok(()) + } + + /// Bytes at the start of `rest` that the current field absorbs as ordinary text: up to + /// the next delimiter, escape or line break in a plain field, up to the next quote or + /// escape in a quoted one. Zero in every other state, where each character is a step. + fn run_len(&self, rest: &str) -> usize { + let d = self.dialect; + match self.state { + State::InField => { + rest.find(|c: char| matches!(c, '\n' | '\r') || Some(c) == d.escapechar || c == d.delimiter) + } + State::InQuotedField => rest.find(|c: char| Some(c) == d.escapechar || self.is_quote(c)), + _ => Some(0), + } + .unwrap_or(rest.len()) + } + + /// Whether `c` opens or closes a quoted field under this dialect. + fn is_quote(&self, c: char) -> bool { + Some(c) == self.dialect.quotechar && self.dialect.quoting != Quoting::None + } + + /// Appends a run of ordinary characters to the current field, within the field size limit. + fn add_run(&mut self, run: &str) -> RunResult<()> { + let count = run.chars().count(); + if self.field_len + count > FIELD_SIZE_LIMIT { + Err(field_limit_error()) + } else { + self.field.push_str(run); + self.field_len += count; + Ok(()) + } + } + + /// Appends a character to the current field, within the field size limit. + fn add_char(&mut self, c: char) -> RunResult<()> { + if self.field_len >= FIELD_SIZE_LIMIT { + Err(field_limit_error()) + } else { + self.field.push(c); + self.field_len += 1; + Ok(()) + } + } + + /// Closes the current field: an unquoted empty field is `None` under `QUOTE_NOTNULL` / + /// `QUOTE_STRINGS`, an unquoted non-empty one a `float` under `QUOTE_NONNUMERIC` / `QUOTE_STRINGS`. + fn save_field(&mut self, fields: &mut Vec, heap: &Heap) -> RunResult<()> { + let quoting = self.dialect.quoting; + let unquoted = self.unquoted_field; + let value = if unquoted && self.field_len == 0 && matches!(quoting, Quoting::Notnull | Quoting::Strings) { + Value::None + } else if unquoted && self.field_len != 0 && matches!(quoting, Quoting::Nonnumeric | Quoting::Strings) { + Value::Float(parse_f64_from_str(&self.field)?) + } else { + // From the slice: one exact-size allocation, and the buffer keeps its capacity. + allocate_string(self.field.as_str(), heap) + }; + self.field.clear(); + self.field_len = 0; + self.unquoted_field = false; + heap.tracker.check_growth(fields.len(), fields.capacity(), VALUE_SIZE)?; + fields.push(value); + Ok(()) + } +} + +/// The `_csv.Error` for a field past [`FIELD_SIZE_LIMIT`]. +fn field_limit_error() -> RunError { + ExcType::csv_error(format!("field larger than field limit ({FIELD_SIZE_LIMIT})")) +} diff --git a/crates/bashkit-monty/src/types/csv/writer.rs b/crates/bashkit-monty/src/types/csv/writer.rs new file mode 100644 index 000000000..57157c966 --- /dev/null +++ b/crates/bashkit-monty/src/types/csv/writer.rs @@ -0,0 +1,455 @@ +//! `_csv.writer`: formats records and hands each line to the target's `write()`. +//! +//! Formatting is a port of CPython's `join_append_data`, so quoting and escaping decisions +//! match. A file target yields the host write (one `OsCall` per `writerow`, and one combined +//! write per `writerows`); any other target's `write`, bound at construction, runs as a +//! Python call. + +use std::{fmt::Write, mem, sync::Arc}; + +use monty_types::ResourceTracker; +use serde::{Deserialize, Serialize}; + +use crate::{ + args::ArgValues, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunResult}, + fstring::FormatFloat, + heap::{ContainsHeap, DropWithContext, HeapData, HeapId, HeapRead}, + intern::StaticStrings, + os_dispatch::{PendingEffect, PostConversionEffect}, + string_builder::StringBuilder, + types::{ + CsvObject, PyTrait, Type, + csv::dialect::{Dialect, Quoting}, + iter::collect_owned_iterable, + str::allocate_string, + }, + value::{EitherStr, VALUE_SIZE, Value}, +}; + +/// A `_csv.writer`: the target, its `write` callable and the dialect. +#[derive(Debug, Serialize, Deserialize)] +pub(crate) struct Writer { + /// The `csvfile` argument. Owned. + target: Value, + /// `csvfile.write`, bound at construction as CPython does, so rebinding the attribute + /// later does not redirect writes. `None` for a file target, whose write is a host call + /// through `target`. Owned. + write: Value, + /// Shared with each record written, so a row costs no copy of the dialect's strings. + pub(crate) dialect: Arc, +} + +impl Writer { + pub(crate) fn new(target: Value, write: Value, dialect: Dialect) -> Self { + Self { + target, + write, + dialect: Arc::new(dialect), + } + } + + /// Whether the target is an `open()` file, whose `write()` yields a host call. + pub(crate) fn targets_file(&self, vm: &VM<'_>) -> bool { + is_file(&self.target, vm) + } + + /// An owned clone of the bound `write` (`None` for a file target). + pub(crate) fn write_method(&self, heap: &impl ContainsHeap) -> Value { + self.write.clone_with_heap(heap) + } + + /// Invokes `on_child` for each heap id this writer owns (GC trace hook). + pub(crate) fn for_each_child_id(&self, mut on_child: impl FnMut(HeapId)) { + for value in [&self.target, &self.write] { + if let Value::Ref(id) = value { + on_child(*id); + } + } + } + + /// Releases the owned references (mirrors `for_each_child_id`). + pub(crate) fn py_dec_ref_ids(&mut self, stack: &mut Vec) { + self.target.py_dec_ref_ids(stack); + self.write.py_dec_ref_ids(stack); + } +} + +/// `target.write`, looked up once at construction and required to be callable as CPython +/// does: `Some(Value::None)` for a file target (its write is a host call), `None` when +/// `target` cannot back a writer. The caller owns the returned callable. +pub(crate) fn write_method(target: &Value, vm: &mut VM<'_>) -> RunResult> { + if is_file(target, vm) { + return Ok(Some(Value::None)); + } + let name = EitherStr::Interned(vm.interns.intern_static(StaticStrings::Write)); + match target.py_getattr(&name, vm) { + Ok(CallResult::Value(method)) if method.is_callable(vm) => Ok(Some(method)), + Ok(result) => { + result.drop_with(vm); + Ok(None) + } + Err(err) if err.is_catchable(ExcType::AttributeError) => Ok(None), + Err(err) => Err(err), + } +} + +/// `writer.writerow(row)`: formats `row` and returns whatever the target's `write()` returns. +pub(super) fn writerow<'h>(obj: &HeapRead<'h, CsvObject>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let row = args.get_one_arg("writer.writerow", vm.heap)?; + defer_drop!(row, vm); + let items = row_items(row, vm)?; + defer_drop!(items, vm); + write_fields(obj, items, vm) +} + +/// Formats `items` as one record and writes it, returning whatever `write()` returns: the +/// tail of `writerow`, and of the `DictWriter` methods once they have flattened their dict. +pub(super) fn write_fields<'h>( + obj: &HeapRead<'h, CsvObject>, + items: &[Value], + vm: &mut VM<'h>, +) -> RunResult { + let (target, write, dialect) = parts(obj, vm); + defer_drop!(target, vm); + defer_drop!(write, vm); + let terminator_chars = terminator_chars(&dialect.lineterminator); + let line = format_items(&dialect, &terminator_chars, items, &mut String::new(), vm)?; + write_line(target, write, line, vm) +} + +/// `writer.writerows(rows)`: writes every row and returns `None`. +/// +/// A file target receives all the lines in one host write, since a Rust loop cannot suspend +/// once per row; any other target's `write()` is called synchronously as each row arrives. +pub(super) fn writerows<'h>(obj: &HeapRead<'h, CsvObject>, args: ArgValues, vm: &mut VM<'h>) -> RunResult { + let rows = args.get_one_arg("writer.writerows", vm.heap)?; + defer_drop!(rows, vm); + let (target, write, dialect) = parts(obj, vm); + defer_drop!(target, vm); + defer_drop!(write, vm); + let terminator_chars = terminator_chars(&dialect.lineterminator); + if is_file(target, vm) { + let rows: Vec = collect_owned_iterable(rows.clone_with_heap(vm.heap), vm)?; + defer_drop!(rows, vm); + let mut lines = String::new(); + for row in rows { + let items = row_items(row, vm)?; + defer_drop!(items, vm); + format_row(&dialect, &terminator_chars, items, &mut lines, vm)?; + } + if rows.is_empty() { + Ok(CallResult::Value(Value::None)) + } else { + let lines = StringBuilder::from_existing(lines, &vm.heap.tracker).finish(vm.heap)?; + write_line(target, write, lines, vm).map(discard_write_result) + } + } else { + let iterator = rows.py_iter(vm)?.require_synchronous(vm)?; + defer_drop!(iterator, vm); + // One line buffer serves every row, so each costs a single exact-size allocation. + let mut line = String::new(); + // One view across the loop: its step count is what polls the time limit. + let mut rows = iterator.read(vm); + while let Some(row) = rows.py_next(vm)? { + defer_drop!(row, vm); + let items = row_items(row, vm)?; + defer_drop!(items, vm); + writerow_now(write, &dialect, &terminator_chars, items, &mut line, vm)?; + } + Ok(CallResult::Value(Value::None)) + } +} + +/// Formats `items` through `line` and runs the bound `write` to completion; the per-row step +/// of `writerows` and `DictWriter.writerows` on a target that is not a file. +pub(super) fn writerow_now( + write: &Value, + dialect: &Dialect, + terminator_chars: &[char], + items: &[Value], + line: &mut String, + vm: &mut VM<'_>, +) -> RunResult<()> { + let line = format_items(dialect, terminator_chars, items, line, vm)?; + vm.evaluate_function(write, ArgValues::One(line))?.drop_with(vm); + Ok(()) +} + +/// The distinct characters of a line terminator, sorted for `binary_search`: membership +/// per field character must not scan the terminator itself, which can be any length. +/// Built once per call, since the sort is linear-logarithmic in the terminator. +pub(super) fn terminator_chars(lineterminator: &str) -> Vec { + let mut chars: Vec = lineterminator.chars().collect(); + chars.sort_unstable(); + chars.dedup(); + chars +} + +/// One record as a `str`, formatted through `line`, which is cleared first and keeps its +/// capacity for the caller's next record. +fn format_items( + dialect: &Dialect, + terminator_chars: &[char], + items: &[Value], + line: &mut String, + vm: &mut VM<'_>, +) -> RunResult { + line.clear(); + format_row(dialect, terminator_chars, items, line, vm)?; + // From the slice: one exact-size allocation, bounded by the tracker-grown buffer. + Ok(allocate_string(line.as_str(), vm.heap)) +} + +/// Appends one record to `out`: `join_append` per field plus the line terminator. +/// +/// `out` grows through a tracker-checked builder at each step, since a record copies its +/// fields' `str()` forms (twice for a quote-doubled field) before the next checkpoint. The +/// builder cannot outlive a field's `str()` call, which re-enters the VM, so it wraps `out` +/// per step rather than owning it. +pub(crate) fn format_row( + dialect: &Dialect, + terminator_chars: &[char], + items: &[Value], + out: &mut String, + vm: &mut VM<'_>, +) -> RunResult<()> { + let mut record_len = 0usize; + let mut field_buffer = String::new(); + let mut number = String::new(); + for (index, item) in items.iter().enumerate() { + // A `None` field skips the polled character loop, so poll per field as well. + vm.heap.tracker.check_time_every(index)?; + let mut quoted = match dialect.quoting { + Quoting::Nonnumeric => !is_number(item, vm), + Quoting::All => true, + Quoting::Strings => item.is_str(vm.heap), + Quoting::Notnull => !matches!(item, Value::None), + Quoting::Minimal | Quoting::None => false, + }; + field_buffer.clear(); + let tracker = &vm.heap.tracker; + match item { + Value::None => {} + // `str()` of an int or float is written to a stack or scratch buffer: the + // common numeric fields cost no heap string. + Value::Int(v) => { + let mut digits = itoa::Buffer::new(); + let text = digits.format(*v); + append_field_data(dialect, terminator_chars, text, &mut quoted, &mut field_buffer, tracker)?; + } + Value::Float(v) => { + number.clear(); + write!(number, "{}", FormatFloat(*v))?; + append_field_data( + dialect, + terminator_chars, + &number, + &mut quoted, + &mut field_buffer, + tracker, + )?; + } + _ => { + let text = item.py_str(vm)?; + defer_drop!(text, vm); + append_field_data( + dialect, + terminator_chars, + text.to_str(vm)?, + &mut quoted, + &mut field_buffer, + &vm.heap.tracker, + )?; + } + } + record_len += append_field(dialect, &field_buffer, quoted, index > 0, out, &vm.heap.tracker)?; + } + // A lone empty field would write as an empty line, which reads back as no record at all. + if items.len() == 1 && record_len == 0 { + if matches!(dialect.quoting, Quoting::None | Quoting::Strings | Quoting::Notnull) { + return Err(ExcType::csv_error("single empty field record must be quoted")); + } + append_field(dialect, "", true, false, out, &vm.heap.tracker)?; + } + let mut builder = StringBuilder::from_existing(mem::take(out), &vm.heap.tracker); + builder.push_str(&dialect.lineterminator)?; + *out = builder.finish_raw()?; + Ok(()) +} + +/// Longest stretch of a field scanned between clock polls: a field with no special +/// character is otherwise one run, however long, and never reaches the poll. +const FIELD_SCAN_CHUNK: usize = 64 * 1024; + +/// Escapes or quote-doubles the characters of one field into `buffer`, as +/// `join_append_data` does, upgrading `quoted` when a special character requires it. +/// `buffer` is at most twice `text`, which is already tracked; the loop polls the clock +/// at least once per [`FIELD_SCAN_CHUNK`] of input. +fn append_field_data( + dialect: &Dialect, + terminator_chars: &[char], + text: &str, + quoted: &mut bool, + buffer: &mut String, + tracker: &ResourceTracker, +) -> RunResult<()> { + let is_special = |c: char| { + c == dialect.delimiter + || Some(c) == dialect.escapechar + || Some(c) == dialect.quotechar + || c == '\n' + || c == '\r' + || terminator_chars.binary_search(&c).is_ok() + }; + // One reservation for the common no-escape case, rather than doubling per chunk. + buffer.reserve(text.len()); + let mut rest = text; + let mut polls = 0usize; + while !rest.is_empty() { + tracker.check_time_every(polls)?; + polls += 1; + // Everything up to the next special character is copied as one run, scanning at + // most a chunk at a time so a long ordinary field still reaches the poll above. + let window = &rest[..rest.floor_char_boundary(FIELD_SCAN_CHUNK)]; + let Some(run) = window.find(is_special) else { + buffer.push_str(window); + rest = &rest[window.len()..]; + continue; + }; + buffer.push_str(&rest[..run]); + rest = &rest[run..]; + let Some(c) = rest.chars().next() else { + break; + }; + rest = &rest[c.len_utf8()..]; + let mut want_escape = dialect.quoting == Quoting::None; + if !want_escape { + if Some(c) == dialect.quotechar { + if dialect.doublequote { + buffer.push(c); + } else { + want_escape = true; + } + } else if Some(c) == dialect.escapechar { + want_escape = true; + } + if !want_escape { + *quoted = true; + } + } + if want_escape { + let Some(escapechar) = dialect.escapechar else { + return Err(ExcType::csv_error("need to escape, but no escapechar set")); + }; + buffer.push(escapechar); + } + buffer.push(c); + } + Ok(()) +} + +/// Appends a prepared field to `out`, after a delimiter when asked and quoted when asked, +/// returning the bytes written (the delimiter included): the caller only tests it for zero. +fn append_field( + dialect: &Dialect, + text: &str, + quoted: bool, + delimited: bool, + out: &mut String, + tracker: &ResourceTracker, +) -> RunResult { + let mut builder = StringBuilder::from_existing(mem::take(out), tracker); + let mut written = text.len(); + if delimited { + builder.push(dialect.delimiter)?; + written += 1; + } + if quoted { + let quotechar = dialect.quotechar.expect("quoting requires a quotechar"); + builder.push(quotechar)?; + builder.push_str(text)?; + builder.push(quotechar)?; + written += 2; + } else { + builder.push_str(text)?; + } + *out = builder.finish_raw()?; + Ok(written) +} + +/// `PyNumber_Check`: the numeric types a `QUOTE_NONNUMERIC` writer leaves unquoted. +fn is_number(value: &Value, vm: &VM<'_>) -> bool { + matches!(value.py_type(vm), Type::Int | Type::Float | Type::Bool | Type::Complex) +} + +/// Whether `value` is an `open()` file, whose `write()` yields a host call. +fn is_file(value: &Value, vm: &VM<'_>) -> bool { + matches!(value, Value::Ref(id) if matches!(vm.heap.get(*id), HeapData::OpenFile(_))) +} + +/// The fields of one row, as `writerow`'s `iter(row)` sees them: a non-iterable row is +/// `_csv.Error`, unlike `writerows`' plain `TypeError`. A `list` or `tuple`, the usual row, +/// is copied without an iterator. +fn row_items(row: &Value, vm: &mut VM<'_>) -> RunResult> { + let direct = match row { + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::List(list) => Some(list.as_slice()), + HeapData::Tuple(tuple) => Some(tuple.as_slice()), + _ => None, + }, + _ => None, + }; + if let Some(items) = direct { + vm.heap.tracker.check_allocation(items.len() * VALUE_SIZE)?; + Ok(items.iter().map(|item| item.clone_with_heap(vm.heap)).collect()) + } else { + let iterator = match row.py_iter(vm).and_then(|call| call.require_synchronous(vm)) { + Ok(iterator) => iterator, + Err(err) if err.is_catchable(ExcType::TypeError) => { + return Err(ExcType::csv_error(format!( + "iterable expected, not {}", + row.py_type_name(vm) + ))); + } + Err(err) => return Err(err), + }; + collect_owned_iterable(iterator, vm) + } +} + +/// `write(line)`: the host call of a file target, otherwise the bound `write`. +fn write_line(target: &Value, write: &Value, line: Value, vm: &mut VM<'_>) -> RunResult { + if is_file(target, vm) { + let name = vm.interns.intern_static(StaticStrings::Write); + vm.call_attr(target.clone_with_heap(vm.heap), name, ArgValues::One(line)) + } else { + vm.call_function(write, ArgValues::One(line)) + } +} + +/// Marks a file write's pending result as `None`, which `writerows` returns. +fn discard_write_result(mut result: CallResult) -> CallResult { + if let CallResult::OsCallWithEffect { + effect: PendingEffect::Post(PostConversionEffect::WritePosition { result_none, .. }), + .. + } = &mut result + { + *result_none = true; + } + result +} + +/// The owned target, its `write` and the dialect of a writer object, read under a short borrow. +fn parts<'h>(obj: &HeapRead<'h, CsvObject>, vm: &VM<'h>) -> (Value, Value, Arc) { + let CsvObject::Writer(writer) = obj.get(vm.heap) else { + unreachable!("dispatched on CsvObject::Writer") + }; + ( + writer.target.clone_with_heap(vm.heap), + writer.write.clone_with_heap(vm.heap), + Arc::clone(&writer.dialect), + ) +} diff --git a/crates/bashkit-monty/src/types/date.rs b/crates/bashkit-monty/src/types/date.rs new file mode 100644 index 000000000..6356237a0 --- /dev/null +++ b/crates/bashkit-monty/src/types/date.rs @@ -0,0 +1,518 @@ +//! Python `datetime.date` implementation. +//! +//! Monty stores dates with `chrono::NaiveDate` and keeps CPython-compatible +//! constructor validation and arithmetic behavior. + +use std::{ + borrow::Cow, + collections::hash_map::DefaultHasher, + fmt::{self, Write}, + hash::{Hash, Hasher}, +}; + +use chrono::{Datelike, NaiveDate, NaiveTime, format::StrftimeItems}; +use monty_types::{OsFunctionCall, ResourceTracker}; + +use crate::{ + args::{ArgValues, FromArgs, StrArg}, + bytecode::{CallResult, VM}, + defer_drop, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + hash::HashValue, + heap::{Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapReadOutput}, + intern::{Interns, StaticStrings}, + string_builder::StringBuilder, + types::{ + CmpOrder, LazyHeapSet, PyTrait, TimeDelta, Type, datetime, + str::{allocate_string, allocate_string_no_interning}, + timedelta, + timezone::{format_offset_compact, format_offset_hms, tzname_string}, + }, + value::{EitherStr, Value}, +}; + +const MICROSECONDS_PER_DAY: i128 = 86_400_000_000; + +/// `datetime.date` storage backed by `chrono::NaiveDate`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)] +pub(crate) struct Date(pub(crate) NaiveDate); + +/// Creates a date from validated civil components. +/// +/// Error messages match CPython 3.14 format exactly. +pub(crate) fn from_ymd(year: i32, month: i32, day: i32) -> RunResult { + if !(1..=9999).contains(&year) { + return Err(year_out_of_range(year)); + } + if !(1..=12).contains(&month) { + return Err( + SimpleException::new_msg(ExcType::ValueError, format!("month must be in 1..12, not {month}")).into(), + ); + } + let Ok(month_u32) = u32::try_from(month) else { + return Err( + SimpleException::new_msg(ExcType::ValueError, format!("month must be in 1..12, not {month}")).into(), + ); + }; + let Ok(day_u32) = u32::try_from(day) else { + return Err(day_out_of_range_error(day, month, year)); + }; + + let Some(date) = NaiveDate::from_ymd_opt(year, month_u32, day_u32) else { + return Err(day_out_of_range_error(day, month, year)); + }; + Ok(Date(date)) +} + +/// `date`'s year-range error, raised both by construction and by the probe +/// [`datetime.astimezone`](super::datetime) makes a day either side of a value. +pub(crate) fn year_out_of_range(year: i32) -> RunError { + SimpleException::new_msg(ExcType::ValueError, format!("year must be in 1..9999, not {year}")).into() +} + +/// Produces a CPython-compatible error for an invalid day value. +/// +/// Format: `"day {day} must be in range 1..{max_day} for month {month} in year {year}"` +fn day_out_of_range_error(day: i32, month: i32, year: i32) -> RunError { + let max_day = max_day_for_month(year, month); + SimpleException::new_msg( + ExcType::ValueError, + format!("day {day} must be in range 1..{max_day} for month {month} in year {year}"), + ) + .into() +} + +/// Returns the maximum valid day for a given month and year. +fn max_day_for_month(year: i32, month: i32) -> u32 { + // Try the last possible day (31) and work backwards to find the actual max + let Ok(month_u32) = u32::try_from(month) else { + return 31; + }; + for d in (28..=31).rev() { + if NaiveDate::from_ymd_opt(year, month_u32, d).is_some() { + return d; + } + } + 31 +} + +/// Creates a date from a proleptic Gregorian ordinal value. +pub(crate) fn from_ordinal(ordinal: i32) -> RunResult { + let Some(date) = NaiveDate::from_num_days_from_ce_opt(ordinal) else { + return Err(SimpleException::new_msg(ExcType::OverflowError, "date value out of range").into()); + }; + if !(1..=9999).contains(&date.year()) { + return Err(SimpleException::new_msg(ExcType::OverflowError, "date value out of range").into()); + } + Ok(Date(date)) +} + +/// Returns the proleptic Gregorian ordinal (`1 == 0001-01-01`) for a date. +#[must_use] +pub(crate) fn to_ordinal(date: Date) -> i32 { + date.0.num_days_from_ce() +} + +/// Returns civil components `(year, month, day)`. +#[must_use] +pub(crate) fn to_ymd(date: Date) -> (i32, u32, u32) { + (date.0.year(), date.0.month(), date.0.day()) +} + +/// Constructor for `date(year, month, day)`. +pub(crate) fn init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let DateInitArgs { year, month, day } = DateInitArgs::from_args(args, vm)?; + let date = from_ymd(year, month, day)?; + Ok(Value::Ref(vm.heap.allocate(HeapData::Date(date)))) +} + +/// Argument shape for `date(year, month, day)`. +/// +/// CPython's `date()` is C-implemented (`PyArg_ParseTupleAndKeywords`), hence +/// `style = c` — "function takes at most N arguments", "function missing +/// required argument 'X' (pos N)", etc. Unlike `datetime()` it has no +/// keyword-only fields, so the derive keeps the plain (non-"positional") +/// at-most wording automatically. +#[derive(FromArgs)] +#[from_args(name = "function", style = c, at_most_total)] +struct DateInitArgs { + year: i32, + month: i32, + day: i32, +} + +/// Reads `date.today()` from the session's clock in the session zone. A `CallHost` +/// clock requests a `DateToday` answer constructed with `MontyObject::date`. +pub(crate) fn class_today(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + args.check_zero_args("date.today", vm.heap)?; + Ok(match datetime::sandbox_instant(vm)? { + None => CallResult::OsCall(OsFunctionCall::DateToday), + Some(utc) => { + let local = datetime::sandbox_local_wall_clock(vm, utc)?; + CallResult::Value(Value::Ref(vm.heap.allocate(HeapData::Date(Date(local.date()))))) + } + }) +} + +/// Classmethod `date.fromisoformat(date_string)`. +/// +/// Parses ISO 8601 date strings in the formats `YYYY-MM-DD` and `YYYYMMDD`, +/// matching CPython 3.11+ behavior. +pub(crate) fn class_fromisoformat(heap: &mut Heap, args: ArgValues, interns: &Interns) -> RunResult { + let value = args.get_one_arg("date.fromisoformat", heap)?; + let s = extract_str_arg(&value, "fromisoformat", heap, interns); + value.drop_with(heap); + let s = s?; + + let date = parse_iso_date(&s) + .ok_or_else(|| SimpleException::new_msg(ExcType::ValueError, format!("Invalid isoformat string: '{s}'")))?; + Ok(Value::Ref(heap.allocate(HeapData::Date(date)))) +} + +/// Parses an ISO 8601 date string into a `Date`. +/// +/// Uses speedate for Python-compatible ISO 8601 parsing. +fn parse_iso_date(s: &str) -> Option { + let parsed = speedate::Date::parse_bytes(s.as_bytes()).ok()?; + from_ymd(i32::from(parsed.year), i32::from(parsed.month), i32::from(parsed.day)).ok() +} + +/// Allocates a `date` from already-in-range components. +/// +/// For Rust-side construction where the values are known good (the `date.min` / +/// `date.max` class constants); anything derived from user input must go +/// through [`from_ymd`] so the components are validated. +pub(crate) fn allocate_ymd(year: i32, month: i32, day: i32, heap: &Heap) -> Value { + let date = from_ymd(year, month, day).expect("caller guarantees in-range date components"); + Value::Ref(heap.allocate(HeapData::Date(date))) +} + +/// Extracts a string from a `Value` for use by classmethods. +pub(crate) fn extract_str_arg(value: &Value, method_name: &str, heap: &Heap, interns: &Interns) -> RunResult { + match value { + Value::InternString(string_id) => Ok(interns.get_str(*string_id).to_owned()), + Value::Ref(heap_id) => match heap.get(*heap_id) { + HeapData::Str(s) => Ok(s.as_str().to_owned()), + _ => Err(ExcType::type_error(format!("{method_name}: argument must be str"))), + }, + _ => Err(ExcType::type_error(format!("{method_name}: argument must be str"))), + } +} + +impl HeapItem for Date { + fn py_dec_ref_ids(&mut self, _stack: &mut Vec) {} +} + +/// `HeapRead`-based dispatch for `Date`, enabling the `HeapReadOutput` enum to +/// delegate `PyTrait` calls to heap-resident dates. +impl<'h> PyTrait<'h> for HeapObjectRead<'h, Date> { + fn py_type(&self, _vm: &VM<'h>) -> Type { + Type::Date + } + + fn py_len(&self, _vm: &VM<'h>) -> Option { + None + } + + fn py_eq_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let Some(HeapReadOutput::Date(other)) = other.read_heap(vm) else { + return Ok(None); + }; + Ok(Some(*self.get(vm.heap) == *other.get(vm.heap))) + } + + fn py_hash(&self, vm: &mut VM<'h>) -> RunResult> { + let mut hasher = DefaultHasher::new(); + self.get(vm.heap).hash(&mut hasher); + Ok(Some(HashValue::new(hasher.finish()))) + } + + fn py_cmp(&self, other: &Self, vm: &mut VM<'h>) -> RunResult { + Ok(CmpOrder::from_total(self.get(vm.heap).partial_cmp(other.get(vm.heap)))) + } + + fn py_bool(&self, _vm: &mut VM<'h>) -> RunResult { + Ok(true) + } + + fn py_repr_fmt(&self, f: &mut impl Write, vm: &mut VM<'h>, _heap_ids: &mut LazyHeapSet) -> RunResult<()> { + let (year, month, day) = to_ymd(*self.get(vm.heap)); + write!(f, "datetime.date({year}, {month}, {day})")?; + Ok(()) + } + + fn py_str(&self, vm: &mut VM<'h>) -> RunResult { + let (year, month, day) = to_ymd(*self.get(vm.heap)); + Ok(allocate_string(format!("{year:04}-{month:02}-{day:02}"), vm.heap)) + } + + fn py_add_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + let Some(HeapReadOutput::TimeDelta(other)) = other.read_heap(vm) else { + return Ok(None); + }; + Ok(py_add(*self.get(vm.heap), *other.get(vm.heap), vm.heap)) + } + + fn py_sub_impl(&self, other: &Value, vm: &mut VM<'h>) -> RunResult> { + match other.read_heap(vm) { + Some(HeapReadOutput::Date(other)) => Ok(py_sub_date(*self.get(vm.heap), *other.get(vm.heap), vm.heap)), + Some(HeapReadOutput::TimeDelta(other)) => { + Ok(py_sub_timedelta(*self.get(vm.heap), *other.get(vm.heap), vm.heap)) + } + _ => Ok(None), + } + } + + fn py_call_attr(&mut self, vm: &mut VM<'h>, attr: &EitherStr, args: ArgValues) -> RunResult { + let date = *self.get(vm.heap); + match attr.static_string(vm.interns) { + Some(StaticStrings::Isoformat) => { + args.check_zero_args("date.isoformat", vm.heap)?; + let (year, month, day) = to_ymd(date); + Ok(CallResult::Value(allocate_string_no_interning( + format!("{year:04}-{month:02}-{day:02}"), + vm.heap, + ))) + } + Some(StaticStrings::Strftime) => { + let StrftimeArgs { format } = StrftimeArgs::from_args(args, vm)?; + defer_drop!(format, vm); + let formatted = format_date_strftime(date, format.as_str(vm), &vm.heap.tracker)?; + Ok(CallResult::Value(allocate_string(formatted, vm.heap))) + } + Some(StaticStrings::Replace) => { + let (year, month, day) = to_ymd(date); + let DateReplaceArgs { + year: new_year, + month: new_month, + day: new_day, + } = DateReplaceArgs::from_args(args, vm)?; + let new_date = from_ymd( + new_year.unwrap_or(year), + new_month.unwrap_or(i32::try_from(month).expect("month in 1..=12")), + new_day.unwrap_or(i32::try_from(day).expect("day in 1..=31")), + )?; + Ok(CallResult::Value(Value::Ref( + vm.heap.allocate(HeapData::Date(new_date)), + ))) + } + Some(StaticStrings::Weekday) => { + args.check_zero_args("date.weekday", vm.heap)?; + Ok(CallResult::Value(Value::Int(i64::from( + date.0.weekday().num_days_from_monday(), + )))) + } + Some(StaticStrings::Isoweekday) => { + args.check_zero_args("date.isoweekday", vm.heap)?; + Ok(CallResult::Value(Value::Int(i64::from( + date.0.weekday().number_from_monday(), + )))) + } + _ => Err(ExcType::attribute_error_method(Type::Date, attr, args, vm)), + } + } + + fn py_getattr(&self, attr: &EitherStr, vm: &mut VM<'h>) -> RunResult> { + let (year, month, day) = to_ymd(*self.get(vm.heap)); + match attr.static_string(vm.interns) { + Some(StaticStrings::Year) => Ok(Some(CallResult::Value(Value::Int(i64::from(year))))), + Some(StaticStrings::Month) => Ok(Some(CallResult::Value(Value::Int(i64::from(month))))), + Some(StaticStrings::Day) => Ok(Some(CallResult::Value(Value::Int(i64::from(day))))), + _ => Ok(None), + } + } +} + +/// `date - date` returns a timedelta with the difference in days. +pub(crate) fn py_sub_date(a: Date, b: Date, heap: &mut Heap) -> Option { + let diff_days = i64::from(to_ordinal(a)) - i64::from(to_ordinal(b)); + let delta = timedelta::from_total_microseconds(i128::from(diff_days) * MICROSECONDS_PER_DAY).ok()?; + Some(Value::Ref(heap.allocate(HeapData::TimeDelta(delta)))) +} + +/// `date + timedelta` helper. +pub(crate) fn py_add(date: Date, delta: TimeDelta, heap: &mut Heap) -> Option { + let (days, _, _) = timedelta::components(&delta); + let new_ordinal = i64::from(to_ordinal(date)).checked_add(i64::from(days))?; + let new_ordinal = i32::try_from(new_ordinal).ok()?; + let value = from_ordinal(new_ordinal).ok()?; + Some(Value::Ref(heap.allocate(HeapData::Date(value)))) +} + +/// `date - timedelta` helper. +pub(crate) fn py_sub_timedelta(date: Date, delta: TimeDelta, heap: &mut Heap) -> Option { + let (days, _, _) = timedelta::components(&delta); + let new_ordinal = i64::from(to_ordinal(date)).checked_sub(i64::from(days))?; + let new_ordinal = i32::try_from(new_ordinal).ok()?; + let value = from_ordinal(new_ordinal).ok()?; + Some(Value::Ref(heap.allocate(HeapData::Date(value)))) +} + +/// Formats a [`Date`] with a `strftime` directive string, shared by the +/// `date.strftime()` method and f-string formatting (`f"{d:%Y-%m-%d}"`). +/// +/// Uses `chrono`'s **lenient** parser so an unrecognised directive is emitted +/// verbatim (`%Q` → `"%Q"`), matching glibc/Linux CPython — see +/// [`invalid_strftime_error`] for why that platform is the target. The +/// `ValueError` path remains for the rare directive that parses but can't be +/// rendered (so [`render_strftime`] never has to panic). +pub(crate) fn format_date_strftime(date: Date, format: &str, tracker: &ResourceTracker) -> RunResult { + // Anchored at midnight so time directives render CPython's zeros + // (`date(2024, 6, 15).strftime('%H:%M')` is `'00:00'` on both) rather than + // failing for want of a time component. + let anchored = date.0.and_time(NaiveTime::MIN); + let format = rewrite_zone_directives(format, None, None, tracker)?; + render_strftime(anchored.format_with_items(StrftimeItems::new_lenient(&rewrite_microsecond_directive(&format)))) + .ok_or_else(invalid_strftime_error) +} + +/// Substitutes the zone directives CPython fills from `utcoffset()` and +/// `tzname()`: `%z` (`±HHMM[SS]`), `%:z` (`±HH:MM[:SS]`) and `%Z` (the zone +/// name), all empty for a naive value. chrono renders the naive components +/// and cannot supply them. A `%` in the name is doubled to stay literal. +/// Every `%Z` copies the name, so the output is built against the tracker. +pub(crate) fn rewrite_zone_directives<'f>( + format: &'f str, + offset_seconds: Option, + name: Option<&str>, + tracker: &ResourceTracker, +) -> RunResult> { + // One byte-pair pass: three `str::contains` calls cost more than the whole + // chrono render on a short format. `%%z` and `%:` without `z` pass here + // and are handled by the loop below. + let may_have_zone = format + .as_bytes() + .windows(2) + .any(|pair| pair[0] == b'%' && matches!(pair[1], b'z' | b'Z' | b':')); + if !may_have_zone { + return Ok(Cow::Borrowed(format)); + } + let zone_name = offset_seconds.map(|offset| tzname_string(offset, name).replace('%', "%%")); + let mut out = StringBuilder::with_capacity(format.len(), tracker)?; + let mut rest = format; + while let Some(percent) = rest.find('%') { + let (before, from_percent) = rest.split_at(percent); + out.push_str(before)?; + let directive = &from_percent[1..]; + let consumed = if let Some(after) = directive.strip_prefix('z') { + if let Some(offset) = offset_seconds { + out.push_str(&format_offset_compact(offset))?; + } + directive.len() - after.len() + 1 + } else if let Some(after) = directive.strip_prefix(":z") { + if let Some(offset) = offset_seconds { + out.push_str(&format_offset_hms(offset))?; + } + directive.len() - after.len() + 1 + } else if let Some(after) = directive.strip_prefix('Z') { + if let Some(zone_name) = &zone_name { + out.push_str(zone_name)?; + } + directive.len() - after.len() + 1 + } else { + // Copy the directive whole, so `%%z` consumes `%%` and leaves `z` as text. + out.push('%')?; + match directive.chars().next() { + Some(c) => { + out.push(c)?; + 1 + c.len_utf8() + } + None => 1, + } + }; + rest = &from_percent[consumed..]; + } + out.push_str(rest)?; + out.finish_raw().map(Cow::Owned) +} + +/// Rewrites CPython's `%f` to chrono's `%6f` in a strftime format string. +/// +/// Both mean "fractional seconds", but chrono's bare `%f` is 9-digit +/// nanoseconds where CPython's is 6-digit microseconds; `%6f` is chrono's +/// spelling for the latter. `%%` is an escaped percent, so the `f` after it is +/// a literal and must not be rewritten. +pub(crate) fn rewrite_microsecond_directive(format: &str) -> Cow<'_, str> { + if !format.contains("%f") { + return Cow::Borrowed(format); + } + let mut out = String::with_capacity(format.len() + 1); + let mut rest = format; + while let Some(percent) = rest.find('%') { + let (before, from_percent) = rest.split_at(percent); + out.push_str(before); + // Take the directive whole, so `%%f` consumes `%%` and leaves `f` as text. + let mut chars = from_percent.char_indices().skip(1); + match chars.next() { + Some((_, 'f')) => { + out.push_str("%6f"); + rest = &from_percent[2..]; + } + Some((_, c)) => { + out.push('%'); + out.push(c); + rest = &from_percent[1 + c.len_utf8()..]; + } + None => { + out.push('%'); + rest = ""; + } + } + } + out.push_str(rest); + Cow::Owned(out) +} + +/// Renders a `chrono` strftime result without the panic that `.to_string()` +/// triggers on an invalid directive. +/// +/// `chrono`'s `DelayedFormat` `Display` impl returns `fmt::Error` for an +/// unsupported/invalid directive, and `ToString::to_string` turns that into a +/// panic — unacceptable for untrusted sandbox input. Writing into our own +/// buffer surfaces the failure as `None` so the caller can raise instead. +pub(crate) fn render_strftime(formatted: impl fmt::Display) -> Option { + let mut out = String::new(); + write!(out, "{formatted}").ok().map(|()| out) +} + +/// The `ValueError` raised when a `strftime` directive parses but can't be +/// rendered for this value (e.g. a time directive on a bare `date`). +/// +/// Unrecognised directives no longer reach this path — the lenient parser +/// emits them verbatim to match glibc/Linux CPython (`strftime('%Q') == '%Q'`), +/// rather than CPython's macOS behaviour (`'Q'`) which we deliberately don't +/// follow; see `limitations/datetime.md`. +pub(crate) fn invalid_strftime_error() -> RunError { + SimpleException::new_msg(ExcType::ValueError, "Invalid format string".to_owned()).into() +} + +/// Argument shape for `date.strftime(format)` and `datetime.strftime(format)`. +/// +/// CPython implements `strftime` as a C method and reports errors with the +/// bare method name (no class prefix), so we use `style = c_named` + the +/// `"strftime"` descriptor — matching wordings like +/// `strftime() missing required argument 'format' (pos 1)` and +/// `strftime() takes at most 1 argument (2 given)`. +/// +/// `bad_arg` opts the wrong-type wording into CPython's `_PyArg_BadArgument` +/// form (`strftime() argument 1 must be str, not `), including the +/// `None`-vs-`NoneType` special case — so the type-check logic lives in +/// the derive rather than a hand-written extract helper. +#[derive(FromArgs)] +#[from_args(name = "strftime", style = c_named, at_most_total, bad_arg)] +pub(crate) struct StrftimeArgs { + pub(crate) format: StrArg, +} + +/// Keyword arguments for `date.replace()`. All keyword-only; absent fields +/// inherit the original date's component via `unwrap_or` at the call site. +#[derive(FromArgs)] +#[from_args(name = "replace")] +struct DateReplaceArgs { + #[from_args(kw_only, default)] + year: Option, + #[from_args(kw_only, default)] + month: Option, + #[from_args(kw_only, default)] + day: Option, +} diff --git a/crates/bashkit-monty/src/types/datetime.rs b/crates/bashkit-monty/src/types/datetime.rs new file mode 100644 index 000000000..adc3190bf --- /dev/null +++ b/crates/bashkit-monty/src/types/datetime.rs @@ -0,0 +1,1537 @@ +//! Python `datetime.datetime` implementation. +//! +//! Monty stores datetimes with chrono primitives and layers CPython-compatible +//! constructor rules, aware/naive comparison semantics, and arithmetic on top. + +use std::{ + collections::hash_map::DefaultHasher, + fmt::Write, + hash::{Hash, Hasher}, +}; + +use chrono::{ + Datelike, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, TimeDelta as ChronoTimeDelta, Timelike, + format::{Parsed, StrftimeItems, parse as chrono_parse, parse_and_remainder}, +}; +use monty_types::{ + DateTimeSource, MontyDateTime, MontyTimeZone, OsFunctionCall, ResourceTracker, SandboxTimeZone, local_wall_clock, +}; + +use crate::{ + args::{ArgValues, FromArgs, StrArg}, + bytecode::{CallResult, VM}, + defer_drop, defer_drop_mut, + exception_private::{ExcType, ExcTypeExt, RunError, RunResult, SimpleException}, + hash::HashValue, + heap::{Heap, HeapData, HeapId, HeapItem, HeapObjectRead, HeapReadOutput}, + intern::{Interns, StaticStrings}, + types::{ + CmpOrder, LazyHeapSet, PyTrait, TimeDelta, TimeZone, Type, + date::{self, StrftimeArgs}, + str::{StringRepr, allocate_string, allocate_string_no_interning}, + time::{self, Time, TimeSpec}, + timedelta, timezone, + }, + value::{EitherStr, Value}, +}; + +/// Number of microseconds in a single second. +const DATE_OUT_OF_RANGE: &str = "date value out of range"; + +/// `datetime.datetime` storage backed by `chrono::NaiveDateTime` plus optional fixed offset. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub(crate) struct DateTime { + naive: NaiveDateTime, + offset_seconds: Option, + timezone_name: Option, + /// Stable timezone object identity for aware datetimes. + /// + /// CPython preserves the original `tzinfo` object identity (`dt.tzinfo is tz`) + /// and repeated `dt.tzinfo` access returns the same object. We store a retained + /// heap reference so attribute lookup can return a stable object instead of + /// allocating a new timezone each time. + tzinfo_ref: Option, +} + +impl DateTime { + /// Returns the retained `tzinfo` heap reference, if this datetime is timezone-aware. + /// + /// Used by GC traversal (`collect_child_ids`) and ref-count cascade + /// (`py_dec_ref_ids_for_data`) so that the timezone object stays alive as long + /// as the datetime references it. Without this, `gc.collect` cannot reach the + /// tzinfo and may sweep it while the datetime still points at the freed slot. + pub(crate) fn tzinfo_ref(&self) -> Option { + self.tzinfo_ref + } +} + +impl Hash for DateTime { + fn hash(&self, state: &mut H) { + // Hash must be consistent with equality (py_eq). + if is_aware(self) { + // Aware datetimes compare equal if they represent the same UTC instant, + // regardless of their local offset or timezone name. + let _ = utc_micros(self).inspect(|m| m.hash(state)); + } else { + // Naive datetimes compare equal if they have the same local fields. + local_micros(self).hash(state); + } + } +} + +/// Creates a datetime from civil components and optional fixed offset. +#[expect(clippy::too_many_arguments)] +pub(crate) fn from_components( + year: i32, + month: i32, + day: i32, + hour: i32, + minute: i32, + second: i32, + microsecond: i32, + tzinfo: Option, + tzinfo_ref: Option, + heap: &mut Heap, +) -> RunResult { + if !(0..=23).contains(&hour) { + return Err(SimpleException::new_msg(ExcType::ValueError, format!("hour must be in 0..23, not {hour}")).into()); + } + if !(0..=59).contains(&minute) { + return Err( + SimpleException::new_msg(ExcType::ValueError, format!("minute must be in 0..59, not {minute}")).into(), + ); + } + if !(0..=59).contains(&second) { + return Err( + SimpleException::new_msg(ExcType::ValueError, format!("second must be in 0..59, not {second}")).into(), + ); + } + if !(0..=999_999).contains(µsecond) { + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("microsecond must be in 0..999999, not {microsecond}"), + ) + .into()); + } + + // Delegate all date-component validation to `date::from_ymd` so date and datetime + // constructors stay in lockstep on CPython-compatible error behavior. + let date_value = date::from_ymd(year, month, day)?; + let time = NaiveTime::from_hms_micro_opt( + u32::try_from(hour).expect("hour validated to 0..=23"), + u32::try_from(minute).expect("minute validated to 0..=59"), + u32::try_from(second).expect("second validated to 0..=59"), + u32::try_from(microsecond).expect("microsecond validated to 0..=999_999"), + ) + .expect("validated time components must produce a NaiveTime"); + + let (offset_seconds, timezone_name) = match tzinfo { + Some(tz) => (Some(tz.offset_seconds), tz.name), + None => (None, None), + }; + if let Some(offset_seconds) = offset_seconds + && FixedOffset::east_opt(offset_seconds).is_none() + { + return Err(SimpleException::new_msg(ExcType::ValueError, "timezone offset out of range").into()); + } + + let mut datetime = DateTime { + naive: date_value.0.and_time(time), + offset_seconds, + timezone_name, + tzinfo_ref: None, + }; + + if let Some(offset_seconds) = offset_seconds { + let Some(utc) = to_utc_naive(&datetime) else { + return Err(SimpleException::new_msg(ExcType::OverflowError, DATE_OUT_OF_RANGE).into()); + }; + if from_utc_naive_with_offset(utc, offset_seconds).is_none() { + return Err(SimpleException::new_msg(ExcType::OverflowError, DATE_OUT_OF_RANGE).into()); + } + } + + attach_or_allocate_tzinfo_ref(&mut datetime, tzinfo_ref, heap); + Ok(datetime) +} + +/// Allocates a naive `datetime` from already-in-range components. +/// +/// For the `datetime.min` / `datetime.max` class constants; anything derived +/// from user input must go through [`from_components`] to be validated. Takes +/// `&mut Heap`, unlike its siblings, because that shared path may allocate a +/// timezone. +#[expect(clippy::too_many_arguments)] +pub(crate) fn allocate_naive( + year: i32, + month: i32, + day: i32, + hour: i32, + minute: i32, + second: i32, + microsecond: i32, + heap: &mut Heap, +) -> Value { + let datetime = from_components(year, month, day, hour, minute, second, microsecond, None, None, heap) + .expect("caller guarantees in-range datetime components"); + Value::Ref(heap.allocate(HeapData::DateTime(datetime))) +} + +/// Returns true when this is an aware datetime. +#[must_use] +pub(crate) fn is_aware(datetime: &DateTime) -> bool { + datetime.offset_seconds.is_some() +} + +/// Returns the fixed offset seconds for aware datetimes. +#[must_use] +pub(crate) fn offset_seconds(datetime: &DateTime) -> Option { + datetime.offset_seconds +} + +/// Returns timezone metadata for aware datetimes. +#[must_use] +pub(crate) fn timezone_info(datetime: &DateTime) -> Option { + datetime.offset_seconds.map(|offset_seconds| TimeZone { + offset_seconds, + name: datetime.timezone_name.clone(), + }) +} + +/// Returns civil components in compact integer widths for object conversion. +#[must_use] +pub(crate) fn to_components(datetime: &DateTime) -> Option<(i32, u8, u8, u8, u8, u8, u32)> { + let year = datetime.naive.date().year(); + if !year_in_python_range(year) { + return None; + } + + Some(( + year, + u8::try_from(datetime.naive.date().month()).expect("month is always in 1..=12"), + u8::try_from(datetime.naive.date().day()).expect("day is always in 1..=31"), + u8::try_from(datetime.naive.time().hour()).expect("hour is always in 0..=23"), + u8::try_from(datetime.naive.time().minute()).expect("minute is always in 0..=59"), + u8::try_from(datetime.naive.time().second()).expect("second is always in 0..=59"), + datetime.naive.and_utc().timestamp_subsec_micros(), + )) +} + +/// The host-value form of a datetime, or `None` when its year is outside 1..=9999. +#[must_use] +pub(crate) fn to_monty_datetime(datetime: &DateTime) -> Option { + let (year, month, day, hour, minute, second, microsecond) = to_components(datetime)?; + Some(MontyDateTime { + year, + month, + day, + hour, + minute, + second, + microsecond, + offset_seconds: datetime.offset_seconds, + timezone_name: datetime.timezone_name.clone(), + }) +} + +/// Constructor for `datetime(...)`. +pub(crate) fn init(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let DatetimeInitArgs { + year, + month, + day, + hour, + minute, + second, + microsecond, + tzinfo, + fold, + } = DatetimeInitArgs::from_args(args, vm)?; + // `tzinfo` owns the input ref; keep it alive across `tzinfo_from_value` and + // `from_components` so the heap-allocated TimeZone (if any) is not freed + // before `attach_or_allocate_tzinfo_ref` takes its own reference. + defer_drop_mut!(tzinfo, vm); + + if fold != 0 && fold != 1 { + return Err( + SimpleException::new_msg(ExcType::ValueError, format!("fold must be either 0 or 1, not {fold}")).into(), + ); + } + + let (tz, tz_ref) = tzinfo_from_value(tzinfo, vm.heap, vm.interns)?; + let dt = from_components(year, month, day, hour, minute, second, microsecond, tz, tz_ref, vm.heap)?; + Ok(Value::Ref(vm.heap.allocate(HeapData::DateTime(dt)))) +} + +/// Argument shape for `datetime(year, month, day, hour=0, minute=0, second=0, +/// microsecond=0, tzinfo=None, *, fold=0)`. +/// +/// CPython emits two distinct wordings for over-arity: when the overflow +/// could still fit in the keyword-only tail (`actual <= 9`) the message is +/// "function takes at most 8 *positional* arguments"; once it exceeds the +/// total slot count it switches to "function takes at most 9 arguments". +/// The derive turns the pivot on automatically for `style = c` structs with +/// keyword-only fields — the trailing kw-only `fold` slot is what bumps +/// `max_total` to 9. +/// +/// `fold` itself is accepted for CPython parity but currently has no effect +/// on the stored datetime — Monty does not track DST-fold disambiguation. +#[derive(FromArgs)] +#[from_args(name = "function", style = c)] +struct DatetimeInitArgs { + year: i32, + month: i32, + day: i32, + #[from_args(default = 0)] + hour: i32, + #[from_args(default = 0)] + minute: i32, + #[from_args(default = 0)] + second: i32, + #[from_args(default = 0)] + microsecond: i32, + #[from_args(default = Value::None)] + tzinfo: Value, + #[from_args(kw_only, default = 0)] + fold: i32, +} + +/// Reads `datetime.now(tz=None)` from the session clock, preserving `tz` identity. +/// Naive results use the session zone. A `CallHost` clock yields `DateTimeNow` +/// with a validated [`Option`] for the host to answer. +pub(crate) fn class_now(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let NowArgs { tz } = NowArgs::from_args(args, vm)?; + defer_drop!(tz, vm); + let (tz, tz_ref) = tzinfo_from_value(tz, vm.heap, vm.interns)?; + // Invalid fixed instants raise; only CallHost falls back to the host's clock. + let Some(utc) = sandbox_instant(vm)? else { + let tz = tz.map(|tz| MontyTimeZone { + offset_seconds: tz.offset_seconds, + name: tz.name, + }); + return Ok(CallResult::OsCall(OsFunctionCall::DateTimeNow(tz))); + }; + let mut dt = match &tz { + Some(tz) => from_utc_naive_with_timezone_parts(utc, tz.offset_seconds, tz.name.clone()), + None => from_local_naive(sandbox_local_wall_clock(vm, utc)?), + } + .ok_or_else(date_out_of_range)?; + attach_or_allocate_tzinfo_ref(&mut dt, tz_ref, vm.heap); + Ok(CallResult::Value(Value::Ref(vm.heap.allocate(HeapData::DateTime(dt))))) +} + +/// `datetime.astimezone(tz=None)`: the same instant in `tz`, or in the sandbox +/// zone at that instant when `tz` is `None`. A naive value is read as sandbox-local +/// wall time, as CPython reads it in the host's zone. +fn astimezone(dt: &DateTime, vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let AstimezoneArgs { tz } = AstimezoneArgs::from_args(args, vm)?; + defer_drop!(tz, vm); + let (tz, tz_ref) = tzinfo_from_value(tz, vm.heap, vm.interns)?; + let zone = &vm.env.os_policy.timezone; + // CPython forms `self - utcoffset()` as a datetime, so the UTC intermediate + // must be in range as well as the result. + let utc = if dt.offset_seconds.is_some() { + to_utc_naive(dt).filter(|utc| year_in_python_range(utc.year())) + } else { + probe_neighbouring_days(dt.naive.date())?; + zone.utc_from_local(dt.naive) + } + .ok_or_else(date_out_of_range)?; + let target = match tz { + Some(tz) => MontyTimeZone { + offset_seconds: tz.offset_seconds, + name: tz.name, + }, + None => zone.at(utc), + }; + let mut converted = + from_utc_naive_with_timezone_parts(utc, target.offset_seconds, target.name).ok_or_else(date_out_of_range)?; + attach_or_allocate_tzinfo_ref(&mut converted, tz_ref, vm.heap); + Ok(CallResult::Value(Value::Ref( + vm.heap.allocate(HeapData::DateTime(converted)), + ))) +} + +/// CPython finds a naive value's local offset by rendering the days either side +/// of it, so the first and last representable days raise before any conversion +/// happens — in every zone, including UTC. Monty needs no such probe, but the +/// error is observable, so it is reproduced. +fn probe_neighbouring_days(date: NaiveDate) -> RunResult<()> { + // chrono's own range is far wider than Python's, so the years are what decide. + let in_range = |day: Option| day.is_some_and(|day| year_in_python_range(day.year())); + if !in_range(date.pred_opt()) { + Err(date::year_out_of_range(0)) + } else if !in_range(date.succ_opt()) { + Err(date::year_out_of_range(10_000)) + } else { + Ok(()) + } +} + +/// Argument shape for `datetime.astimezone(tz=None)`, checked like [`NowArgs`]: +/// `at_most_total` gives CPython's `astimezone() takes at most 1 argument (2 given)`. +#[derive(FromArgs)] +#[from_args(name = "astimezone", at_most_total)] +struct AstimezoneArgs { + #[from_args(default = Value::None)] + tz: Value, +} + +/// Reads the session clock in UTC; `None` means `CallHost` and requires suspension. +/// Unrepresentable fixed instants raise `OverflowError` for all three clock calls. +pub(crate) fn sandbox_instant(vm: &VM<'_>) -> RunResult> { + match vm.env.os_policy.datetime { + DateTimeSource::CallHost => Ok(None), + source => source.read().map(Some).ok_or_else(date_out_of_range), + } +} + +/// Converts UTC to the session zone's wall clock for naive `now()` and `today()`; +/// out-of-range years raise `OverflowError`. +pub(crate) fn sandbox_local_wall_clock(vm: &VM<'_>, utc: NaiveDateTime) -> RunResult { + let offset = vm.env.os_policy.timezone.at(utc).offset_seconds; + local_wall_clock(utc, offset).ok_or_else(date_out_of_range) +} + +fn date_out_of_range() -> RunError { + SimpleException::new_msg(ExcType::OverflowError, DATE_OUT_OF_RANGE).into() +} + +/// Argument shape for `datetime.now(tz=None)`. +/// +/// `tz` stays a raw [`Value`] so the None-or-timezone check runs in the body +/// (`tzinfo_from_value`) with CPython's tzinfo wording. `at_most_total` +/// matches CPython's `PyArg_ParseTupleAndKeywords` pre-count: a duplicate tz +/// (`now(utc, tz=utc)`) reports "takes at most 1 argument (2 given)". +#[derive(FromArgs)] +#[from_args(name = "now", at_most_total)] +struct NowArgs { + #[from_args(default = Value::None)] + tz: Value, +} + +/// Classmethod `datetime.strptime(date_string, format)`. +/// +/// Parses a date/time string using the given format. Delegates to chrono's +/// `NaiveDateTime::parse_from_str`, expanding Python `%f` directives into the +/// chrono widths needed to accept 1 through 6 fractional digits. +pub(crate) fn class_strptime(heap: &mut Heap, args: ArgValues, interns: &Interns) -> RunResult { + let (date_string_val, format_val) = args.get_two_args("datetime.strptime", heap)?; + + let date_string = date::extract_str_arg(&date_string_val, "strptime", heap, interns); + let fmt = date::extract_str_arg(&format_val, "strptime", heap, interns); + date_string_val.drop_with(heap); + format_val.drop_with(heap); + let date_string = date_string?; + let fmt = fmt?; + + reject_bad_strptime_directive(&fmt)?; + + // Python's `%f` accepts 1..=6 digits and right-pads with zeros, while chrono + // requires an explicit width. Try all valid `%f` widths before reporting a + // mismatch so `datetime.strptime(..., '%f')` matches CPython. + let Some(parsed) = parse_strptime(&date_string, &fmt) else { + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("time data '{date_string}' does not match format '{fmt}'"), + ) + .into()); + }; + let (naive, offset_seconds) = parsed?; + + if !year_in_python_range(naive.date().year()) { + return Err(SimpleException::new_msg(ExcType::ValueError, "year is out of range").into()); + } + if let Some(offset_seconds) = offset_seconds { + timezone::check_offset_seconds(offset_seconds)?; + } + + let dt = DateTime { + naive, + offset_seconds, + timezone_name: None, + tzinfo_ref: None, + }; + Ok(Value::Ref(heap.allocate(HeapData::DateTime(dt)))) +} + +/// CPython's `strptime` has no `%:z`, so the `:` reads as a directive of its own. +/// Monty's `strftime` does accept `%:z`, which makes silently parsing it here the +/// wrong kind of asymmetry. +fn reject_bad_strptime_directive(fmt: &str) -> RunResult<()> { + let mut chars = fmt.chars(); + while let Some(ch) = chars.next() { + if ch == '%' + && let Some(next) = chars.next() + && next == ':' + { + return Err(SimpleException::new_msg( + ExcType::ValueError, + format!("'{next}' is a bad directive in format '{fmt}'"), + ) + .into()); + } + } + Ok(()) +} + +/// Classmethod `datetime.fromisoformat(date_string)`. +/// +/// Parses ISO 8601 datetime strings. Supports the following formats: +/// - `YYYY-MM-DD` (date only, time defaults to midnight) +/// - `YYYY-MM-DDTHH:MM` or `YYYY-MM-DD HH:MM` +/// - `YYYY-MM-DDTHH:MM:SS` or `YYYY-MM-DD HH:MM:SS` +/// - `YYYY-MM-DDTHH:MM:SS.ffffff` +/// - Any of the above with `+HH:MM` or `+HH:MM:SS` timezone suffix +pub(crate) fn class_fromisoformat(heap: &mut Heap, args: ArgValues, interns: &Interns) -> RunResult { + let value = args.get_one_arg("datetime.fromisoformat", heap)?; + let s = date::extract_str_arg(&value, "fromisoformat", heap, interns); + value.drop_with(heap); + let s = s?; + + let dt = parse_iso_datetime(&s, heap) + .ok_or_else(|| SimpleException::new_msg(ExcType::ValueError, format!("Invalid isoformat string: '{s}'")))?; + + Ok(Value::Ref(heap.allocate(HeapData::DateTime(dt)))) +} + +/// `datetime.combine(date, time, tzinfo=self.tzinfo)`. +/// +/// The `date` argument may itself be a `datetime` (CPython makes `datetime` a +/// `date` subclass), in which case only its date part is used. The result takes +/// the time's timezone unless a third argument overrides it; passing `None` +/// explicitly is how CPython drops an aware time's zone. +pub(crate) fn class_combine(vm: &mut VM<'_>, args: ArgValues) -> RunResult { + let CombineArgs { date, time, tzinfo } = CombineArgs::from_args(args, vm)?; + defer_drop!(date, vm); + defer_drop!(time, vm); + // Guarded before the two type checks below, since both can fail while + // holding the caller's `tzinfo` reference. + defer_drop!(tzinfo, vm); + + let date_part = combine_date_part(date, vm)?; + let time_part = combine_time_part(time, vm)?; + + // Absent keeps the time's zone; present (including `None`) replaces it. + // Either way the zone is borrowed, so the guard above has to outlive + // `combine_allocate` — which takes its own ref via `from_components`. + match tzinfo.as_ref() { + None => { + let tz = (time::attached_timezone(&time_part, vm.heap), time_part.tzinfo_ref()); + combine_allocate(vm, date_part, &time_part, tz) + } + Some(tzinfo) => { + let tz = tzinfo_from_value(tzinfo, vm.heap, vm.interns)?; + combine_allocate(vm, date_part, &time_part, tz) + } + } +} + +/// Allocates the `datetime` `combine` returns, given its resolved parts. +fn combine_allocate( + vm: &mut VM<'_>, + (year, month, day): (i32, i32, i32), + time: &Time, + (tz, tz_ref): (Option, Option), +) -> RunResult { + let (hour, minute, second, microsecond) = time.components_i32(); + let combined = from_components(year, month, day, hour, minute, second, microsecond, tz, tz_ref, vm.heap)?; + Ok(Value::Ref(vm.heap.allocate(HeapData::DateTime(combined)))) +} + +/// Argument shape for `datetime.combine(date, time, tzinfo=self.tzinfo)`. +/// +/// Every field stays a raw [`Value`] so the type checks run in the body with +/// CPython's own wording (`combine() argument 1 must be datetime.date, not +/// str`, and the shared `tzinfo argument must be ...` message). +#[derive(FromArgs)] +#[from_args(name = "combine", style = c_named, at_most_total)] +struct CombineArgs { + date: Value, + time: Value, + // `Option` keeps "omitted" (inherit the time's zone) distinct from an + // explicit `tzinfo=None` (make the result naive). + #[from_args(default)] + tzinfo: Option, +} + +/// Extracts `(year, month, day)` from `combine`'s first argument. +fn combine_date_part(date: &Value, vm: &mut VM<'_>) -> RunResult<(i32, i32, i32)> { + let naive = match date { + Value::Ref(id) => match vm.heap.get(*id) { + HeapData::Date(d) => Some(d.0), + HeapData::DateTime(dt) => Some(dt.naive.date()), + _ => None, + }, + _ => None, + }; + let naive = naive.ok_or_else(|| { + ExcType::type_error_bad_arg_pos( + "combine", + 1, + "datetime.date", + date.py_type_heap(vm.heap).cpython_arg_name(vm.heap, vm.interns), + ) + })?; + Ok(( + naive.year(), + i32::try_from(naive.month()).expect("month in 1..12"), + i32::try_from(naive.day()).expect("day in 1..31"), + )) +} + +/// Extracts the `Time` from `combine`'s second argument. +/// +/// The clone shares the original's `tzinfo_ref` without taking a reference to +/// it, so it is only safe while the caller's guard keeps the source `time` +/// alive — which is exactly how long [`class_combine`] uses it. +fn combine_time_part(time: &Value, vm: &mut VM<'_>) -> RunResult